有没有办法使用密钥登录来ssh-copy-id
复制另一个密钥,而无需手动编辑~/.ssh/authorized_key
.
手册页中似乎有-o ssh_option
,我尝试传递 -i 选项,但这似乎不起作用。
ssh-copy-id -o "-i ~/.ssh/working-key" -i ~/.ssh/new-key user@ip
答案1
您正在寻找的选项是身份文件但默认情况下它不起作用:ssh-copy-id
这是一个 shell 脚本,期望使用其-i
参数来复制公钥和进行身份验证的私钥,作为检测重复条目创建的方法(注意:如果没有-f
,除了要复制的公钥之外,还必须提供私钥副本才能进行身份验证)。但是-o IdentityFile
覆盖-i
给ssh
内部的参数ssh-copy-id
会让人ssh-copy-id
相信密钥已经被授权,因为它可以在没有密码的情况下连接,并给出最终结果:
$ ssh-copy-id -o 'IdentityFile=.ssh/working-key' -i .ssh/new-key.pub user@ip
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".ssh/new-key.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
Enter passphrase for key '.ssh/working-key':
/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
(if you think this is a mistake, you may want to use -f option)
添加-f
将使其工作(注意:然后不需要私钥的可用性),因为没有检查会失败。运行该命令两次将不再是幂等的:它将再次在远程的authorized_keys
.
这没有被视为问题可能是因为它在ssh-agent
使用时运行良好:如果working-key
在代理中加载(但不是new-key
),ssh-copy-id -i .ssh/new-key.pub user@ip
则将按预期工作。再次运行将检测到重复项。
简而言之:
- 你应该使用
ssh-agent
, 并加载working-key
它, - 否则你可以插入
-f -o IdentifyFile=~/.ssh/working-key
但它不会检测重复项, - 否则,如果需要的话,这里有一个正在运行的包装器
ssh-agent
。
这是一个包装器,它将为您执行此操作:如果它没有找到已经运行的ssh-agent
,它将临时为单个操作生成一个。如果存在,它将被使用(并且添加的密钥将保持添加状态,我希望保持简单)。它将非常简单地处理附加选项:添加的选项 ( -I
) 必须位于第一个(如果存在),然后是其单独的参数,请随意改进它(可能通过使用某种 case 循环)。我还采取了额外的步骤,不询问已加载到可用代理中的密钥的密码(使用这个问答)。
wrapper-ssh-copy-id.sh
:
#!/bin/sh
if [ x"$1" = x-I ]; then
if [ $# -lt 2 ]; then
exit 1
fi
privkeyfile="$2"
shift 2
if [ -z "$SSH_AUTH_SOCK" ]; then
trap 'eval $(ssh-agent -k)' EXIT
eval $(ssh-agent)
fi
fingerprint=$(ssh-keygen -lf "$privkeyfile" | awk '{print $2}')
if [ -z "$fingerprint" ]; then
exit 1
fi
ssh-add -l | grep -F -q "$fingerprint" || ssh-add "$privkeyfile"
fi
ssh-copy-id "$@"