Wednesday, January 18, 2012

Python - Paramiko - Transport to negotiate SSH2 across the connection

Recently i got a task , where i need to connect to linux box,copy some files and run some shell scripts before i am going to validate my UI using selenium in my windows box.
I felt both are good to use
1. Python - paramiko
2. sshxcute

I want to share w.r.t paramiko,as for #2 , there are good examples available in the same site/page.


import paramiko
import ConfigParser
from config import *
import glob
import os
import md5


global ssh
dir_local = 'c:\paramikoLearn'
dir_remote = "/home/test"
filePattern = "*.txt"
 
def connectTo():
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     ssh.connect(HOSTNAME, username=USERNAME, password=PASSWORD)

def closeConnection():
    ssh.close();
   

def copy():

# Get paramiko Transport to negotiate SSH2 across the connection  

    try:
        t = ssh.get_transport()
        print "Start client"
     
        if not t.is_authenticated():
            print "Connect Client"
            t.connect(username=USERNAME, password=PASSWORD)
            t.connect
            print "StartClient successful"
        else:
            sftp = t.open_session()
            print "StartClient successful"
       
        sftp = paramiko.SFTPClient.from_transport(t)
       
        # BETTER: use the get() and put() methods
        # for fname in os.listdir(dir_local):
       
        for  fname in glob.glob(dir_local + os.sep + filePattern):
            is_up_to_date = False
            if fname.lower().endswith('txt'):
                local_file = os.path.join(dir_local, fname)
                remote_file = dir_remote + '/' + os.path.basename(fname)
       
                #if remote file exists
                try:
                    if sftp.stat(remote_file):
                        local_file_data = open(local_file, "rb").read()
                        remote_file_data = sftp.open(remote_file).read()
                        md1 = md5.new(local_file_data).digest()
                        md2 = md5.new(remote_file_data).digest()
                        if md1 == md2:
                            is_up_to_date = True
                            print "UNCHANGED:", os.path.basename(fname)
                        else:
                            print "MODIFIED:", os.path.basename(fname),
                except:
                    print "NEW: ", os.path.basename(fname),
       
                if not is_up_to_date:
                    print 'Copying', local_file, 'to ', remote_file
                    sftp.put(local_file, remote_file)
                   
        t.close()
   
    except Exception as e:
        print '*** Caught exception: %s: %s' % (e.__class__, e)
        try:
            t.close()
        except:
            pass
   
def executeShellScript():
   return ssh.exec_command("ls -l")


if __name__ == '__main__':
   
    ssh = paramiko.SSHClient()
    try:
        connectTo()
        output = executeShellScript()
        print output[1].read()
        closeConnection()
       
    except:
        closeConnection()
    ************
In my junit testscript by using RunTime,Process i was able to run the python script and able to complete the task. :)
   

No comments: