需求:

  1. 主机分组
  2. 登录后显示主机分组,选择分组后查看主机列表
  3. 可批量执行命令、发送文件,结果实时返回
  4. 主机用户名密码可以不同

流程图:

说明:

## 需求: 
  1. 主机分组
  2. 登录后显示主机分组,选择分组后查看主机列表
  3. 可批量执行命令、发送文件,结果实时返回
  4. 主机用户名密码可以不同
## 目录结构
  batch-manage
    bin/
      start.py   # 启动主程序
    conf/
      setting.py  # 远程主机配置文件
    core/
      control.py   # RemoteControl类,用于远程主机执行命令及上传
      local.py    # 本地数据处理 ## 说明
  目前实现可批量执行命令,上传文件功能。 ## 运行环境
  windows
  python3.0+ 代码下载地址:https://github.com/hukeyy/batch-manage

bin/
  start.py

#!_*_coding:utf-8_*_
# Author: hkey
import threading, os, sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from core import control
from core import local
from conf import setting if __name__ == '__main__': for host in setting.hosts.keys():
host_tuple = local.options()
print('\33[42;1m[put file or inter system command.]\33[0m')
while True:
cmd = input('>>>').strip()
if len(cmd) == 0: continue
t_list = []
for host in host_tuple:
remote_control = control.RemoteControl(cmd, *host)
t = threading.Thread(target=remote_control.run,)
t.setDaemon(True)
t.start()
t_list.append(t)
for t in t_list:
t.join()
conf/
  setting.py
#!_*_coding:utf-8_*_
# Author: hkey

## 元组在python中是不可变对象,保存序列时,应当尽量采用这种方式
hosts = {'测试系统':(('10.0.0.11', 22, 'root', ''),
('10.0.0.12', 22, 'root', ''),
), '生产系统':(('10.0.0.12', 22, 'root', ''),
),
}

core/
  control.py
#!_*_coding:utf-8_*_
# Author: hkey
import paramiko class RemoteControl(object):
'''远程主机操作类'''
def __init__(self, cmd, *kw):
self.hostname = kw[0]
self.port = kw[1]
self.username = kw[2]
self.password = kw[3]
self.cmd = cmd def run(self):
   '''通过反射功能将程序解耦'''
cmd = self.cmd.split()[0]
if hasattr(self, cmd):
getattr(self, cmd)()
else:
setattr(self, cmd, self.command)
getattr(self, cmd)() def put(self):
'''上传文件'''
# try:
transport = paramiko.Transport(self.hostname, self.port)
transport.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(self.cmd.split()[1], self.cmd.split()[2])
transport.close()
print('\33[32;1m【%s】上传文件【%s】成功!' %(self.hostname, self.cmd.split()[1]))
# except Exception as e:
# print('\33[31;1m错误:【%s】: 【%s】\33[0m' %(self.hostname, e)) def command(self):
'''执行系统静态命令'''
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=self.hostname, port=self.port, username=self.username,
password=self.password)
stdin, stdout, stderr = ssh.exec_command(self.cmd)
res, err = stdout.read(), stderr.read()
result = res if res else err
print('\33[32;1m%s\33[0m'.center(50, '-') % self.hostname)
print(result.decode())
ssh.close()

core/
     local.py

#!_*_coding:utf-8_*_
# Author: hkey
import os, sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from conf import setting
def options():
'''通过配置文件setting.py,用户选择主机组并通过用户选择的组获取到主机的信息'''
for host in setting.hosts.keys():
print(host)
while True:
choice = input('please choice groupname:')
if len(choice) ==0: continue
if choice in setting.hosts.keys():
for host in setting.hosts[choice]:
print(host[0])
return setting.hosts[choice]
else:
print('groupname not exist.')
break

