Thursday, January 19, 2012

Script to execute given command on multiple remote hosts


Script is use to execute any command on multiple remote hosts.


#runcmd --help
Usage: runcmd -u "username" -d "domain" -s "servers1,server2" -c "command"

Options:
  -h, --help            show this help message and exit
  -s SERVER, --server=SERVER
                        servers to update
  -u USER, --user=USER  user name
  -d DOMAIN, --domain=DOMAIN
                        domain name
  -c COMMAND, --command=COMMAND
                        remote command to execute
  -v, --verbose         verbose


Copy paste following in "runcmd" and make sure that file is in executable mode.

#!/usr/bin/python
#Auther: Prasad Wani
#This script will execute the given command on any remote server
#


import commands
from optparse import OptionParser
import pexpect
import os
import getpass
import paramiko
import ConfigParser
import sys


usage = 'usage: %prog -u "username" -d "domain" -s "servers1,server2" -c "command"'
parser = OptionParser(usage)
parser.add_option('-s', '--server', dest='server', help='servers to update')
parser.add_option('-u', '--user', dest='user', default='prasad', help='user name')
parser.add_option('-d', '--domain', dest='domain', default='sjc2', help='domain name')
parser.add_option('-c', '--command', dest='command', help='remote command to execute')
parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='verbose')


options, args = parser.parse_args()
if not len(sys.argv) > 1:
  parser.error("Some required options are missing, please run 'runcmd --help'")


hosts = options.server
hosts = hosts.split(',')


username = options.user
password = getpass.getpass(prompt="\033[34m"'Please enter the password for user'+' '+username+':'"\033[0m")


def verify_password (host, username):
   global password
   try:
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, 22, username, password)
    ssh.close()
   except paramiko.AuthenticationException:
    print "\033[31m""Error: Authentication Failed""\033[34m"
    password    =   getpass.getpass(prompt="\033[34m"'Please enter the password for user'+' '+username+':'"\033[0m")
    verify_password(host, username)


for host in hosts:
            host = host.strip()+"."+options.domain+".com"
   print host
   ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host, 22, username, password)
   print options.command
            stdin, stdout, stderr = ssh.exec_command(options.command)
            print "------------"
            print stdout.read()
            ssh.close()