用python實現批量/並發處理

來源:互聯網
上載者:User

最近在學習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
=========================================================================

針對前面的代碼,還存在的問題進行了改善:
1、去掉純文字密碼,通過互動輸入密碼
2、通過傳參執行相關命令,增加靈活性
3、異常處理
4、其他問題待發現,聯絡QQ群: 24967504

具體代碼:

#!/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:
pass

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 '========================================================================='

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
=========================================================================

若密碼不對
[Error]192.168.13.116
=========================================================================
[Error]192.168.13.117

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.