Wednesday, August 11, 2010

ssh.py - automating ssh tasks

so part of my learning python has been finding ways to design tools using it that are simpler than just hashing the same functionality out in bash. Yesterday I came across a python ssh module http://media.commandline.org.uk//code/ssh.txt which provides connection handling and a few basic methods for interaction.

Using that, i built a template for executing commands on multiple systems for administrative purposes by processing a list of dictionaries containing the target info and then issuing commands to each connection that's made:

import ssh

a = {'host': '192.168.1.1', 'username': 'myuser', 'password': 'mypass'};
b = {'host': '192.168.1.2', 'username': 'myuser', 'password': 'mypass'};
c = {'host': '192.168.1.3', 'username': 'myuser', 'password': 'mypass'};
d = {'host': '192.168.1.4', 'username': 'myuser', 'password': 'mypass'};

hl = [a,b,c,d]

for x in hl:
        s = ssh.Connection(x['host'], username=x['username'], password=x['password'])
        date = s.execute('date')
        #uptime = s.execute('uptime')
        who = s.execute('w')
        netstat = s.execute('netstat -antp |grep ESTAB')
        print x['host']
        print date[0]
        #print uptime
        for y in who:
                print y
        for z in netstat:
                print z
        print '--------------------------------------------------'
        s.close()

This just returns a few simple bits of information about each box, but it is an excellent template for future uses. Next i need to find a way to hash the passwords or utilize public keys before putting it into use.

0 comments:

Post a Comment