通過(guò)Semaphore
來(lái)控制對(duì)共享資源的的訪問(wèn)數(shù)量,可以控制同一時(shí)刻并發(fā)的進(jìn)程數(shù) 。
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 + " 獲得鎖運(yùn)行" ); 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 + " 釋放鎖結(jié)束" ); 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 ) #同時(shí)并發(fā)200個(gè)進(jìn)程 for n in range ( 111 ): p = multiprocessing.Process(target = ssh, args = (s, 2 , "192.168.0." + str (n))) p.start() |
運(yùn)行結(jié)果如下圖:
到此這篇關(guān)于python多進(jìn)程登錄遠(yuǎn)端服務(wù)器的文章就介紹到這了,更多相關(guān)多進(jìn)程 Python內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.tuicool.com/articles/M3iQVju