您的位置:首页 > 编程语言 > Python开发

搭建MHA,python实现服务器ssh无密码认证

2016-03-24 08:46 666 查看
最近团队搭建MHA,于是写了ssh验证

#/usr/bin/env python

import sys

import paramiko

import pexpect

import subprocess

ssh_dir='/root/.ssh'

id_rsa_pub='%s/id_rsa.pub' %ssh_dir

if not id_rsa_pub:

    print 'id_rsa.pub does not exist!,now create id_rsa_pub'

    cmd="ssh-keygen -t rsa -f /root/.ssh/id_rsa -P ''"

    subprocess.call(cmd,shell=True)

else:

    print "have id_rsa_pub"

    

def up_key(host,port,user,passwd):

    try:

        s=paramiko.SSHClient()

        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        s.connect(host,port,user,passwd)

        t=paramiko.Transport((host,port))

        t.connect(username=user,password=passwd)

        sftp=paramiko.SFTPClient.from_transport(t)

        #stdin,stdout,stderr=s.exec_command('ls /root/.ssh')

        print 'upload id_rsa.pub to host:%s....' %host

        sftp.put(id_rsa_pub,"/tmp/temp_key")

        stdin,stdout,stderr=s.exec_command('cat /tmp/temp_key >> ~/.ssh/authorized_keys && rm -rf /tmp/temp_key')

        print 'host:%s auth success!\n' %host

        s.close()

        t.close()

    except Exception,e:

        import traceback

        traceback.print_exc()

        try:

            s.close()

            t.close()

        except:

             pass

if __name__=='__main__':

     mylist=[]

     mylist2=[]

     for i in range(1,len(sys.argv)):

         mylist.append(sys.argv[i])

     print mylist

     

     username="root"

     passwd="d4ngd4ngmyr00t"

     port=22

     print "Begin......"

     length=len(mylist)

     for i in range(length):

         ip=mylist[i]

        a=up_key(ip,port,username,passwd)

     

参考:

https://github.com/linuxyan/linuxyan/blob/master/python/Batch_create_pub_key/Batch_key.py

http://www.cnblogs.com/ma6174/archive/2012/05/25/2508378.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: