我新开了50个os系统用来跑tomcat节点服务
远程连接采用密钥认证的方式。
通过python编写脚本实现
所有的系统ip和用户密码都存放在脚本目录下的hosts文件里,格式如下:
[hosts]
tomcat-001 : 192.168.0.30
tomcat-002 :192.168.0.31
tomcat-003 : 192.168.0.32
tomcat-004 : 192.168.0.33
[admin]
user:xxxx
passwd:xxxxx
脚本CpyKeyConn.py内容如下:
#!/usr/bin/env python
#coding=utf-8
import os,sys,time
import pexpect
import configparser
import threading
'''
定义自己的线程类(继承threading.Thread)
'''
class MyThread(threading.Thread):
#初始化实例并定义实例的相关对象
def __init__(self,host,user,passwd,keyfile):
threading.Thread.__init__(self)
self.host=host
self.user=user
self.passwd=passwd
self.keyfile=keyfile
def run(self):
self.ConHost()
self.CpyKey()
#连接主机
def ConHost(self):
child=pexpect.spawn('ssh -l %s %s' %(self.user,self.host))
i=child.expect(['Permission denied','\(yes/no\)','password:',pexpect.EOF,pexpect.TIMEOUT],timeout=5)
if i == 0:
print('no permission')
elif i == 1:
child.sendline('yes')
index=child.expect([pexpect.EOF,pexpect.TIMEOUT,'password:'],timeout=5)
if index == 2:
child.sendline(self.passwd)
time.sleep(2)
print('%s connect success..ok' %(self.host))
elif index ==1:
print('connect timeout')
elif i == 2:
child.sendline(self.passwd)
else:
print('%s subproc has quit'%(self.host))
#将服务器生成的公钥拷贝到各个主机节点上
def CpyKey(self):
child=pexpect.spawn('ssh-copy-id -i %s %s' %(self.keyfile,self.host))
index=child.expect([pexpect.TIMEOUT,pexpect.EOF,'password:'])
if index == 2:
child.sendline(self.passwd)
time.sleep(3)
print('%s: %s user translation success..ok' % (self.host,self.user))
elif index == 0:
print('copy time out:%s'% self.host)
elif index == 1:
print('%s cpykey_ssh proc has done'%(self.host))
else:
print('%s: %s user translation success..ok' % (self.host,self.user))
'''
该函数用来创建密钥对
'''
def CrtKey(cmd):
#通过pexpect用来交互操作
child=pexpect.spawn(cmd)
while True:
i=child.expect(['id_rsa\):','passphrase\):','again:',pexpect.TIMEOUT,pexpect.EOF],timeout=5)
#对捕获返回的信息列表进行处理
if i==0 or i==1 or i==2:
child.sendline('\n')
time.sleep(2)
else:
break
def main():
keyfile='/root/.ssh/id_rsa.pub'
'''
检查公钥是否存在。如果不存在调用CrtKey()
创建密钥对
'''
if os.path.exists(keyfile):
print("id_rsa.pub has been exists")
else:
CrtKey('ssh-keygen -t rsa')
'''
通过configparser模块来操作文件,读取hosts
中主机ip和用户名以及密码
'''
cf=configparser.ConfigParser()
cf.read('hosts')
user=cf.get("admin","user")
passwd=cf.get("admin","passwd")
kvs=cf.items("hosts")
for h in kvs:
host=h[1]
my_thread=MyThread(host,user,passwd,keyfile)
my_thread.start()
my_thread.join()
print('done..............ok')
if __name__=='__main__':
main()