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