Monday, October 21, 2013

Python in Action: Paramiko handling ssh connection

I came across the ssh interactive session from bash long time ago using the expect. But, this morning I am exploring paramiko, and start to draft a stupid easy codes to test out the library. It is clean and blazing fast. Hope this small chunks of codes can get you started with all the complicated paramiko codes.

#!/usr/bin/python                                                          
import os                                                                  
import paramiko                                                            
import getpass                                                             
                                                                            
user=os.getlogin()                                                         
print "Connecting via %s: what is your password?" % user                   
pw = getpass.getpass()                                                     
ssh = paramiko.SSHClient()                                                 
#ssh.load_host_keys()                                                      
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())                  
ssh.connect('centos64-1', username=user, password=pw)                      
stdin, stdout, stderr = ssh.exec_command('uname -a')                       
print "output", stdout.read()                                              
ssh.close() 


 
After a day so, I feel like I want to do a little of enhancement out of it. So, I recode it something like below. Still feeling it is not as neath as I love to. But, overall it can carry out the work.

#!/usr/bin/python
import os
import paramiko
import getpass
import socket

def get_credential():
    user=os.getlogin()
    print "Connecting via [%s]: what is your password?" % user
    pw = getpass.getpass()
    return (user, pw)

def ssh_connect():
    (user, pw) = get_credential()
    try:
        ssh = paramiko.SSHClient()
        #ssh.load_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect('centos64-1', username=user, password=pw)
        stdin, stdout, stderr = ssh.exec_command('uname -a')
        print "output: ", stdout.read()
        ssh.close()
    except paramiko.SSHException, e:
        print "Password is invalid:" , e
    except paramiko.AuthenticationException:
        print "Authentication failed for some reason"
    except socket.error, e:
        print "Socket connection failed:", e

def main():
    ssh_connect() 


if __name__ == '__main__':                                                    
    main()                 



After a day so, I have done some polishing on the same codes. Now, it can accept a list of target hosts with a comma delimiter. Then, the script will be connecting to target hosts one by one. Feel free to copy/use it. Thanks!

#!/usr/bin/python
import os
import paramiko
import getpass
import socket

def get_host():
    target_host = []
    input = raw_input("What is your target host? ")
    for item in input.split(","):
        target_host.append(item.strip())
    return target_host

def get_credential():
    pw = ""
    user=os.getlogin()
    print "Connecting via [%s]: what is your password?" % user
    while not pw:
        pw = getpass.getpass()
    return (user, pw)


def ssh_connect():
    target_host = get_host()
    (user, pw) = get_credential()

    ssh = paramiko.SSHClient()
    #ssh.load_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    for h in target_host:
        try:
            print "Connecting to %s ..." % h
            ssh.connect(h, username=user, password=pw)
            stdin, stdout, stderr = ssh.exec_command('uname -a')
            print "%s>" % h,stdout.read()
        except paramiko.SSHException, e:
            print "Password is invalid:" , e
        except paramiko.AuthenticationException:
            print "Authentication failed for some reason"
        except socket.error, e:
            print "Socket connection failed on %s:" % h, e
    ssh.close()
def main():
    ssh_connect()

if __name__ == '__main__':                                                    
    main()



Here is the output that I got.

hiuy@nasilemak ~ $ ./pyssh.py
What is your target host? centos64-1, centos64-2
Connecting via [hiuy]: what is your password?
Password:
Connecting to centos64-1 ...
centos64-1> Linux centos64-1.hiu.com 2.6.32-358.18.1.el6.x86_64 #1 SMP Wed Aug 28 17:19:38 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Connecting to centos64-2 ...
centos64-2> Linux localhost.localdomain 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

2 comments:

Anonymous said...

Thank you for some other geeat article. Where elsze couuld anybody
get that type of information in such an ideal means of writing?
I have a presentation subsequent week, and I am on the search for such info.


My blog Spanish Grammar Checklist

Luis Giner said...

Just wanted to thank you for writing this up. Really help me.

Thank you.