类似于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. 【django之用户认证】

    一.auth模块 模块导入 from django.contrib import auth 主要方法如下: 1 .authenticate()    提供了用户认证,即验证用户名以及密码是否正确,一般 ...

  2. mui页面跳转(传值+接收)

    <script type="text/javascript" charset="utf-8"> mui.init(); mui.plusReady( ...

  3. BZOJ 4008: [HNOI2015]亚瑟王 [DP 概率 !!!]

    传送门 题意: $r$轮$n$张卡牌,每一轮依次考虑每张卡牌,$p_i$概率发动造成$d_i$伤害后结束本轮或者继续考虑下一张 每张卡牌发动过之后以后都会跳过 求$r$轮之后的期望伤害 看了一节课出题 ...

  4. POJ 2888 Magic Bracelet [Polya 矩阵乘法]

    传送门 题意:竟然扯到哈利波特了.... 和上一题差不多,但颜色数很少,给出不能相邻的颜色对 可以相邻的连边建图矩阵乘法求回路个数就得到$f(i)$了.... 感觉这样的环上有限制问题挺套路的...旋 ...

  5. BZOJ 3670: [Noi2014]动物园 [KMP]

    求这玩意: 对于字符串S的前i个字符构成的子串,既是它的后缀同时又是它的前缀,并且该后缀与该前缀不重叠,将这种字符串的数量记作num[i] 对1,000,000,007取模的结果 n≤5,L≤1,00 ...

  6. AWS-SS配置过程

    为满足家长要求,以下只录步骤: 远端: 1. 注册并启动一个AWS实例.这一步网上N多教程,搜 AWS EC2 等均可. 2. 远程安装SS,并写配置文件.依然网搜, AWS S(hadow)S(oc ...

  7. Java实现单链表的快速排序和归并排序

    本文描述了LeetCode 148题 sort-list 的解法. 题目描述如下: Sort a linked list in O(n log n) time using constant space ...

  8. Websocket原理及使用场景[转载]

    WebSocket的使用场景 社交聊天.弹幕.多玩家游戏.协同编辑.股票基金实时报价.体育实况更新.视频会议/聊天.基于位置的应用.在线教育.智能家居等需要高实时的场景 由轮询到WebSocket 1 ...

  9. 安装RabbitMQ(一)

    RabbitMQ简介 RabbitMQ 是由 LShift 提供的一个 Advanced Message Queuing Protocol (AMQP) 的开源实现,由以高性能.健壮以及可伸缩性出名的 ...

  10. 关于 IO的同步异步间要描述

    IO在计算机中指Input/Output,也就是输入和输出.由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口. 比如你打开 ...