Paramiko启动SSH进程后为何死亡?

2 投票
1 回答
1915 浏览
提问于 2025-04-17 03:14

下面是我的代码。当我登录到服务器并运行命令 ps aux | grep python 时,我看到所有的进程都启动了,然后在一两秒后就结束了。如果我在服务器上直接运行这个命令,它是可以正常工作的。我尝试过用 nohup 和不用 nohup 的方式,但还是找不到原因。这是一个应该要运行几个小时的长时间任务。

key = paramiko.RSAKey.from_private_key_file(rsa_private_key)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,port,username=username,pkey=key)
#stdin, stdout, stderr = ssh.exec_command('tar -xf /home/ubuntu/opt.tar.gz')
stdin, stdout, stderr = ssh.exec_command('ls')
#stdin, stdout, stderr = ssh.exec_command(bash)
stdin, stdout, stderr = ssh.exec_command('ls')
stdin, stdout, stderr = ssh.exec_command('export DISPLAY=localhost:0')
stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('nohup python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &')
stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py &')
ssh.close()

1 个回答

1

试着查看一下命令的输出。可能有错误信息被写入了,但你现在的代码看不到。可以尝试这样做:

stdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py')
print 'exit_code: %d' % stdout.channel.recv_exit_status()
print stdout.read()
print stderr.read()

一旦你找到了问题所在并修复了它,就可以继续使用nohup了。

我觉得问题出在你调用export DISPLAY命令的方式上。这不会影响你运行的其他命令的环境。你需要这样做:

stdin, stdout, stderr = ssh.exec_command('sh -c "export DISPLAY=localhost:0; python /home/ubuntu/Optimization/pvServer2.py"')

撰写回答