最近在学习python,感觉很不错,特别是实现批量/并发处理。实现起来非常方便,比shell方便很多。刚学python一个月,在这留个记录。下面分享一段代码。多提建议/意见~(QQ群交流:24967504)

需求:批量查看/对比线上服务器的状态情况,如uptime、df -h、MD5sum文件等等。本打算让执行命令通过传参进行、密码通过交互输入(3次不对退出)。后面再完善~~

#-*- coding: utf-8 -*-
#!/usr/bin/python

import paramiko
import threading
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 '========================================================================='
def main():
    cmd = ['uptime']  #执行命令
    username = "root"
    passwd = "密码"
    threads = [4]
    f = file('list.txt')  #ip列表
    while True:
        ip = f.readline()
        if len(ip) == 0:
            break
        a = threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
        a.start()
    f.close()      

if __name__ == '__main__':
    main()

执行结果:

[root@bw-vm-soft ~]# python ssh2.py
 13:31:28 up 514 days,  7:28,  1 user,  load average: 10.27, 9.44, 9.03
[OK]192.168.13.116
=========================================================================
 13:31:28 up 514 days,  8:04,  1 user,  load average: 5.99, 6.05, 6.46
[OK]192.168.13.117
=========================================================================