root@datapark2:~# python -V Python 3.4.3 #!/usr/bin/python # -*- coding:utf-8 -*- import paramiko import sys,os home_dir=os.path.expanduser(‘~‘) id_rsa_pub=‘%s/.ssh/id_rsa.pub‘ % home_dir if not id_rsa_pub: print(‘id_rsa.pub error!‘) sys.exit(0) def upload_file(hostname,port,user,passwd): try: s=paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname,port,user,passwd) t=paramiko.Transport((hostname,port)) t.connect(username=user,password=passwd) sftp=paramiko.SFTPClient.from_transport(t) print(‘create Host:%s .ssh dir......‘ %hostname) stdin,stdout,stderr=s.exec_command(‘mkdir ~/.ssh‘) print(‘upload id_rsa.pub to Host: %s.....‘ %hostname) sftp.put(id_rsa_pub,"/tmp/temp_key") stdin,stdout,stderr=s.exec_command(‘cat /tmp/temp_key >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && rm -f /tmp/temp_key‘) print(‘host:%s@%s auth success!\n‘ %(user,hostname)) t.close() s.close() except Exception as e: import traceback traceback.print_exc() try: t.close() s.close() except: pass def run(): with open(‘host.txt‘,‘r‘) as f: for i in f: f1 = i.split() hostname,port,user,passwd = f1 upload_file(hostname,int(port),user,passwd) if __name__ =="__main__": run() root@datapark2:/data/python_test# cat host.txt 192.168.31.162 22 root 123456 192.168.31.130 22 root 123456
本文出自 “patrick” 博客,请务必保留此出处http://patrick0715.blog.51cto.com/3681259/1825235
原文地址:http://patrick0715.blog.51cto.com/3681259/1825235