2017-04-03 112 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更多細節