有很多关于简单的 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"'
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
只需使用一个变量,如下所示:
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;"
Run Code Online (Sandbox Code Playgroud)