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

最近团队搭建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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值