Существует множество руководств по простому копированию ключа SSH, но ни одно из них не проверяет, существует ли ключ удаленно. Это должно работать:
cat ~/.ssh/id_rsa.pub | ssh -p <port> <user>@<hostname> 'sh -c "if ( ! grep -q '`cat -`' ~/.ssh/authorized_keys); then cat - >>~/.ssh/authorized_keys; fi"'
В cat -
внутри grep не интерполируется в одну строку, а в 3, и это все отбрасывает. Я сделал это на Ruby, и он работает, но не идеально. Есть ли где-нибудь про Bash?
Net::SSH.start(<host>, <username>, :password => <password>, :port => <port>) do |ssh|
local_public_key = `cat ~/.ssh/id_rsa.pub`.chomp
ssh.exec! %{
if ( ! grep -q '#{local_public_key}' ~/.ssh/authorized_keys ); then echo '#{local_public_key}' >> ~/.ssh/authorized_keys; fi
}
Просто используйте переменную, например:
KEY=$(cat ~/.ssh/id_rsa.pub) ssh -p <port> <user>@<hostname> "if [ -z \"\$(grep \"$KEY\" ~/.ssh/authorized_keys )\" ]; then echo $KEY >> ~/.ssh/authorized_keys; echo key added.; fi;"
Почему бы просто не использовать ssh-copy-id?
НАЗВАНИЕ
ssh-copy-id -- copy public keys to a remote host
ОБЗОР
ssh-copy-id [-lv] [-i keyfile] [-o option] [-p port] [user@]hostname
ОПИСАНИЕ
The ssh-copy-id utility copies public keys to a remote host's ~/.ssh/authorized_keys file (creating the file and directory, if required). The following options are available: -i file Copy the public key contained in file. This option can be speci- fied multiple times and can be combined with the -l option. If a private key is specified and a public key is found then the pub- lic key will be used. -l Copy the keys currently held by ssh-agent(1). This is the default if the -i option was not specified. -o ssh-option Pass this option directly to ssh(1). This option can be speci- fied multiple times. -p port Connect to the specified port on the remote host instead of the default. -v Pass -v to ssh(1). The remaining arguments are a list of remote hosts to connect to, each one optionally qualified by a user name.
СТАТУС ВЫХОДА
The ssh-copy-id utility exits 0 on success, and >0 if an error occurs.
ПРИМЕРЫ
To send a specific key to multiple hosts: $ ssh-copy-id -i /path/to/keyfile.pub user@host1 user@host2 user@host3
Возможно, старый вопрос, но вы также можете выполнить:
ssh -q -o "BatchMode=yes" user@hostname exit
Что, если ssh-copy-id уже произошло, завершится успешно и вернет 0. Если не вернет ошибку.