通过Semaphore 来控制对共享资源的的访问数量,可以控制同一时刻并发的进程数

#/usr/bin/python

# _*_ coding: utf-8 _*_

import multiprocessing

import time

import paramiko

def ssh(s,i,host):

 try:

   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 `date` && df -hl")

   print(stdout.read().decode('utf-8'))

   returncode = stdout.channel.recv_exit_status()

   print("returncode:",returncode)

 except:

   ssh.close()

  # time.sleep(i)

   print(time.strftime('%H:%M:%S'),multiprocessing.current_process().name + " 释放锁结束");

   s.release()

   print (host+" is unreachable")

 finally:

   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