subprocess.popen在crontab中运行似乎失败
我在用定时任务(crontab)运行一个脚本,这个脚本会通过ssh连接到另一台机器,执行一个命令,然后把结果存到一个文件里。
看起来出问题的地方是 subprocess.popen
这个函数。
这是我的Python函数:
def _executeSSHCommand(sshcommand,user,node):
'''
Simple function to execute an ssh command on a remote node.
'''
sshunixcmd = '/usr/bin/ssh %s@%s \'%s\'' % (user,node,sshcommand)
process = subprocess.Popen([sshunixcmd],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
process.wait()
result = process.stdout.readlines()
return result
当我从命令行直接运行这个脚本时,一切正常,但从定时任务运行时,似乎就出错了,错误信息如下。
这是我的定时任务设置:
02 * * * * /home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log
这里是错误信息:
Sep 23 17:02:01 timmy CRON[13387]: (matt) CMD (/home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log)
Sep 23 17:02:01 timmy CRON[13386]: (CRON) error (grandchild #13387 failed with exit status 2)
我感觉自己快要看不懂了,不知道哪里出了问题。有没有什么建议?
4 个回答
1
如果你想在Python中处理与ssh相关的事情,可以考虑使用paramiko这个库。用这个库的话,下面的代码应该能实现你想要的功能。
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(node, username=user)
stdout = client.exec_command(ssh_command)[0]
return stdout.readlines()
4
cron的路径设置是很有限的。你要么直接写出ssh的绝对路径,比如/usr/bin/ssh,要么在你的crontab文件的第一行设置好PATH。
2
你可能需要给ssh加上-i这个参数,告诉它使用一个特定的密钥文件。问题是你的环境没有设置好,无法告诉ssh该用哪个密钥。
你在这里使用python其实并不是重点。