黑帽联盟

标题: python简单主机批量管理工具 [打印本页]

作者: yun    时间: 2017-2-7 22:22
标题: python简单主机批量管理工具
今天做了一个很简单的小项目,感受到了paramiko模块的强大,也深感自己Linux的功力不行~~
一、需求
13.png

二、简单需求分析及流程图
需求很少,我就简单地说下:
1. 主机分组可以配置文件实现(我用字典存数据的).
2. 登陆功能不做。选择分组后可查看组内对应主机的主机名和IP地址.
3. >>>cmd: df(输入命令则起多个线程(视组内有多少个主机而定)同时执行)
输出:
-------------h1------------
……(命令返回的数据)
-------------h2------------
……
>>>put  test.yy(本地文件)   filename (把本地的test.yy文件传到远程主机的/root目录下)
4.可写在配置文件中。包括远程主机的: 主机名 IP 用户名 密码 端口
流程图
14.png

三、目录结构及源代码
目录结构:
15.png
from_windows.py(待上传的文件)
main.py(批量主机管理接口)
  1. """批量主机管理接口"""

  2. import core

  3. if __name__ == "__main__":
  4.   core.run()
复制代码
core.py(核心代码,被接口调用)
  1. """核心代码"""
  2. import settings
  3. import paramiko
  4. import threading
  5. import os


  6. class REMOTE_HOST(object):
  7.   #远程操作主机
  8.   def __init__(self, host, port ,username, password, cmd):
  9.     self.host = host
  10.     self.port = port
  11.     self.username = username
  12.     self.password = password
  13.     self.cmd = cmd

  14.   def run(self):
  15.     """起线程连接远程主机后调用"""
  16.     cmd_str = self.cmd.split()[0]
  17.     if hasattr(self, cmd_str):   #反射 eg:调用put方法
  18.       getattr(self, cmd_str)()
  19.     else:
  20.       #setattr(x,'y',v)is equivalent to  ``x.y=v''
  21.       setattr(self, cmd_str, self.command)
  22.       getattr(self, cmd_str)() #调用command方法,执行批量命令处理

  23.   def command(self):
  24.     """批量命令处理"""
  25.     ssh = paramiko.SSHClient() #创建ssh对象
  26.     #允许连接不在know_hosts文件中的主机
  27.     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  28.     ssh.connect(hostname=self.host,port=self.port,username=self.username,password=self.password)
  29.     stdin,stdout,stderr = ssh.exec_command(self.cmd)
  30.     result = stdout.read()
  31.     print("%s".center(50, "-") % self.host)
  32.     print(result.decode())
  33.     ssh.close()

  34.   def put(self):
  35.     """上传文件"""
  36.     filename = self.cmd.split()[1] #要上传的文件
  37.     transport = paramiko.Transport((self.host, self.port))
  38.     transport.connect(username=self.username, password=self.password)
  39.     sftp = paramiko.SFTPClient.from_transport(transport)
  40.     sftp.put(filename, filename)
  41.     print("put sucesss")

  42.     transport.close()


  43. def show_host_list():
  44.   """通过选择分组显示主机名与IP"""
  45.   for index, key in enumerate(settings.msg_dic):
  46.     print(index + 1, key, len(settings.msg_dic[key]))
  47.   while True:
  48.     choose_host_list = input(">>>(eg:group1)").strip()
  49.     host_dic = settings.msg_dic.get(choose_host_list)
  50.     if host_dic:
  51.       #print(host_dic)
  52.       for key in host_dic:
  53.         print(key, host_dic[key]["IP"])
  54.       return host_dic
  55.     else:
  56.       print("NO exit this group!")


  57. def interactive(choose_host_list):
  58.   """根据选择的分组主机起多个线程进行批量交互"""
  59.   thread_list = []
  60.   while True:
  61.     cmd = input(">>>").strip()
  62.     if cmd:
  63.       for key in choose_host_list:
  64.         host, port, username, password = choose_host_list[key]["IP"], choose_host_list[key]["port"], \
  65.                          choose_host_list[key]["username"], choose_host_list[key]["password"]
  66.         func = REMOTE_HOST(host, port, username, password, cmd) # 实例化类
  67.         t = threading.Thread(target=func.run) # 起线程
  68.         t.start()
  69.         thread_list.append(t)
  70.       for t in thread_list:
  71.         t.join() # 主线程等待子线程执行完毕
  72.     else:
  73.       continue


  74. def run():
  75.   choose_host_list = show_host_list()
  76.   interactive(choose_host_list)
复制代码
settings.py(配置文件)
  1. """配置文件"""

  2. msg_dic = {
  3.   "group1":{  #分组1
  4.     "h1":{"IP":"192.168.1.1", "username":"11", "password":"aa", "port":22},
  5.     "h2":{"IP":"192.168.1.2", "username":"22", "password":"bb", "port":22},
  6.     "h3":{"IP":"192.168.1.3", "username":"33", "password":"cc", "port":22},
  7.     "h4":{"IP":"192.168.1.4", "username":"44", "password":"dd", "port":22},
  8.     "h5":{"IP":"192.168.1.5", "username":"55", "password":"ee", "port":22},
  9.     "h6":{"IP":"192.168.1.6", "username":"66", "password":"ff", "port":22},
  10.   },

  11.   "group2":{  #分组2
  12.     "h1":{"IP":"192.168.2.1", "username":"111", "password":"aaa", "port":22},
  13.     "h2":{"IP":"192.168.2.2", "username":"222", "password":"bbb", "port":22},
  14.     "h3":{"IP":"192.168.2.3", "username":"333", "password":"ccc", "port":22},
  15.     "h4":{"IP":"192.168.2.4", "username":"444", "password":"ddd", "port":22},
  16.     "h5":{"IP":"192.168.2.5", "username":"555", "password":"eee", "port":22},
  17.     "h6":{"IP":"192.168.2.6", "username":"666", "password":"fff", "port":22},
  18.     "h7":{"IP":"192.168.2.7", "username":"777", "password":"ggg", "port":22},
  19.     "h8":{"IP":"192.168.2.8", "username":"888", "password":"hhh", "port":22},
  20.   },

  21.   "group3":{
  22.     "h1":{"IP":"192.168.179.133", "username":"root", "password":"zcl", "port":22},
  23.   }
  24. }
复制代码
测试:
硬件限制,我只用连接一台虚拟机测试~
  1. C:\Python34\python3.exe C:/Users/Administrator/PycharmProjects/laonanhai/host_manage/main.py
  2. 1 group1 6
  3. 2 group3 1
  4. 3 group2 8
  5. >>>(eg:group1)group3
  6. h1 192.168.179.133
  7. >>>put from_windows.py
  8. put sucesss
  9. >>>
  10. >>>ls
  11. ------------------------192.168.179.133------------------------
  12. anaconda-ks.cfg
  13. database_test
  14. from_windows.py
  15. install.log
  16. install.log.syslog
  17. m
  18. oot
  19. \root
  20. tmp\from_windows.py

  21. >>>
复制代码
上传前没有from_windows.py文件,上传后就有了!
16.png





欢迎光临 黑帽联盟 (https://bbs.cnblackhat.com/) Powered by Discuz! X2.5