批量远程执行linux服务器程序--基于pxpect(多进程、记日志版)
2015-11-13 10:59
543 查看
#!/usr/bin/python
'''
Created on 2015-06-09
@author: Administrator
'''
import pexpect import os,sys from optparse import OptionParser import logging,multiprocessing import logging.handlers #menue usage='%prog [-h][-s Servers][-c CMDS][--version]' parser=OptionParser(usage=usage,version='Hu 2.0_20150609') parser.add_option('-s','--Server',dest='server',default='ip.txt',help='The Server Info') parser.add_option('-c','--CMDS',dest='cmd',default='pwd',help='You wann to execute commands') (options,args)=parser.parse_args() print options.server,options.cmd logger=logging.getLogger() logger.setLevel(logging.DEBUG) ch=logging.StreamHandler() cc=logging.handlers.RotatingFileHandler('log.txt', maxBytes = 1024*1024, backupCount = 5) formatter=logging.Formatter("%(asctime)s-%(name)s-%(levelname)s %(message)s") ch.setFormatter(formatter) cc.setFormatter(formatter) logger.addHandler(ch) logger.addHandler(cc) #ssh functions def connect(ip,username,password,port,prompt=']#'): try: ssh_newkey='Are you sure you want to continue connecting' child=pexpect.spawn('ssh '+username + '@'+ip+' -p '+port,maxread=5000) child.logfile=fout i=child.expect([prompt,'assword:*',ssh_newkey,'refused',pexpect.TIMEOUT,'key.*? failed']) print i #if not False: # print child.before,child.after if i==0: pass elif i==1: print password child.sendline(password) elif i==2: child.sendline('yes') elif i==4: raise Exception('Error TIMEOUT!') elif i==3: print 'Connect refused' elif i==5: print child.before,child.after os.remove(os.path.expanduser('~')+'/.ssh/known_hosts') child.expect('#') print child.after,child.before child.sendline(options.cmd) child.expect('#') print child.before,child.after print 'The command %s result is:' % options.cmd print child.before except Exception,e: logger.error("Connect Error") #check -s isn't exits if os.path.exists(options.server): filename=options.server pass else: print 'Please check %s and ip.txt is exits' % options.server exit(-1) #execute fout=file('mylog.txt','w') for line in open(filename): ip,user,passwd,port=line.strip().split() print '*'*50 print 'The follow ip is %s:' % ip p=multiprocessing.Pool(processes=4) result=p.apply_async(connect,[ip,user,passwd,port]) print result.get() #connect(ip,user,passwd,port)
E-mail:362299908@qq.com
相关文章推荐
- linux(raspberry) 安装配置 samba
- centos 编译安装python
- Linux下编译安装Pymol 1.7.6
- linux串口操作及设置详解
- 探讨一下,linux下的i节点。
- Linux下基本的文件和目录管理命令学习教程
- win7中将文件拷贝到虚拟机linux下的方法
- linux:SUID、SGID详解
- Linux下实现磁盘配额的两种方法
- 64位linux centos 安装android问题及解决方案
- 查看centos的版本
- 从CentOS7默认安装的/home中转移空间到根目录/ - LVM操作简明教程
- linux学习笔记(5):Linux文件类型与扩展名
- Centos7 下配置mysql5.6主从复制实例(一主两从)
- Linux下查看硬件配置信息
- Linux_Centos中搭建nexus私服
- linux之sed用法
- CentOS x64上Matlab R2015b的镜像安装方法与卸载
- 修改双系统(Linux系统和Windows系统)的启动顺序和等待时间
- linux 查看系统资源实用情况之top命令