我在 ubuntu 20.04 上,我正在运行一个 bash 脚本,我想将其移植到我的其他服务器上,但我无法同时用变量替换身份文件和 ssh_username,否则会出现 pubkey 错误。
首先我用来shellcheck.net
验证我的基本语法是否正确
#!/bin/bash
source_ssh_user="admin"
source_ssh_host="123.456.789.12"
connecting_keyfile="/home/username/.ssh/id_my_rsa"
#this does NOT work, but it should:
ssh -i $connecting_keyfile $source_ssh_user@$source_ssh_host
当我将-vvv
标志添加到命令时,它会验证是否向服务器提供了正确的 ssh 密钥文件:
...
...
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /home/username/.ssh/id_my_rsa RSA SHA256:UXXXXXXXXUx/w1dY explicit agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering public key: /home/username/.ssh/id_my_rsa RSA SHA256:UGKOXXXXXXXXXx/w1dY explicit
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
[email protected]: Permission denied (publickey).
奇怪之处:
当我用这个命令替换上面的命令时,明确定义用户名,那么相同的密钥文件变量就可以完美运行
ssh -p22 -i $connecting_keyfile username@$source_ssh_host
问题:
似乎当我用变量替换 ssh_username 时,管理我的密码的 ssh-agent 不知何故失去了发送密码凭证的能力
为了管理我的密码,我在 .bashrc 中有以下内容:
#Add passphrase to ssh-agent
SSH_ENV="$HOME/.ssh/agent-environment"
function start_agent {
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
}
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
#ps ${SSH_AGENT_PID} doesn't work under cywgin
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
这在我的~/.ssh/config
Host *
AddKeysToAgent yes
User username
Port 22
IdentityFile /home/username/.ssh/id_my_rsa