从 cron 使用 ssh 时出现的问题

从 cron 使用 ssh 时出现的问题

我正在尝试自动执行一个脚本,该脚本通过 ssh 在远程计算机上执行命令。我使用 ssh-agent 在计算机之间设置了公钥身份验证。从命令提示符执行时,该脚本运行良好。我怀疑我的问题是 cron 没有启动 ssh-agent,因为它的环境很简陋。这是我将 -v 标志添加到 ssh 时的输出:

debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: gssapi-with-mic
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Offering public key: /home/<user>/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug1: Trying private key: /home/<user>/.ssh/id_dsa
debug1: Next authentication method: password
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
Permission denied, please try again.
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
Permission denied, please try again.
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic,password).

我该如何实现它?谢谢!

答案1

  1. 不要尝试通过 cron 使用 ssh-agent:这样做弊大于利。
    请改用-i identity_filessh(请参阅ssh(1))。
  2. 确保您的密钥没有密码(因为 cron 无法为您输入密码)。
  3. 如果上述方法不起作用,请仔细检查您的权限:SSH 将拒绝接受不安全的身份文件。

答案2

我最终在脚本中启动了 ssh-agent,然后使用以下代码进行 ssh 调用。效果非常好。

PATH=$PATH:$HOME/bin
SSH_ENV="$HOME/.ssh/environment"

function start_agent {
     echo "Initialising new SSH agent..."
     /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
     echo succeeded
     chmod 600 "${SSH_ENV}"
     . "${SSH_ENV}" > /dev/null
     /usr/bin/ssh-add;
}

# Source SSH settings, if applicable

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 


export PATH
unset USERNAME

答案3

也许你更适合使用以下工具功能

相关内容