remote command on multiple servers with python (V1)

#!/usr/bin/python
import getpass
import sys
import string
import os, time
import pexpect

def print_usage():
print "usage: ./exec.py USERNAME PASSWORD CMD SERVERLIST LOGFILENAME"

def execute(username="root",password="Your Password",cmd="ifconfig",serverlist="serverlist",logfilename="log.txt"):

prompt="^.*\(.*\):|\$"

serverlistfile=open(serverlist)
logfile=open(logfilename,'w')
for servername in serverlistfile:
# try:
servername=servername.strip("\n")
print "Processing "+servername+"..."
sshcmd="ssh root@"+servername+' '+cmd
#print cmd
child=pexpect.spawn(sshcmd)
child.logfile=logfile
child.setecho(False)
print sshcmd
i=-1
print str(i)
while(i!=0):
print str(i)
i=child.expect(['Are you sure you want to continue','password',pexpect.EOF,pexpect.TIMEOUT],1)
print str(i)
if i==0:
child.sendline('yes')
print "answer to ssh key question"
if i==1:
child.sendline(password)
print str(i)
if i==2:
print "end of file met"
i=0
# except pexpect.ExceptionPexpect:
# print ""


if __name__=="__main__":
try:
username=sys.argv[1]
password=sys.argv[2]
cmd=sys.argv[3]
serverlist=sys.argv[4]
logfilename=sys.argv[5]
print username,password,cmd,serverlist,logfilename
execute(username,password,cmd,serverlist,logfilename)
print "unexpected error",sys.exc_info()[0]
print_usage()
except:
print_usage()

Comments

Popular posts from this blog

周末发现的两样东西,和心理有关的。

QStringList related performance