[英]using subprocess.popen with ssh - python
我正在嘗試通過subprocess.popen從主機向某些客戶端運行python腳本。 該命令是一發不可收拾的,並且客戶端中的進程應無限期運行,直到我殺死它為止。 問題是-當我在python中運行此行時,進程在客戶端上運行了一個小時,然后在1小時2分鍾后突然停止:
subprocess.Popen(["rsh {} {} {}".format(ipClient,command,args)], shell=True)
其中“命令”是客戶端中的路徑和命令。 當我在外殼中簡單地運行rsh 'ip' 'command' 'args'
時,它可以按預期工作並且不會突然停止。
任何想法?
盡管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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.