#!/usr/bin/python #coding=utf-8 import pexpect import threading import getpass import os def lock_num(num): t = threading.BoundedSemaphore(num) def lock(func): def wrapper(remote_ip,publickey,password): t.acquire() func(remote_ip,publickey,password) t.release() return wrapper return lock @lock_num(10) #此裝飾器利用多線程信號量,須要控制併發時使用,併發爲10 def put_public_key(remote_ip,publickey,password): child=pexpect.spawn("/usr/bin/ssh-copy-id -i %s %s" %(publickey,remote_ip)) flag=child.expect(["yes/no","password",pexpect.EOF,pexpect.TIMEOUT]) print (flag) if flag==0: #0匹配成功,1匹配失敗,2超時,3子程序退出 print ("開始向%s上傳公鑰" %remote_ip) try: child.sendline("yes") child.expect("password") child.sendline(password) #send不換行,sendline換行 child.expect('added') #遠程命令返回成功,無此行,會顯示已上傳,可是實際沒傳輸過去。 print ("%s已上傳公鑰" %remote_ip) except Exception as e: print("上傳公鑰失敗") print(e) finally: child.close() elif flag==1: try: child.sendline(password) child.expect('added') print ("%s已上傳公鑰" %remote_ip) except Exception as e: print("上傳公鑰失敗") print(e) finally: child.close() else: print ("%s未上傳公鑰" %remote_ip) child.close() if __name__=='__main__': ip_list=['192.168.10.129','192.168.10.130'] default_public_key = os.path.expanduser('~/.ssh/id_rsa.pub') public_key=default_public_key passwd = getpass.getpass("\033[33mplease input password:\033[0m") if not os.path.exists(public_key) and not os.path.isfile(public_key): #無公鑰時建立 key_path=os.path.expanduser('~/.ssh/id_rsa') child = pexpect.spawn("/usr/bin/ssh-keygen -t rsa -P '' -f %s" %key_path) #必須-f指定放置位置 child.expect(pexpect.exceptions.EOF) child.close(force=True) for i in ip_list: t=threading.Thread(target=put_public_key, args=(i,public_key,passwd)) t.start()