我是Python的新手。我编写了一个脚本来连接到主机并执行一条命令。
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=pw)
print 'running remote command'
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for line in stdout.read().splitlines():
print '%s$: %s' % (host, line)
if outfile != None:
f_outfile.write("%s\n" %line)
for line in stderr.read().splitlines():
print '%s$: %s' % (host, line + "\n")
if outfile != None:
f_outfile.write("%s\n" %line)
ssh.close()
if outfile != None:
f_outfile.close()
print 'connection to %s closed' %host
except:
e = sys.exc_info()[1]
print '%s' %e
当远程命令不需要tty时,这段代码可以正常工作。我在Paramiko中嵌套SSH会话找到了一个invoke_shell示例。但是我对这个解决方案不太满意,因为如果服务器上有一个未在我的脚本中指定的提示符,则会导致无限循环;或者,如果脚本中指定的提示符是返回文本中的字符串,则可能收不到所有数据。也许有更好的解决方案,可以像我的脚本一样将标准输出和标准错误发送回来吗?