[ Python - 10 ] 练习:批量管理主机工具的更多相关文章

  1. 【Python】JBOSS-JMX-EJB-InvokerServlet批量检测工具

    一.说明 在JBoss服务器上部署web应用程序,有很多不同的方式,诸如:JMX Console.Remote Method Invocation(RMI).JMXInvokerServlet.Htt ...

  2. Python简单主机批量管理工具

    一.程序介绍 需求: 简单主机批量管理工具 需求: 1.主机分组 2.主机信息使用配置文件 3.可批量执行命令.发送文件,结果实时返回 4.主机用户名密码.端口可以不同 5.执行远程命令使用param ...

  3. python 简单主机批量管理工具

    需求: 主机分组 主机信息配置文件用configparser解析 可批量执行命令.发送文件,结果实时返回,执行格式如下  batch_run  -h h1,h2,h3   -g web_cluster ...

  4. 【Python之旅】第六篇(七):开发简易主机批量管理工具

    [Python之旅]第六篇(七):开发简易主机批量管理工具 python 软件开发 Paramiko模块 批量主机管理 摘要: 通过前面对Paramiko模块的学习与使用,以及Python中多线程与多 ...

  5. python运维之使用python进行批量管理主机

    1. python运维之paramiko 2. FABRIC 一个与多台服务器远程交互的PYTHON库和工具 3. SSH连接与自动化部署工具paramiko与Fabric 4. Python批量管理 ...

  6. Python开发程序:简单主机批量管理工具

    题目:简单主机批量管理工具 需求: 主机分组 登录后显示主机分组,选择分组后查看主机列表 可批量执行命令.发送文件,结果实时返回 主机用户名密码可以不同 流程图: 说明: ### 作者介绍: * au ...

  7. MySQL通用批量写入工具(Python)

    背景   平台目前的分析任务主要以Hive为主,分析后的结果存储在HDFS,用户通过REST API或者Rsync的方式获取分析结果,这样的方式带来以下几个问题:   (1)任务执行结束时间未知,用户 ...

  8. Linux系统——Ansible批量管理工具

    批量管理工具: (1)ansible 操作简单(适用于500台以下服务器) (2)saltstack 比较复杂(一般适用于1000-4w台服务器) (3)puppet超级复杂 systemctl(统一 ...

  9. 简单主机批量管理工具(这里实现了paramiko 用su切换到root用户)

    项目名:简单主机批量管理工具 一.需求 1.主机分组 2.可批量执行命令.发送文件,结果实时返回,执行格式如下 batch_run  -h h1,h2,h3   -g web_clusters,db_ ...

随机推荐

  1. TensorFlow 常见错误与解决方法——长期不定时更新

    1. TypeError: Cannot interpret feed_dict key as Tensor: Can not convert a builtin_function_or_method ...

  2. Internet History,Technology and Security

    Internet History,Technology and Security(简单记录) First Week High Stakes Research in Computing,and Comm ...

  3. lintcode-99-重排链表

    99-重排链表 给定一个单链表L: L0→L1→-→Ln-1→Ln, 重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→- 必须在不改变节点值的情况下进行原地操作. 样例 给出链表 1-> ...

  4. Storm之tickTuple

    tickTuple是Storm中引入的一种定时机制,利用tickTuple能够实现间隔一段时间进行某种处理的逻辑. 在boltA中实现tickTuple注册的方法如下 @Override public ...

  5. 配合JAVA的AJAX使用

    概要 Ajax是“Asynchronous JavaScript and XML”的简称,即异步的JavaScript和XML. readyState属性用来返回当前的请求状态,有五个可选值.分别是0 ...

  6. SRM709 div1 Xscoregame(状压dp)

    题目大意: 给定一个序列a,包含n个数(n<=15),每个数的大小小于等于50 初始时x = 0,让你每次选a中的一个数y,使得x = x + x^y 问如何安排选择的次序,使得最终结果最大. ...

  7. perl的Sys::Syslog模块(openlog,syslog,closelog函数,setlogsock)-自定义日志

    perl的Sys::Syslog模块(openlog,syslog,closelog函数,setlogsock)-自定义日志 http://blog.chinaunix.net/xmlrpc.php? ...

  8. win32 application怎么把结果输出到调试窗口

    方法1: TCHAR str[]; wsprintf(str, TEXT(); OutputDebugString(TEXT("-------lala------\n")); Ou ...

  9. 使用XTU降低CPU功耗,自动执行不失效

    INTEL出品的XTU可以用来做软超频操作,给CPU/GPU加电压超频,也可以通过降低CPU/GPU电压来减少功耗. 以前用XTU设置好了之后,过一段时间就自动失效了,最近失效的频率突然很高,于是找了 ...

  10. Codeforces Round #524 (Div. 2) B. Margarite and the best present

    B. Margarite and the best present 题目链接:https://codeforces.com/contest/1080/problem/B 题意: 给出一个数列:an=( ...