[Python]用python实现批量/并发处理(完善版)

  针对前面的代码 http://lxsym.blog.51cto.com/1364623/1065854,还存在的问题进行了改善:
    一、去掉明文密码,经过交互输入密码
    二、经过传参执行相关命令,增长灵活性
    三、异常处理
    四、其余问题待发现,联系QQ群: 24967504python

具体代码:nginx

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
import paramiko
import threading
import getpass
def main():
    try:
        cmd = sys.argv[1:]
        username = "root"
        passwd = getpass.getpass('Please input password: ')
        threads = [4]
        f = file('list.txt')
        while True:
            ip = f.readline()
            if len(ip) == 0:
                break
            a = threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
            a.start()
        f.close()
    except:
         passweb

def ssh2(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin,stdout,stderr = ssh.exec_command(m)
            stdin.write("Y")
            out = stdout.readlines()
            for o in out:
                print o,
        print '[OK]%s' %(ip),
        print '========================================================================='
        ssh.close()
    except:
        print '[Error]%s' %(ip),
        print '========================================================================='ssh

if __name__ == '__main__':
    main()
 
执行结果:
[root@bw-vm-soft test]# python ssh2.py 'md5sum /usr/local/webserver/nginx/conf/nginx.conf' 
Please input password:
33066988953224e936028b341f4e1337  /usr/local/webserver/nginx/conf/nginx.conf
[OK]192.168.13.116
=========================================================================
33066988953224e936028b341f4e1337  /usr/local/webserver/nginx/conf/nginx.conf
[OK]192.168.13.117
=========================================================================ide

若密码不对
[Error]192.168.13.116
=========================================================================
[Error]192.168.13.117spa

相关文章
相关标签/搜索