[Python]用python實現批量/併發處理

    最近在學習python,感受很不錯,特別是實現批量/併發處理。實現起來很是方便,比shell方便不少。剛學python一個月,在這留個記錄。下面分享一段代碼。多提建議/意見~(QQ×××流:24967504)python

需求:批量查看/對比線上服務器的狀態狀況,如uptime、df -h、MD5sum文件等等。本打算讓執行命令經過傳參進行、密碼經過交互輸入(3次不對退出)。後面再完善~~shell

#-*- 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()ssh

執行結果:ide

[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
=========================================================================學習

相關文章
相關標籤/搜索