类似于fabric的主机管理系统

可以批量对主机进行操作

  • 批量上传文件
  • 批量下载文件
  • 批量执行命令

demo代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author : Leon
# Date 2017/6/27 import threading
import paramiko
from conf import HOST_MAP
lock = threading.Lock() class MyFabric(object):
'''MyFabric'''
def __init__(self):
self.show()
self.run() def run(self):
while True:
ChoiceList = input("请输入选择的主机编号,一个或多个,多个请空格隔开,一个组请以group作为关键字开始[exit退出]:").strip().split()
if ChoiceList[0] == "exit":
exit("Bye")
elif ChoiceList[0] == "group":
self.ChoiceHost = [] #清空
GroupName = ChoiceList[1]
for host in HOST_MAP:
if HOST_MAP[host]["group"] == GroupName:
self.ChoiceHost.append(host)
print("经过输入帅选,确认选择的主机以及编号".center(25, '#')) for index in self.ChoiceHost:
print("[{host}]".format(host=index))
confirm = input("请确认[yes/no]:").strip().lower()
if confirm:
if confirm == "yes":
# 选择想要执行的动作
action = input("请输入想要执行的动作(put/get/cmd):").strip()
if hasattr(self, action):
func = getattr(self, action)
func()
print("\033[36mThe End\033[0m".center(30, '-'))
elif confirm == "no":
continue
else:
self.ChoiceHost = []
for item in self.IndexHOST_MAP:
if str(self.IndexHOST_MAP[item]["index"]) in ChoiceList:
self.ChoiceHost.append(item)
print("经过输入帅选,确认选择的主机以及编号".center(25, '#'))
for index in self.ChoiceHost:
print("[{host}]".format(host=index))
confirm = input("请确认[yes/no]:").strip().lower()
if confirm:
if confirm == "yes":
# 选择想要执行的动作
action = input("请输入想要执行的动作(put/get/cmd):").strip()
if hasattr(self, action):
func = getattr(self, action)
func()
print("\033[36mThe End\033[0m".center(30, '-'))
elif confirm == "no":
continue def show(self):
self.IndexHOST_MAP = HOST_MAP
print("\033[32mhost list\033[0m".center(20, '-'))
for index,host in enumerate(HOST_MAP):
print("[{index}]:{host}".format(index=index, host=host))
self.IndexHOST_MAP[host]["index"] = index #添加一个index字段 def _put_file(self,host,port,user,password,LocalPath,ServerPath):
try:
t = paramiko.Transport((host,port))
t.connect(username=user, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(LocalPath, ServerPath)
t.close()
print("\033[32m从[{host}]上传成功!\033[0m".format(host=host))
return True except Exception as e:
print(e)
print("\033[31m从[{host}]上传失败!\033[0m".format(host=host))
return False def _get_file(self,host,port,user,password,ServerPath,LocalPath):
try:
t = paramiko.Transport((host, port))
t.connect(username=user, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(ServerPath, LocalPath)
t.close()
print("\033[32m从[{host}]下载成功!\033[0m".format(host=host))
return True
except Exception as e:
print(e)
print("\033[31m从[{host}]下载失败!\033[0m".format(host=host))
return False def _exec_command(self,host,port,user,password,command):
lock.acquire()
try:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(host, port, user, password)
std_in, std_out, std_err = ssh_client.exec_command(command)
print("\033[32m[{host}]命令执行成功\033[0m".format(host=host))
for line in std_out:
print(line.strip("\n"))
ssh_client.close()
except Exception as e:
print(e)
print("\033[31m[{host}]命令执行失败\033[0m".format(host=host))
lock.release() def get(self):
ServerPath = input("请输入需要批量下载的远程文件文件名[eg:/etc/passwd]:").strip()
LocalPath = input("请输入文件本地存放的目录以及文件名[eg:/home/passwd]:").strip()
ThreadList = []
for item in self.ChoiceHost:
t = threading.Thread(target=self._get_file,args=(item,
HOST_MAP[item]["port"],
HOST_MAP[item]["username"],
HOST_MAP[item]["password"],
ServerPath,LocalPath+"_from_"+item,))
ThreadList.append(t)
for t in ThreadList:
t.start()
t.join() def put(self):
LocalPath = input("请输入需要上传的本地文件地址[eg:/home/passwd]:").strip()
ServerPath = input("请输入远程存放目录以及文件名[eg:/etc/passwd]").strip()
ThreadList = []
for item in self.ChoiceHost:
t = threading.Thread(target=self._put_file, args=(item,
HOST_MAP[item]["port"],
HOST_MAP[item]["username"],
HOST_MAP[item]["password"],
LocalPath,
ServerPath,))
ThreadList.append(t)
for t in ThreadList:
t.start() def cmd(self):
command = input("请输入需要批量执行的命令:[eg:hostanme]").strip()
ThreadList = []
for item in self.ChoiceHost:
t = threading.Thread(target=self._exec_command, args=(item,
HOST_MAP[item]["port"],
HOST_MAP[item]["username"],
HOST_MAP[item]["password"],
command,))
ThreadList.append(t)
for t in ThreadList:
t.start()
t.join() if __name__ == '__main__':
obj = MyFabric()

配置文件

HOST_MAP = {
"10.215.24.30":{
"port":22,
"username":"root",
"password":"123456",
"group":"test"
},
"10.215.24.31":{
"port":22,
"username":"root",
"password":"123456",
"group":"test1"
},
"10.215.24.32": {
"port": 22,
"username": "root",
"password": "123456",
"group": "test1"
}
}

涉及的知识点

  • paramiko模块的使用
  • 多线程
  • 反射

类似fabric主机管理demo的更多相关文章

  1. paramiko类Fabric主机管理

    环境:Linux python3.5 要求:类 Fabric 主机管理程序开发:1. 运行程序列出主机组或者主机列表2. 选择指定主机或主机组3. 选择让主机或者主机组执行命令或者向其传输文件(上传/ ...

  2. python10作业思路及源码:类Fabric主机管理程序开发(仅供参考)

    类Fabric主机管理程序开发 一,作业要求 1, 运行程序列出主机组或者主机列表(已完成) 2,选择指定主机或主机组(已完成) 3,选择主机或主机组传送文件(上传/下载)(已完成) 4,充分使用多线 ...

  3. python作业类Fabric主机管理程序开发(第九周)

    作业需求: 1. 运行程序列出主机组或者主机列表 2. 选择指定主机或主机组 3. 选择让主机或者主机组执行命令或者向其传输文件(上传/下载) 4. 充分使用多线程或多进程 5. 不同主机的用户名密码 ...

  4. EasyUI+MVC+EF简单用户管理Demo(问题及解决)

    写在前面 iframe-src EntityFramework版本 connectionStrings View.Action.页面跳转 EasyUI中DataGrid绑定 新增.修改和删除数据 效果 ...

  5. 第一章 权限管理DEMO简介

    源代码GitHub:https://github.com/ZhaoRd/Zrd_0001_AuthorityManagement 1.系列介绍 工作已有五年之久,一直有想通过博客写点自己知道的,在博客 ...

  6. LNMP服务器虚拟主机管理lnmp

    安装 系统需求: 需要2 GB硬盘剩余空间 安装步骤: 1.使用putty或类似的SSH工具登陆:登陆后运行:screen -S lnmp如果提示screen命令不存在可以执行:yum install ...

  7. mvc 权限管理 demo

    http://blog.csdn.net/zht666/article/details/8529646 new http://www.cnblogs.com/fengxing/archive/2012 ...

  8. Windows 2008 R2 X64 安装WebsitePanel(WSP虚拟主机管理面板)

                   Windows 2008 R2 X64  安装WebsitePanel(WSP2.0虚拟主机管理面板) 估计很多同学都还不知道WebsitePanel是什么东东吧,Web ...

  9. (转载)运行主机管理在openvswitch之上

    在这篇文章里介绍了如果运行主机管理在openvswitch之上,而不是单独配置一个物理网卡用于主机管理,并且所有的vm的流量还是通过openvswitch走的. Running Host Manage ...

随机推荐

  1. awk 实用技巧

    awk 用法:awk ' pattern {action} ' 变量名 含义ARGC 命令行变元个数ARGV 命令行变元数组FILENAME 当前输入文件名FNR 当前文件中的记录号FS 输入域分隔符 ...

  2. Linux时间转标准时间

    [root@nhserver2 ~]# date -d '1970-1-1 0:0:0 GMT + 1394592071 seconds'Wed Mar 12 10:41:11 CST 2014

  3. JS-使用工厂方法创建对象

    function createPerson(name,age,gender){ //创建新对象 var obj=new Object(); //向对象中添加属性 obj.name=name; obj. ...

  4. 小白的.Net Core 2.0 ConsoleApp入门(keng)指南(一)

    一.准备工作 准备工作很简单,甚至可以不用Visual Studio,一只.NET CORE和Runtime即可(你有考虑过世界第一IDE的感受吗) 下载:https://www.microsoft. ...

  5. [Android] Toast问题深度剖析(一)

    欢迎大家前往云+社区,获取更多腾讯海量技术实践干货哦~ 题记 Toast 作为 Android 系统中最常用的类之一,由于其方便的api设计和简洁的交互体验,被我们所广泛采用.但是,伴随着我们开发的深 ...

  6. Python CRM项目六

    自定义Django Admin的action 在Django Admin中,可以通过action来自定义一些操作,其中默认的action的功能是选中多条数据来进行删除操作 我们在king_admin中 ...

  7. angular js $post,$get请求传值

    困扰了我好几天的问题!!! 刚开始学play框架,在向后台传值时,一直不成功! 当你用$POST传递一个参数时: HTML: <button ng-click=test()>测试</ ...

  8. 单元测试系列:JUnit单元测试规范

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 原文链接:http://www.cnblogs.com/zishi/p/6762032.html Junit测试代 ...

  9. 梅安森元图地图开放平台、专业GIS地图平台

    元图地图开放平台:http://map.cmetamap.com/?from=groupmessage 梅安森元图地图开放平台: 自主知识产权,专业GIS地图平台,用简单语言即可轻松操作复杂的互联网地 ...

  10. BZOJ 2115: [Wc2011] Xor [高斯消元XOR 线性基 图]

    啦啦啦 题意: N 个点M条边的边带权的无向图,求1到n一条XOR和最大的路径 感觉把学的东西都用上了.... 1到n的所有路径可以由一条1到n的简单路径异或上任意个简单环得到 证明: 如果环与路径有 ...