类似fabric主机管理demo
类似于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的更多相关文章
- paramiko类Fabric主机管理
环境:Linux python3.5 要求:类 Fabric 主机管理程序开发:1. 运行程序列出主机组或者主机列表2. 选择指定主机或主机组3. 选择让主机或者主机组执行命令或者向其传输文件(上传/ ...
- python10作业思路及源码:类Fabric主机管理程序开发(仅供参考)
类Fabric主机管理程序开发 一,作业要求 1, 运行程序列出主机组或者主机列表(已完成) 2,选择指定主机或主机组(已完成) 3,选择主机或主机组传送文件(上传/下载)(已完成) 4,充分使用多线 ...
- python作业类Fabric主机管理程序开发(第九周)
作业需求: 1. 运行程序列出主机组或者主机列表 2. 选择指定主机或主机组 3. 选择让主机或者主机组执行命令或者向其传输文件(上传/下载) 4. 充分使用多线程或多进程 5. 不同主机的用户名密码 ...
- EasyUI+MVC+EF简单用户管理Demo(问题及解决)
写在前面 iframe-src EntityFramework版本 connectionStrings View.Action.页面跳转 EasyUI中DataGrid绑定 新增.修改和删除数据 效果 ...
- 第一章 权限管理DEMO简介
源代码GitHub:https://github.com/ZhaoRd/Zrd_0001_AuthorityManagement 1.系列介绍 工作已有五年之久,一直有想通过博客写点自己知道的,在博客 ...
- LNMP服务器虚拟主机管理lnmp
安装 系统需求: 需要2 GB硬盘剩余空间 安装步骤: 1.使用putty或类似的SSH工具登陆:登陆后运行:screen -S lnmp如果提示screen命令不存在可以执行:yum install ...
- mvc 权限管理 demo
http://blog.csdn.net/zht666/article/details/8529646 new http://www.cnblogs.com/fengxing/archive/2012 ...
- Windows 2008 R2 X64 安装WebsitePanel(WSP虚拟主机管理面板)
Windows 2008 R2 X64 安装WebsitePanel(WSP2.0虚拟主机管理面板) 估计很多同学都还不知道WebsitePanel是什么东东吧,Web ...
- (转载)运行主机管理在openvswitch之上
在这篇文章里介绍了如果运行主机管理在openvswitch之上,而不是单独配置一个物理网卡用于主机管理,并且所有的vm的流量还是通过openvswitch走的. Running Host Manage ...
随机推荐
- mysql has gone away
mysql出现ERROR : (2006, 'MySQL server has gone away') 的问题意思就是指client和MySQL server之间的链接断开了. 造成这样的原因一般是s ...
- JS学习--DOM
1.概念 文档对象模型DOM,定义访问和处理HTML文档的标准方法.DOM将HTML呈现为带有元素.属性和文本的树结构(节点树). 2.document.getElementById("id ...
- 企业级Docker私有仓库部署(https)
部署环境 Centos7.3 x64 docker-ce-17.06.0 docker-compose-1.15.0 Python-2.7.5(系统默认) 部署目标 使用HTTPS协议 支持Clair ...
- Acrobat 转换pdf到png的另一种方法
此方法效率较低,大概2秒转3页pdf成png图片,但是可以保证图片质量很高,分辨率很高.有优化的地方,但没时间研究.先放代码吧. 前提是安装 acrobat 11(即acrobat xi) CAcro ...
- Spring源码情操陶冶-自定义节点的解析
本文承接前文Spring源码情操陶冶-DefaultBeanDefinitionDocumentReader#parseBeanDefinitions,特开辟出一块新地来啃啃这块有意思的骨头 自定义节 ...
- WebService 的工作原理
Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的 ...
- hdu 5909 Tree Cutting [树形DP fwt]
hdu 5909 Tree Cutting 题意:一颗无根树,每个点有权值,连通子树的权值为异或和,求异或和为[0,m)的方案数 \(f[i][j]\)表示子树i中经过i的连通子树异或和为j的方案数 ...
- BZOJ 3907: 网格 [Catalan数 高精度]
3907: 网格 Time Limit: 1 Sec Memory Limit: 256 MBSubmit: 402 Solved: 180[Submit][Status][Discuss] De ...
- Java常用日志框架介绍
Java常用日志框架介绍 java日志概述 对于一个应用程序来说日志记录是必不可少的一部分.线上问题追踪,基于日志的业务逻辑统计分析等都离不日志.java领域存在多种日志框架,目前常用的日志框架包括L ...
- 关于Git的版本问题
问题的起源 我在IDEA上不小心修改了文件(加了一行空行)并且被保存了,在GitHub Desktop桌面工具上可以看到changes中有修改记录,并且使用命令行git status也可以看到文件的修 ...