标签:服务器 python import linux local
经过几天的学习,pexpect模块对于linux下运维脚本编写属实有用,下面写个脚本检验下学习效果。
#!/usr/bin/env python #coding=utf-8 #远程执行服务器上的脚本 import sys, time, os, multiprocessing try: import pexpect except ImportError: print """ You must install pexpect module """ sys.exit(1) addr_map = { ‘s1‘:(‘root@192.168.1.1‘, ‘aaa‘), ‘s2‘:(‘root@192.168.1.2‘, ‘bbb‘), } cmd_map = { ‘four‘:"/usr/local/src/four.sh", ‘five‘:"/usr/local/src/five.sh", } # 必须带1个参数 if len(sys.argv) != 2: #系统错误输出 print ‘wrong!!!‘ sys.stderr.write("Usage: python %s cmd \n" % sys.argv[0]) raise SystemExit(1) try: cmd_key = sys.argv[1] print ‘cmd_key: %s‘ % cmd_key cmd = cmd_map[cmd_key] print ‘cmd: %s‘ % cmd except: sys.stderr.write("Usage: python %s cmd \n" % sys.argv[0]) print "cmd: four or five" raise SystemExit(1) ‘‘‘ # #################################### # 定义函数,并将其作为单个进程 def runn(s): child = pexpect.spawn(‘ssh %s %s‘ % (addr_map[s][0],cmd_map[cmd_key])) index = child.expect(["(?i)password", pexpect.EOF, pexpect.TIMEOUT]) child.sendline(addr_map[s][1]) child.expect(pexpect.EOF) print child.before child.sendline("quit") for key in addr_map: p = multiprocessing.Process(target=runn, args=(key,)) p.start() ‘‘‘ # ####################################### # 将进程定义为类 class ttt(multiprocessing.Process): def __init__(self,id): multiprocessing.Process.__init__(self) self.id = id print self.id def run(self): child = pexpect.spawn(‘ssh %s %s‘ % (addr_map[self.id][0],cmd_map[cmd_key])) index = child.expect(["(?i)passwd",pexpect.EOF,pexpect.TIMEOUT]) child.sendline(addr_map[self.id][1]) child.expect(pexpect.EOF) print child.before child.sendline("quit") for key in addr_map: p = ttt(key) p.start()
pexpect练习实例--批量执行远程服务器上的指定脚本,布布扣,bubuko.com
标签:服务器 python import linux local
原文地址:http://yayang.blog.51cto.com/826316/1411514