[英]subprocess.popen seems to fail when run from crontab
I'm running a script from crontab that will just ssh and run a command and store the results in a file. 我正在从crontab运行脚本,它将仅ssh并运行命令并将结果存储在文件中。
The function that seems to be failing is subprocess.popen
. 似乎失败的功能是subprocess.popen
。
Here is the python function: 这是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
When it's run from the command line, it executes correctly, from cron it seems to fail with the error message below. 从命令行运行时,它可以正确执行,从cron看来似乎失败,并显示以下错误消息。
Here are the crontab entries: 以下是crontab条目:
02 * * * * /home/matt/scripts/check-diskspace.py >> /home/matt/logs/disklog.log
Here are the errors: 以下是错误:
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)
I'm going blind trying to find exactly where I have gone so wrong. 我盲目地试图找出我哪里错了。 Any ideas? 有任何想法吗?
The cron PATH is very limited. cron路径非常有限。 You should either set absolute path to your ssh /usr/bin/ssh or set the PATH as a first line in your crontab. 您应该将ssh / usr / bin / ssh设置为绝对路径,或者将PATH设置为crontab中的第一行。
You probably need to pass ssh the -i argument to tell ssh to use a specific key file. 您可能需要通过ssh -i参数来告诉ssh使用特定的密钥文件。 The problem is that your environment is not set up to tell ssh which key to use. 问题是您的环境未设置为告诉ssh使用哪个密钥。
The fact that you're using python here is a bit of a red herring. 您在这里使用python的事实有点让人讨厌。
For everything ssh-related in python, you might consider using paramiko . 对于python中与ssh相关的所有内容,您可以考虑使用paramiko 。 Using it, the following code should do what you want. 使用它,下面的代码应该可以实现您想要的。
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()
When running python scripts from cron, the environment PATH
can be a hangup, as user1652558 points out. 从cron运行python脚本时,用户1652558指出,环境PATH
可能是挂断。
To expand on this answer with example code to add custom PATH
values to the environment for a subprocess
call: 要使用示例代码扩展此答案,以将自定义PATH
值添加到环境中以进行subprocess
调用:
import os
import subprocess
#whatever user PATH values you need
my_path = "/some/custom/path1:/some/custom/path2"
#append the custom values to the current PATH settings
my_env = os.environ.copy()
my_env["PATH"] = my_path + ":" + my_env["PATH"]
#subprocess call
resp = subprocess.check_output([cmd], env=my_env, shell=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.