码迷,mamicode.com
首页 > 其他好文 > 详细

paramiko建立无密码传输认证

时间:2016-07-11 10:44:08      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:paramkil/无密码传输认证

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

paramiko建立无密码传输认证

标签:paramkil/无密码传输认证

原文地址:http://patrick0715.blog.51cto.com/3681259/1825235

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!