Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1091542
  • 博文数量: 186
  • 博客积分: 4939
  • 博客等级: 上校
  • 技术积分: 2075
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-08 17:15
文章分类

全部博文(186)

文章存档

2018年(1)

2017年(3)

2016年(11)

2015年(42)

2014年(21)

2013年(9)

2012年(18)

2011年(46)

2010年(35)

分类: Python/Ruby

2011-07-30 11:00:09

原文说明: 
how to run the script or commands  on multipl hosts simultaneously

the utility stems from  my previous experiences listed below ,Let's suppose that you are asked to get information that who is logged on the remote hosts and find out disk usages and much more ?what would you do ?if you have multiple servers with similar or identical configurations (such as nodes in a cluster), it's difficult when you need to make configuration modifications from the command line,and how to execute the exact same command on a large number of systems
originally,logging every host and running specified command and then obtain the information ? It's boring and time-consuming ,but it might occur in your routines .
Time to change now ! let's discard old approaches and experience my magical utility now
1)first ,Puppet is an open source configuration management tool. It is written in Ruby and released under the GPL/Apache,it consists of a custom declarative language to describe system configuration. Puppet seems to handle more complex tasks, at the possible expense of more complex configuration,so it's hard to make full use of for beginners,Familiarity and experience with ruby script is required before you are capable of using it .Besides ,puppet mostly focused on configuration management ,it's an disadvantage in comparison with user defined script .
2) using my magical script
Now we are going to see the following tools which does the required job we are looking for:
1) pexpect
here is the brief introduct about pexpect:
pexpect is a program that talks to other interactive programs according to a script. It is useful for running any program which requires interaction between the program and the user. In general, Pexpect is useful for running any program which requires interaction between  the  program  and  the user.
For example:
set/change pwd via script
ftp/ssh authentication
2)other modules
The scrpit includes 2 functions ,the 1st one named ssh_handle(),which will automation interact with remote hosts and respon as if a human were actually typing , the regular expression provided in advance in the script will capture the output generated by expect child process , When output matches a given pattern ,expect will send the corrent answer and command which running on this host.
the reset function will read the ip address and password which stored in the hostlist ,the ip address contains the remote hosts you plan to have the command executed on,this function calls ssh_handle() , run command or scripts at the same time on every hosts ,gather the output and save in the /tmp or any other place you specified before .
    This is just small script but you are only limited by your own imagination
specific/obtain/fairly/pretty/verfaction/stem from
to monitor verify database network is up ,most db opens a tcp port on the network interface to provide access for application or manual query
but they might communicate through a method called IPC
database "health" is critical. Typically, IT organisations have dedicated staff, DBA's, to look after them. To relieve them of routine tasks and improve on issue escalation and resolution, automated database monitoring with a tool like Nagios is a must.
 It is a good idea to create a dedicated account for monitoring and to restrict it's rights within the database.
