我正在使用子进程将ssh会话连接到远程主机以执行多个命令。
我目前的代码:
import subprocess
import sys
HOST="admin@10.193.180.133"
# 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 :(得分: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