1

I am working on a python script which accepts a command to execute on remote linux. I surfed and found Paramiko. I developed a script which works fine if command like 'who', 'ps', 'ls' is executed. But the same script failed to execute 'top' and 'ping' command. Please help me out from this.

import paramiko
import sys

class sampleParamiko:
    ssh = ""
    def __init__(self, host_ip, uname, passwd):
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(host_ip, username=uname, password=passwd)
            #print "In init function"
        except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException) as e:
            print str(e)
            sys.exit(-1)

    def ececuteCmd(self,cmd):
        try:
            stdin, stdout, stderr = self.ssh.exec_command(cmd)
            out_put = stdout.readlines()
            for item in out_put:
                print item,
        except paramiko.SSHException as e:
            print str(e)
            sys.exit(-1)
host_ip = "10.27.207.62"
uname = "root"
password = "linux"
cmd = str(raw_input("Enter the command to execute in the host machine: "))
conn_obj = sampleParamiko(host_ip, uname, password)
conn_obj.ececuteCmd(cmd)

1 Answer 1

2

You might want to have a look at the invoke_shell() method of paramiko.SSHClient.

From your code, you could do :

import paramiko
import sys

class sampleParamiko:
    ssh = ""
    def __init__(self, host_ip, uname, passwd):
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(host_ip, username=uname, password=passwd)
            #print "In init function"
        except (paramiko.BadHostKeyException, paramiko.AuthenticationException,     paramiko.SSHException) as e:
            print str(e)
            sys.exit(-1)

    def ececuteCmd(self,cmd):
        try:
            channel = self.ssh.invoke_shell()
            timeout = 60 # timeout is in seconds
            channel.settimeout(timeout)
            newline        = '\r'
            line_buffer    = ''
            channel_buffer = ''
            channel.send(cmd + ' ; exit ' + newline)
            while True:
                channel_buffer = channel.recv(1).decode('UTF-8')
                if len(channel_buffer) == 0:
                    break 
                channel_buffer  = channel_buffer.replace('\r', '')
                if channel_buffer != '\n':
                    line_buffer += channel_buffer
                else:
                    print line_buffer
                    line_buffer   = ''
        except paramiko.SSHException as e:
            print str(e)
            sys.exit(-1)
host_ip = "10.27.207.62"
uname = "root"
password = "linux"
cmd = str(raw_input("Enter the command to execute in the host machine: "))
conn_obj = sampleParamiko(host_ip, uname, password)
conn_obj.ececuteCmd(cmd)

Output is :

Jean@MyDesktop:~$ ./test_paramiko.py 
Enter the command to execute in the host machine: ping -c2 127.0.0.1
ping -c2 127.0.0.1 ; exit 
[root@myserver ~]# ping -c2 127.0.0.1 ; exit 
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.032 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.043 ms

--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.032/0.037/0.043/0.008 ms
logout

But you cannot send commands interactively. So if you just ping 127.0.0.1 it will go on forever, until you [CTRL]+[C] or kill your python script. Same for top.

If you want an interactive shell, have a look at the example scripts shipped with paramiko. Especially demos/demo.py and demos/interactive.py

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.