Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to see ifconfig output using paramiko

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...

like image 986
neo Avatar asked Mar 23 '23 02:03

neo


2 Answers

Your server may be discriminating between interactive and non-interactive SSH sessions, running different startup scripts for the different sessions. Try running 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.

like image 188
Henrik Avatar answered Mar 25 '23 17:03

Henrik


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!

like image 31
Aislan Diego Avatar answered Mar 25 '23 16:03

Aislan Diego