0

我正在尝试通过 subprocess.popen 从主机到某些客户端运行 python 脚本。该命令有点像一劳永逸,客户端中的进程应该无限运行,直到我杀死它。问题是 - 当我在 python 中运行这条线时,进程在客户端上运行一个小时,然后在 1 小时 2 分钟后突然停止:

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

其中“command”是客户端中的路径和命令。当我只是 rsh 'ip' 'command' 'args' 在 shell 中运行时,它会按预期工作并且不会突然停止。

任何想法?

4

1 回答 1

0

虽然subprocess.Popen可能适用于包装ssh访问,但这不是这样做的首选方式。

我建议使用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()

如果你想模拟一个终端,就好像用户正在输入:

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)]

示例用法:exec_cmd('pwd')

如果你事先不知道提示,你可以这样设置:

chan.send('PS1="python-ssh:"\n')
于 2015-08-25T07:11:33.743 回答