类似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 ...
随机推荐
- 【转】shell:date 常用方式
在linux下获取时间字符串 命令 date # 以yyyymmdd格式输出23天之前现在这个时刻的时间 $ date +%Y%m%d –date=’23 days ago’ $ date -u Th ...
- 我的java之路week2类的无参、带参方法
2.1语法 public 返回值类型 方法名(){ //方法体 } 2.2方法的调用语法 对象名.方法名 计算平均分和总成绩 public class Score { /** * 创建类 ScoreC ...
- Jquery之isPlainObject源码分析
今天对Jquery中 isPlainObject 源码分析. 1. isPlainObject 方法的作用: 用来判断传入参数,是否是对象. 2. 源码分析:isPlainObject: funct ...
- BZOJ 1415: [Noi2005]聪聪和可可 [DP 概率]
传送门 题意:小兔子乖乖~~~ 题意·真:无向图吗,聪抓可,每个时间聪先走可后走,聪一次可以走两步,朝着里可最近且点编号最小的方向:可一次只一步,等概率走向相邻的点或不走 求聪抓住可的期望时间 和游走 ...
- 【转】 C/C++程序员必须熟练应用的开源项目
作为一个经验丰富的C/C++程序员, 肯定亲手写过各种功能的代码, 比如封装过数据库访问的类, 封装过网络通信的类,封装过日志操作的类, 封装过文件访问的类, 封装过UI界面库等, 也在实际的项目中应 ...
- My97DatePicker选择两个日期范围不超过30天的demo
需求 ExtJs下使用My97DatePicker对时间范围不超过30天进行选择. 关键点 使用全局变量. 对选择完的第一个日期进行逻辑判断.(我的逻辑能力还有待加强啊) 因为当选择了第一个框范围在超 ...
- python 路飞模块一考核总结
1. 分别解释"=","==","+="的含义(口述) =为赋值语句,把一个变量值赋予另一个值 == 为条件判断,判断两个值是否相等 += ...
- ★MySQL一些很重要的SQL语句
[mysqldumpslow] -s 排序选项:c 查询次数 r 返回记录行数 t 查询时间 -t 只显示top n条查询 mysqldumpslow -s r -t 10000 slow-que ...
- Spring-Security+Freemarker 开启跨域请求伪造防护功能
CSRF简介--摘抄自<Spring实战(第4版)> 我们可以回忆一下,当一个POST请求提交到"/spittles"上时,SpittleController ...
- R学习笔记:了解R的使用
R是一种区分大小写的解释性语言,只支持单行注释,注释由符号#开头,当前行出现在#之后的任何文本都会被R解释器忽略.R脚本的一次执行叫做一个会话(Session),可以通过函数quit()退出当前的会话 ...