python paramiko ssh [英] python paramiko ssh

查看:111
本文介绍了python paramiko ssh的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我写了一个脚本来连接到主机并执行一个命令

i'm new on python. i wrote a script to connect to a host and execute one command

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 示例 与 Paramiko 的嵌套 SSH 会话.我对这个解决方案不满意,因为如果服务器有一个未在我的脚本中指定的提示 -> 无限循环或脚本中指定的提示是返回文本中的一个字符串 -> 并非所有数据都将被接收.是否有更好的解决方案,例如在我的脚本中将 stdout 和 stderr 发回?

works fine when then remote command doesn't need a tty. i found an invoke_shell example Nested SSH session with Paramiko. i'm not happy with this solution, because if a server has an prompt that isn't specified in my script -> infinite loop or a specified prompt in the script is a string in the return text -> not all data will be received. is there a better solution maybe where stdout and stderr are send back like in my script?

推荐答案

您可以在以下位置找到大量的 paramiko API 文档:http://docs.paramiko.org/en/stable/index.html

There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html

我使用以下方法在受密码保护的客户端上执行命令:

I use the following method to execute commands on a password protected client:

import paramiko

nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username' 
password = 'password'
command = 'ls'

client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)

stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
    if session.recv_ready():
        stdout_data.append(session.recv(nbytes))
    if session.recv_stderr_ready():
        stderr_data.append(session.recv_stderr(nbytes))
    if session.exit_status_ready():
        break

print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)

session.close()
client.close()

这篇关于python paramiko ssh的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