Wednesday 20 June 2012

python script to connect to linux servers and run a command

This is a sloppy script I wrote to get a job done. The job was to collect the host name, list of users and the wheel group from a list of linux servers. It could be easily edited to run other commands. You need to have your password set the same on each server. My username is hard coded. You also need to have a list of servers in /data/servers.txt

import os

# Read servers in from file
f = file("./data/servers.txt","r")
servers = []
servers = f.readlines()

# set up commands to use later
cmd1 = 'hostname'
cmd2 = 'cat /etc/passwd | sort'
cmd3 = 'grep wheel /etc/group'
sshcmd = 'ssh -p 22 user.name@'

# Loop through the list of servers, connect to each and run the commands that were setup above
for x in servers:
        x = x.rstrip()
        one = sshcmd + x + " " + cmd1 + " >> " + x + ".txt"
        runone = os.system(one)
        print runone

        two = sshcmd + x + " " + cmd2 + " | cut -d: -f 1,3,6 | grep \"[5-9][0-9][0-9]\" | cut -d: -f1 >> " + x + ".txt"
        print two
        runtwo = os.system(two)
        print runtwo

        three = sshcmd + x + " " + cmd3 + " >> "+x+".txt"
        runthree = os.system(three)
        print runthree

An alternative to this would be to use cssh, but that was not available to me.

No comments:

Post a Comment