Python简单主机批量管理工具
一、程序介绍
需求:
简单主机批量管理工具
需求:
1.主机分组
2.主机信息使用配置文件
3.可批量执行命令、发送文件,结果实时返回
4.主机用户名密码、端口可以不同
5.执行远程命令使用paramiko模块
程序结构:
Host_manage/ #程序目录
├── bin #启动程序目录
│ └── start.py #启动程序文件
├── conf #配置目录
│ ├── __pycache__
│ │ └── settings.cpython-36.pyc
│ └── settings.py #配置文件
├── core #主程序目录
│ ├── __pycache__
│ │ └── src.cpython-36.pyc
│ └── src.py #主程序
└── log
二、流程图
三、代码
目录结构:
from_windows.py(待上传的文件)
main.py(批量主机管理接口)
"""批量主机管理接口""" from 作业 import core if __name__ == "__main__": core.run()
core.py(核心代码,被接口调用)
"""核心代码""" from 作业 import settings import paramiko import threading,os class REMOTE_HOST(object): # 远程操作主机 def __init__(self, host, port, username, password, cmd): self.host = host self.port = port self.username = username self.password = password self.cmd = cmd def run(self): """起线程连接远程主机后调用""" cmd_str = self.cmd.split()[0] if hasattr(self, cmd_str): # 反射 eg:调用put方法 getattr(self, cmd_str)() else: # setattr(x,'y',v)is equivalent to ``x.y=v'' setattr(self, cmd_str, self.command) getattr(self, cmd_str)() # 调用command方法,执行批量命令处理 def command(self): """批量命令处理""" ssh = paramiko.SSHClient() # 创建ssh对象 # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.password) stdin, stdout, stderr = ssh.exec_command(self.cmd) print("%s".center(50, "-") % self.host) res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode()) ssh.close() def put(self): """上传文件""" filename = self.cmd.split()[1] # 要上传的文件 transport = paramiko.Transport((self.host, self.port)) transport.connect(username=self.username, password=self.password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(filename, filename) print("put sucesss") transport.close() def get(self): """下载文件""" filename = self.cmd.split()[1] # 要下载的文件 transport = paramiko.Transport((self.host, self.port)) transport.connect(username=self.username, password=self.password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get(filename, filename) print("get sucesss") transport.close() def show_host_list(): """通过选择分组显示主机名与IP""" for index, key in enumerate(settings.msg_dic): print("%s\033[34m 主机组:%s \033[0m \033[33m 主机数量:%s\033[0m" % (index + 1, key, len(settings.msg_dic[key]))) while True: choose_host_list = input(">>(请输入用户组编号如:group1): ").strip() host_dic = settings.msg_dic.get(choose_host_list) if host_dic: # print(host_dic) for key in host_dic: print(key, host_dic[key]["IP"]) return host_dic else: print("NO exit this group!") def interactive(choose_host_list): """根据选择的分组主机起多个线程进行批量交互""" thread_list = [] while True: cmd = input(">>>").strip() if cmd: for key in choose_host_list: host, port, username, password = choose_host_list[key]["IP"], choose_host_list[key]["port"], \ choose_host_list[key]["username"], choose_host_list[key]["password"] func = REMOTE_HOST(host, port, username, password, cmd) # 实例化类 t = threading.Thread(target=func.run) # 起线程 t.start() thread_list.append(t) for t in thread_list: t.join() # 主线程等待子线程执行完毕 else: continue def run(): choose_host_list = show_host_list() interactive(choose_host_list)
settings.py(配置文件)
"""配置文件""" msg_dic = { "group1":{ #分组1 "h1":{"IP":"192.168.50.134", "username":"root", "password":"521521", "port":22} }} #可以分多组我就一台测试机器
View Code
测试:
硬件限制,我只用连接一台虚拟机测试~
C:\Users\Administrator\PycharmProjects\s14\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/s14/作业/main.py
1 主机组:group1 主机数量:1
>>(请输入用户组编号如:group1): group1
h1 192.168.50.134
>>>put from_windows.py
put sucesss
>>>
>>>ls
------------------------192.168.50.134------------------------
anaconda-ks.cfg
database_test
from_windows.py
install.log
install.log.syslog
m
oot
\root
tmp\from_windows.py
>>>
上传前没有from_windows.py文件,上传后就有了!