批量配置主机
Posted gy99
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批量配置主机相关的知识,希望对你有一定的参考价值。
1 #!/usr/bin/python2.7 2 #coding=utf-8 3 import paramiko 4 import os 5 import sys 6 7 8 class ConnLinux(object): 9 def __init__(self, connip, connuser, connpass): 10 self.connip = connip 11 self.connuser = connuser 12 self.connpass = connpass 13 14 ###连接到远程服务器 15 def connect(self): 16 while True: 17 try: 18 self.s = paramiko.SSHClient() 19 self.s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 20 self.s.connect(self.connip, 22, self.connuser, self.connpass) 21 print self.connip, ":successfully connected" 22 return 23 except Exception as e: 24 print self.connip, e 25 ###关闭连接 26 def sshclose(self): 27 self.s.close() 28 29 ###在远程服务器执行命令,无输出 30 def execcommand(self, cmd): 31 self.s.exec_command(cmd) 32 33 ###在远程服务器执行命令并且输出结果 34 def exec_log(self, cmd): 35 stdin, stdout, stderr = self.s.exec_command(cmd) 36 print self.connip, stdout.read().decode(), stderr.read() 37 38 39 ###上传文件到远程服务器 40 def trans(self, fromfile, tofile): 41 if os.path.exists(fromfile) == True: 42 try: 43 self.t = paramiko.Transport((self.connip, 22)) 44 self.t.connect(username=self.connuser, password=self.connpass) 45 self.sftp = paramiko.SFTPClient.from_transport(self.t) 46 self.sftp.put((fromfile), (tofile), confirm=True) 47 self.t.close() 48 except Exception as e: 49 print self.connip, e 50 else: 51 print tofile + "does not exists" 52 def transclose(self): 53 self.t.close() 54 55 56 if __name__ == ‘__main__‘: 57 ###通过root账号和密码连接Linux服务器,IP和密码通过中文字符“¥”区分 58 59 60 def rootConn(rootfile,cmd): 61 with open(rootfile, ‘r‘) as f: 62 result = dict(line.strip().split(‘¥‘) for line in f if line) 63 for v, k in result.items(): 64 # print v,k 65 host = ConnLinux(v, "root", k) 66 host.connect() 67 host.execcommand(cmd) 68 host.sshclose()
以上是关于批量配置主机的主要内容,如果未能解决你的问题,请参考以下文章