[英]Running process of remote SSH server in the background using Python Paramiko
我发现很难在后台使用 Paramiko 在远程 SSH 服务器上运行进程。 我用了 :
stdin, stdout, stderr = ssh.exec_command('executefile.py &')
发现没有运行executefile.py
进程。
然后我尝试使用其他方式包括反斜杠:
stdin, stdout, stderr = ssh.exec_command('executefile.py \&')
这个方法奏效了。 有一个实例在机器上运行,但毫不奇怪,它没有在后台运行。 我可以知道它没有在后台运行,因为代码卡在此代码之后的第二行。 它是
all_inf = stdout.readlines()
现在,除非脚本进程被终止,否则代码不会超出上述行。
我正在学习 Paramiko,任何帮助表示赞赏。
我已经尝试了这里和这里描述的所有方法都没有成功,最后意识到你需要使用通道而不是直接使用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 &')
您应该创建并使用一个频道,这在后台工作:
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 &')
所以nohup
、 dtach
、 screen
等实际上是没有必要的。
你可以试试:
stdin, stdout, stderr = ssh.exec_command('nohup python executefile.py >/dev/null 2>&1 &')
exec_command
不是在交互式 shell 中执行命令,因此“在后台运行进程”实际上没有意义。
如果你真的想这样做,你可以使用命令nohup
来启动你的进程,并在会话退出时让它保持活动状态。 请记住,执行此操作时无法获得 stdin、stdout 或 stderr,因为您将进程与 shell 分离,因此请相应地重定向它们。
我试过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")
但我仍然不知道如何使用 python 脚本杀死它; 我对此有一个悬而未决的问题在这里。
编辑 1:
我以某种方式解决了有关终止进程的问题; 你可以检查一下。
您可以尝试使用屏幕
screen -d -m ping 8.8.8.8
这将启动一个屏幕并ping 8.8.8.8。 您可以使用以下方法查看此屏幕
screen -ls
并附加使用
screen -D <<screen_name>>
请注意,屏幕将在命令执行完成后终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.