2017-04-03 47 views
0

我正在使用子进程将ssh会话连接到远程主机以执行多个命令。在一个进程中用于多个命令的python子进程

我当前的代码:

import subprocess 
import sys 

HOST="[email protected]" 
# Ports are handled in ~/.ssh/config since we use OpenSSH 
COMMAND1="network port show" 
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND1], 
        shell=False, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE) 
result = ssh.stdout.readlines() 
if result == []: 
    error = ssh.stderr.readlines() 
    print >>sys.stderr, "ERROR: %s" % error 
else: 
     resp=''.join(result) 
     print(resp) 
COMMAND2="network interface show" 

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND2], 
        shell=False, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE) 
result = ssh.stdout.readlines() 
if result == []: 
    error = ssh.stderr.readlines() 
    print >>sys.stderr, "ERROR: %s" % error 
else: 
    resp=''.join(result) 
    print(resp) 

在上述情况下,我的代码要我输入密码两次。

但我想要的是密码应该问一次和多个命令必须执行。

请帮

+0

[Python的子 - 通过SSH运行多个外壳命令]的可能的复制(http://stackoverflow.com/questions/19900754/python-subprocess-run-multiple-壳命令-过SSH) –

回答

2

您正在打开在你的代码两种连接方式,所以很自然,你必须输入两次密码。

相反,您可以打开一个连接并传递多个远程命令。

from __future__ import print_function,unicode_literals 
import subprocess 

sshProcess = subprocess.Popen(['ssh', 
           <remote client>], 
           stdin=subprocess.PIPE, 
           stdout = subprocess.PIPE, 
           universal_newlines=True, 
           bufsize=0) 
sshProcess.stdin.write("ls .\n") 
sshProcess.stdin.write("echo END\n") 
sshProcess.stdin.write("uptime\n") 
sshProcess.stdin.write("echo END\n") 
sshProcess.stdin.close() 

看到here更多细节