Not to mention extremly hard if Nagios runs on a UNIX/Linux platform but the target DB is Microsoft's SQL server. It is much easier if we use JDBC
 
  1. #!/usr/bin/env python
  2. #-*- coding:UTF-8 -*-

  3. import pexpect,sys,time
  4. import signal,datetime
  5. import multiprocessing
  6. from optparse import OptionParser

  7. class Notcmd: pass

  8. class Mssh(multiprocessing.Process):
  9.       def __init__(self,ip,user,passwd,cmd,port,debug):
  10.          multiprocessing.Process.__init__(self)
  11.          self.ip=ip
  12.          self.user=user
  13.          self.passwd=passwd
  14.          self.cmd=cmd
  15.          self.port=port
  16.          self.debug=debug
  17.   
  18.       def run(self):
  19.         
  20.         try:
  21.           if not cmd: raise Notcmd
  22.           now=time.strftime("%Y-%m-%d %H:%M:%S")
  23.           print "start time: %s ----- %s " % (now , self.ip)
  24.           ssh = pexpect.spawn('ssh %s@%s %s' % (self.user, self.ip, self.port),timeout=120)
  25.           if debug == None:
  26.             #%(time.strftime("%Y%m%d%H")) #need to import time module
  27.             mlog='/tmp/mssh/' + self.ip
  28.             f = open(mlog,"a+")
  29.             f.write('\n################ %s start at: %s #############\n'%(self.ip,now))
  30.             ssh.logfile_read = f
  31.             #ssh.logfile_send = f
  32.           else :
  33.             f=open('/tmp/tmp.log',"a+b")
  34.             ssh.logfile_read=sys.stdout

  35.           i = ssh.expect(['(?i)password','continue connecting (yes/no)?','[$#]','No route to host','pexpect.TIMEOUT'])

  36.           if i == 0:
  37.              ssh.sendline(self.passwd)

  38.           elif i == 1:
  39.              ssh.sendline('yes')
  40.              ssh.expect('password')
  41.              ssh.sendline(self.passwd)
  42.    
  43.           elif i == 2:
  44.              ssh.sendline()
  45.              #pass
  46.           elif i == 3:
  47.              print 'couldn\'t connect to host ',ssh.before

  48.           else :
  49.              print 'ssh to host timeout ,please check network and pasword '

  50.           #ssh.expect('(?i)terminal type\?')
  51.           #ssh.sendline('vt100')

  52.           if user == 'root' :
  53.             pass
  54.           else :
  55.             ssh.expect('$')
  56.             #ssh.logfile_read = None
  57.             ssh.sendline('sudo su -')
  58.             i = ssh.expect(['[pP]assword','#'])

  59.             if i == 0:
  60.               ssh.sendline(sudopwd)

  61.             else :
  62.               ssh.sendline()

  63.           ssh.expect('#')
  64.           ssh.sendline(cmd)
  65.           ssh.expect('#')
  66.           ssh.sendline()
  67.           f.write('\n#################### %s task finished ##################\n'%self.ip)

  68.         except pexpect.EOF:
  69.          ssh.close()
  70.         except Notcmd:
  71.           print "Mssh Error -- %s server xxnot command" % self.ip
  72.           sys.exit(1)
  73.         except pexpect.TIMEOUT:
  74.           ssh.close()
  75.           print "Mssh Error -- ssh to %s server connect timeout" % self.ip
  76.           sys.exit(1)
  77.         except Exception,e :
  78.           ssh.close()
  79.           print " connect error,",str(e)
  80.           sys.exit(1)
  81.         else:
  82.           ssh.close()
  83.         finally:
  84.           f.close()

  85. def Argument(Print="No"):
  86.   parser = OptionParser(usage="%prog -f hostlist -u user -c \"cmd\" versrion 1.1",version="%prog xiaofu V1.1")
  87.   parser.add_option("-f", "--file",dest="File",action="store",help="host list ,which stores ip and password")
  88.   parser.add_option("-u", "--user",action="store", dest="User",help="username,root or other users")
  89.   parser.add_option("--port",action="store", dest="Port",help="sshd's port ,default:22")
  90.   parser.add_option("-d", "--debug",action="store_true", dest="debug",help="Output debug messages")
  91.   parser.add_option("-c", "--cmd",action="store", dest="Cmd",
  92.     help="commadn to be exected,don't forget to type \"\", e.g \"ifconfig\"\n ")

  93.   (options, args) = parser.parse_args()
  94.   ArgvDict = vars(options)
  95.   if Print == "Yes" : parser.print_help()
  96.   return ArgvDict

  97. def signal_handler(signal, frame):
  98.   print "Kill All Process"
  99.   sys.exit(0)


  100. def Main():

  101.   hostlist=[]
  102.   start = datetime.datetime.now()
  103.   ArgvDict = Argument()
  104.   File = ArgvDict["File"]
  105.   global user
  106.   user = ArgvDict["User"]
  107.   global cmd
  108.   cmd = ArgvDict["Cmd"]
  109.   global debug
  110.   debug = ArgvDict["debug"]
  111.   global port
  112.   port = ArgvDict["Port"]

  113.   signal.signal(signal.SIGINT, signal_handler)

  114.   if port :
  115.     port = "-p "+port
  116.   else :
  117.     port = ""

  118.   file = open(File,"r")
  119.   try:
  120.     while True:
  121.       line = file.readline()
  122.       if len(line) == 0:break
  123.       i = line.strip()
  124.       if i[0] == "#" : continue
  125.       host= i.split()
  126.       hostlist.append(host)
  127.     for i in hostlist:
  128.       ip=i[0]
  129.       passwd=i[1]
  130.       if len(i) == 3 :
  131.          global sudopwd
  132.          sudopwd=i[2]
  133.       p=Mssh(ip,user,passwd,cmd,port,debug)
  134.       x=[]
  135.       x.append(p)
  136.       p.start()
  137.     for t in x:
  138.       t.join()
  139.       
  140.     end = datetime.datetime.now()
  141.     print '\n---------------------------------------------'
  142.     print "All tasks finished! time consuming :",end - start,"\n"

  143.   except Exception,e:
  144.     print "\nError ,reason is : ",str(e),"\n"
  145.   finally:
  146.     file.close()

  147. if __name__ == "__main__":
  148.   if len(sys.argv[1:]) >= 3:
  149.     Main()
  150.   else:
  151.     Argument(Print="Yes")
  152.     sys.exit(1)
目的是替代puppet,Cfengine等批量管理的软件。
阅读(2293) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~