通過Semaphore
來控制對共享資源的的訪問數量,可以控制同一時刻并發的進程數 。
1
2
3
4
5
6
7
8
9
10
11
|
#/usr/bin/python # _*_ coding: utf-8 _*_ import multiprocessing import time import paramiko def ssh(s,i,host): |
try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
s.acquire() print (time.strftime( '%H:%M:%S' ),multiprocessing.current_process().name + " 獲得鎖運行" ); ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname = host, port = 22 , username = "root" , password = "yankefei" ) print (host + " is login success" ) stdin, stdout, stderr = ssh.exec_command("echo d a t e && df - hl") print (stdout.read().decode( 'utf-8' )) returncode = stdout.channel.recv_exit_status() print ( "returncode:" ,returncode) |
except:
1
2
3
4
5
6
7
8
9
|
ssh.close() # time.sleep(i) print (time.strftime( '%H:%M:%S' ),multiprocessing.current_process().name + " 釋放鎖結束" ); s.release() print (host + " is unreachable" ) |
finally:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
ssh.close() s.release() if __name__ = = "__main__" : s = multiprocessing.Semaphore( 200 ) #同時并發200個進程 for n in range ( 111 ): p = multiprocessing.Process(target = ssh, args = (s, 2 , "192.168.0." + str (n))) p.start() |
運行結果如下圖:
到此這篇關于python多進程登錄遠端服務器的文章就介紹到這了,更多相關多進程 Python內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.tuicool.com/articles/M3iQVju