我发现使用paramiko很难在后台运行一个进程.我用了 :
stdin, stdout, stderr = ssh.exec_command('executefile.py &')
Run Code Online (Sandbox Code Playgroud)
并发现没有发现executefile.py进程正在运行.
然后我尝试使用其他方式包括反斜杠:
stdin, stdout, stderr = ssh.exec_command('executefile.py \&')
Run Code Online (Sandbox Code Playgroud)
这种方法奏效了.有一个实例在机器上运行,但毫不奇怪,它没有在后台运行.我可以知道因为它没有在后台运行,因为代码在此代码之后停留在第二行.它是
all_inf = stdout.readlines()
Run Code Online (Sandbox Code Playgroud)
现在代码不会超出上面的行,除非脚本的进程被杀死.
我正在学习paramiko,任何帮助表示赞赏.
小智 13
我已经尝试了这里和这里描述的所有方法没有成功,最后意识到你需要使用通道而不是直接使用SSHClient来调用exec_command(这在后台不起作用):
client = paramiko.SSHClient()
client.connect(
ip_address, username='root', pkey=paramiko_key, timeout=5)
client.exec_command('python script.py > /dev/null 2>&1 &')
Run Code Online (Sandbox Code Playgroud)
你应该创建和使用一个频道,这在后台工作:
client = paramiko.SSHClient()
client.connect(
ip_address, username='root', pkey=paramiko_key, timeout=5)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command('python script.py > /dev/null 2>&1 &')
Run Code Online (Sandbox Code Playgroud)
所以nohup,dtach,screen等实际上并不是必需的.
你可以试试:
stdin, stdout, stderr = ssh.exec_command('nohup python executefile.py >/dev/null 2>&1 &')
Run Code Online (Sandbox Code Playgroud)
我尝试过transport上课,真的很棒。这是我使用的代码:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = "host_ip", username = "un"], password = "up")
channel = ssh.get_transport().open_session()
pty = channel.get_pty()
shell = ssh.invoke_shell()
shell.send("cd /my/directory/; nohup ./exec_name > /dev/null 2>&1 &\n")
Run Code Online (Sandbox Code Playgroud)
但我仍然不知道如何使用 python 脚本杀死它;我在这里有一个悬而未决的问题。
编辑1:
我已经解决了有关以某种方式终止进程的问题;你可以检查一下。
| 归档时间: |
|
| 查看次数: |
9737 次 |
| 最近记录: |