After executing a command by Python Paramiko how could I save result?

谁说胖子不能爱 提交于 2020-01-09 04:59:24

问题


As you see below, is it possible to save the result? Cause, at second and third stdout.read() I couldn't reach the result.

import paramiko
import os
dssh = paramiko.SSHClient()
dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dssh.connect('192.168.1.250', username='root', password='pass')
import os
stdin, stdout, stderr = dssh.exec_command('ifconfig')
print stdout.read()
print ('Sleeping 2 seconds!')
os.system('sleep 2')
stdin, stdout, stderr = dssh.exec_command('ls -l')
print stdout.read()
print stdout.read()
print stdout.read()
dssh.close()

回答1:


Imagine that stdout is an ordinary file. What do you expect to get if you call file.read() the second time? -- nothing (empty string) unless the file has changed outside.

To save the string:

output = stdout.read()

You might find Fabric simpler to use (it uses paramiko to execute commands under the hood).




回答2:


You can try this Generic API

def ssh_ctrl(ip, user, password,cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(hostname=ip, username=user, password=password, timeout=tout, compress = True,look_for_keys=False, allow_agent=False)
    except (socket.error,paramiko.AuthenticationException,paramiko.SSHException) as message:
        print "ERROR: SSH connection to "+ip+" failed: " +str(message)
        sys.exit(1)

    stdin, stdout, ssh_stderr = ssh.exec_command(cmd)
    out = stdout.read()
    stdin.flush()
    ssh.close()
    return out


来源:https://stackoverflow.com/questions/8138241/after-executing-a-command-by-python-paramiko-how-could-i-save-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!