如果本地 SSH 密钥不存在,则将其复制到远程主机

如果本地 SSH 密钥不存在,则将其复制到远程主机

有很多教程可以简单地复制 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"'

grep内部cat -没有插入单个字符串,而是 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
    }

答案1

只需使用一个变量,如下所示:

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;"

答案2

为什么不直接使用ssh-复制-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

答案3

这可能是老问题,但您也可以执行:

ssh -q -o "BatchMode=yes" user@hostname exit

如果 ssh-copy-id 已经发生,则会成功并返回 0。如果没有,则返回错误。

相关内容