Unable to see ifconfig output using paramiko

孤者浪人 提交于 2019-12-10 11:06:44

问题


I am using below code to execute commands on a remote machine,

import paramiko
import os
dssh = paramiko.SSHClient()
dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dssh.connect('192.168.1.5', username='root', password='asdfghhh')

import os

stdin, stdout, stderr = dssh.exec_command('ls')
print stdout.read()
stdin, stdout, stderr = dssh.exec_command('ifconfig')
print stdout.read()
stdin, stdout, stderr = dssh.exec_command('ps')
print stdout.read()
dssh.close()

when I execute the program, Its able to show the ls and ps as well as other commands output. however ifconfig o/p is not observed.

any idea how to solve this problems? Thanks in advance...


回答1:


There is a chance your server discriminates between interactive and non-interactive SSH sessions, and that different startup scripts are run for the different sessions. Try to run echo $PATH on the remote host through the paramiko SSH session and a regular interactive one and compare the outputs.

For a workaround you can do a which ifconfig on the remote server in an interactive session to get the absolute path and use that in your paramiko command.

stdin, stdout, stderr = dssh.exec_command('/abs/path/to/ifconfig')

NOTE On one of my hosts the result of echo $PATH from the paramiko SSH client was /usr/bin:/bin, while in an interactive session it was /usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin, and ifconfig was indeed located in /usr/sbin, i.e. outside the path of the paramiko session.




回答2:


To get the output for certain application binaries you must use the flag: get_pty=True

I'm still looking for the reason it happens for some commands, it's for me unknown yet. However the way I found to workaround this problem is shown in the example below:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('10.2.0.230', username='ibmsys1', password='passw0rd', timeout=5)
stdin, stdout, stderr = ssh.exec_command('/sbin/ifconfig', timeout=3, get_pty=True)

print stdout.read()

Usually I would run: #stdin, stdout, stderr = ssh.exec_command('/sbin/ifconfig')

in my example, I've just added 2 new flags, timeout=3 and get_pty=True This solved my problem. The timeout flag is not related, however I always use it as good practice. The point here is the use of the get_pty=True PS. I would recommend do not trust on the system $PATH, always input the full path for the application to be run, e.g: /usr/bin/my_binary or in your case /sbin/ifconfig

I hope this may help you to workaround the problem. Good luck!



来源:https://stackoverflow.com/questions/17827399/unable-to-see-ifconfig-output-using-paramiko

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