简体   繁体   English

与SSH一起使用subprocess.popen-python

[英]using subprocess.popen with ssh - python

i'm trying to run a python script from host to some clients via subprocess.popen. 我正在尝试通过subprocess.popen从主机向某些客户端运行python脚本。 The command is sort of fire and forget and the process in the clients should run for an unlimited time untill i kill it. 该命令是一发不可收拾的,并且客户端中的进程应无限期运行,直到我杀死它为止。 the problem is - when i run this line in python the process run on the clients for an hour and then suddenly stops after 1 hour and 2 minutes : 问题是-当我在python中运行此行时,进程在客户端上运行了一个小时,然后在1小时2分钟后突然停止:

subprocess.Popen(["rsh {} {} {}".format(ipClient,command,args)], shell=True)

where "command" is the path and the command in the clients. 其中“命令”是客户端中的路径和命令。 and when i simply run rsh 'ip' 'command' 'args' in the shell it works as expected and does not stop suddenly. 当我在外壳中简单地运行rsh 'ip' 'command' 'args'时,它可以按预期工作并且不会突然停止。

any idea? 任何想法?

While subprocess.Popen might work for wrapping ssh access, this is not the preferred way to do so. 尽管subprocess.Popen可能用于包装ssh访问,但这不是首选的方法。

I recommend using paramiko . 我建议使用paramiko

import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(server, username=user,password=password)
...
ssh_client.close()

And If you want to simulate a terminal, as if a user was typing: 如果要模拟终端,就好像用户正在键入:

chan=self.ssh_client.invoke_shell()

def exec_cmd(cmd):
    """Gets ssh command(s), execute them, and returns the output"""
    prompt='bash $' # the command line prompt in the ssh terminal
    buff=''
    chan.send(str(cmd)+'\n')
    while not chan.recv_ready():
        time.sleep(1)
    while not buff.endswith(prompt):
        buff+=self.chan.recv(1024)
    return buff[:len(prompt)]

Example usage: exec_cmd('pwd') 用法示例: exec_cmd('pwd')

If you don't know the prompt in advance, you can set it with: 如果您不预先知道提示,可以使用以下命令进行设置:

chan.send('PS1="python-ssh:"\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM