为什么 ssh 从 crontab 失败,但从命令行执行时成功? [英] Why ssh fails from crontab but succedes when executed from a command line?

查看:21
本文介绍了为什么 ssh 从 crontab 失败,但从命令行执行时成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 bash 脚本,它对远程机器执行 ssh 并在那里执行命令,例如:

I have a bash script that does ssh to a remote machine and executes a command there, like:

ssh -nxv user@remotehost echo "hello world"

当我从命令行执行命令时,它工作正常,但作为 crontab 的一部分执行时失败(错误代码 = 255 - 无法建立 SSH 连接).详情:

When I execute the command from a command line it works fine, but it fails when is being executed as a part of crontab (errorcode=255 - cannot establish SSH connection). Details:

...
Waiting for server public key.
Received server public key and host key.
Host 'remotehost' is known and matches the XXX host key.
...
Remote: Your host key cannot be verified: unknown or invalid host key.
Server refused our host key.
Trying XXX authentication with key '...'
Server refused our key.
...

在本地执行时,我以 root 身份运行,crontab 也以 root 身份运行.从 crontab 和命令行执行 'id' 给出完全相同的结果:

When executing locally I'm acting as a root, crontab works as root as well. Executing 'id' from crontab and command line gives exactly the same result:

$ id
> uid=0(root) gid=0(root) groups=0(root),...

我从一些本地机器 ssh 到运行 crond 的机器.我有 ssh 密钥和凭据,可以通过 ssh 连接到 crond 机器和脚本连接到的任何其他机器.

I do ssh from some local machine to the machine running crond. I have ssh key and credentials to ssh to crond machine and any other machine that the scripts connects to.

附注.请不要问/抱怨/评论以 root 身份执行任何事情是不好的/错误的/等等——这不是这个问题的目的.

PS. Please do not ask/complain/comment that executing anything as root is bad/wrong/etc - it is not the purpose of this question.

推荐答案

我猜通常当您从本地机器 ssh 到运行 crond 的机器时,您的私钥会加载到 ssh-agent 中并通过连接转发.所以当你从命令行执行命令时,它会在 ssh-agent 中找到你的私钥,并用它来登录远程机器.

I am guessing that normally when you ssh from your local machine to the machine running crond, your private key is loaded in ssh-agent and forwarded over the connection. So when you execute the command from the command line, it finds your private key in ssh-agent and uses it to log in to the remote machine.

crond 执行命令时,它没有访问 ssh-agent 的权限,因此无法使用您的私钥.

When crond executes the command, it does not have access to ssh-agent, so cannot use your private key.

您必须在运行 crond 的机器上为 root 创建一个新的私钥,并将其公共部分复制到您希望 crond 登录的远程机器上相应的 authorized_keys 文件

You will have to create a new private key for root on the machine running crond, and copy the public part of it to the appropriate authorized_keys file on the remote machine that you want crond to log in to.

这篇关于为什么 ssh 从 crontab 失败,但从命令行执行时成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