码迷,mamicode.com
首页 > 其他好文 > 详细

批量配置主机

时间:2019-10-31 16:29:02      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:auto   结果   str   pass   stderr   lin   man   shc   toad   

 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()

 

批量配置主机

标签:auto   结果   str   pass   stderr   lin   man   shc   toad   

原文地址:https://www.cnblogs.com/gy99/p/11771675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!