+ -
当前位置:首页 → 问答吧 → 一个批量执行任务的py脚本

一个批量执行任务的py脚本

时间:2011-06-20

来源:互联网

放py版块肯定无人问津,劳烦waker等斑竹就别移走了,这里民工居多,也能减轻负担。

说明,参考了网上的一些人的东西,但我都试过他们的了,都是考虑不全无法使用的,但这种错误还被数人转载,真是误人不浅啊。。

重点参考了pexpect的说明https://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/

版权没得,随意copy吧。
  1. #!/usr/bin/env python
  2. #coding=utf-8

  3. import pexpect
  4. import sys

  5. def ssh_cmd(ip, user, passwd, cmd):
  6.     ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd),timeout=10)
  7.     log = open(ip,"a+b")
  8.     #
  9.     ssh.logfile_read = log
  10.     try:

  11.       i = ssh.expect(['password: ','continue connecting (yes/no)?','pexpect.TIMEOUT'])
  12.       if i == 0:
  13.            ssh.sendline(passwd)
  14.            i = ssh.expect(['Password:','pexpect.TIMEOUT'])
  15.            if i == 0:
  16.                 ssh.sendline(passwd)
  17.            else:
  18.                 print "---------send pwd timout----------"
  19.       elif i == 1:
  20.            ssh.sendline('yes')
  21.            i = ssh.expect(['password: ','pexpect.TIMEOUT'])
  22.            if i == 0:
  23.                 ssh.sendline(passwd)
  24.                 i = ssh.expect(['Password:','pexpect.TIMEOUT'])
  25.                 if i ==0:
  26.                    ssh.sendline(passwd)
  27.                 else:
  28.                    print "----------pwd Timeout----------"
  29.            else:
  30.                 print "----------ssh Timeout----------"
  31.    
  32.       elif i == 2:
  33.            print "----------ssh Timeout----------"

  34.     except pexpect.EOF:
  35.          ssh.close()
  36.          log.close()
  37.          return "it seems fine"
  38.     else:
  39.          ssh.expect(pexpect.EOF)
  40.          ssh.close()

  41. file = open('hosts.txt')
  42. try:
  43.   hosts = file.read()
  44. finally:
  45.   file.close()


  46. for host in hosts.split("\n"):
  47.     if host:
  48.         ip, user, passwd, cmds = host.split(":")
  49.         for cmd in cmds.split(","):
  50.             print "-- %s run:%s --" % (ip, cmd)
  51.             print ssh_cmd(ip, user, passwd, cmd)   
复制代码
hosts里内容格式如下:
172.18.0.131:root:123456:df -h,uptime
。。。。省略若干。。。

首先安装pexpect, Centos 下yum install pexpect -y即可

说明:默认端口22,root用户登录,日志以ip为文件名记录。

可以把脚本放在nagios监控机器上(因为它到各个服务器都有路由,否则无法监控,还有它有http服务),然后在hosts添加wget任务,再修改hosts添加执行脚本的任务。看来写成类和线程更好些,以后完善之。

作者: expert1   发布时间: 2011-06-20

人才啊,必须支持!

作者: bbgg1983   发布时间: 2011-06-20

回复 bbgg1983


    兄弟,去哪里了,好久不见啊,来bj了吗?

作者: expert1   发布时间: 2011-06-20