ansible批量分发免密钥登陆python脚本
最近看了看强大的号称自动化运维的三大利器之一的——ansible,ok,亲测之后,确实感觉,对于我们这种DBA工作者来说,确实很受益。
值得注意的是ansible要求被管理服务器python版本不低于2.6。
OK,简单了写了个脚本,实现服务器端面密钥登陆被管理服务器python脚本,这里省略了ansible,python等的部署以及使用。
环境:
python 2.7
ansible 2.4.0
pexpect (pip installpexpect)
以下是批量分发密钥登陆脚本内容:
#!/usr/bin/python27
""" Made by Joe.Wan Email:1272149624@QQ.com""" import sys import pexpect ip = ['10.1.1.10','10.1.1.13'] #这是ip列表,视情况修改 for x in ip: password='asss' #密码需要视情况修改 expect_list = ['(yes/no)','password:'] p = pexpect.spawn('ssh-copy-id %s' % x) try: while True: idx = p.expect(expect_list) print p.before + expect_list[idx], if idx == 0: print "yes" p.sendline('yes') elif idx == 1: print password p.sendline(password) except pexpect.TIMEOUT: print >>sys.stderr,'timeout' except pexpect.EOF: print p.before print >>sys.stderr,'<the end>'
执行结果:
ok,将上面脚本修改下,弄成单个分发脚本:addhost.py
#!/usr/bin/python import sys import pexpect ip = sys.argv[1] password = 'password' expect_list = ['(yes/no)', 'password:'] p = pexpect.spawn('ssh-copy-id %s' % ip) try: while True: idx = p.expect(expect_list) print p.before + expect_list[idx], if idx == 0: print "yes" p.sendline('yes') elif idx == 1: print password p.sendline(password) except pexpect.TIMEOUT: print >>sys.stderr, 'timeout' except pexpect.EOF: print p.before print >>sys.stderr, '<the end>'
使用方法:python27 addhost.py 10.1.1.1