【发布时间】:2012-05-31 11:43:32
【问题描述】:
我是 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 时工作正常。我找到了一个 invoke_shell 示例Nested SSH session with Paramiko。我对此解决方案不满意,因为如果服务器的提示未在我的脚本中指定-> 无限循环或脚本中指定的提示是返回文本中的字符串-> 并非所有数据都将被接收.有没有更好的解决方案,比如在我的脚本中将 stdout 和 stderr 发回?
【问题讨论】:
-
请注意,此答案不使用 SSH 密钥,因此需要密码。使用 SSH 密钥,您不需要 pw,而是传递 key_filename 参数。