search
HomeBackend DevelopmentPython TutorialShare examples about the development of Fabric-like host management programs

Fabric-like host management program development:
1. Run the program to list the host group or host list
2. Select the specified host or host group
3. Select to let the host or host group execute commands or send commands to Its transfer file (upload/download)
4. Make full use of multi-threading or multi-process
5. The username, password, and port of different hosts can be different

README

类 Fabric 主机管理程序
执行命令(SSH)
向其传输文件(上传/下载)

Fabric/#程序目录
|- - -__init__.py
|- - -bin/#启动目录
|      |- - -__init__.py
|      |- - -Fabric_start.py#视图启动
|      |- - -user_reg.py#主机添加启动
|
|- - -cfg/#配置目录
|      |- - -__init__.py
|      |- - -config.py#配置文件
|
|- - -core/#下载文件目录
|      |- - -__init__.py
|      |- - -main.py#主要逻辑 类
|
|- - -db/#主机列表文件目录
|      |- - -
|
|- - -get_file/#下载文件目录
|
|
|- - -put_file/#上传文件目录
|- - -REDMAE
Fabric/#程序目录
|- - -__init__.py
|- - -bin/#启动目录
|      |- - -__init__.py
|      |- - -Fabric_start.py#视图启动
1 import configparser2 import os ,sys3 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量4 sys.path.append(BASE_DIR)#增加环境变量5 from core.main import loging6 if __name__ == '__main__':7 8     loging()
View Code
|      |- - -user_reg.py#主机添加启动
 1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4  5 import configparser 6 import os ,sys 7 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量 8 sys.path.append(BASE_DIR)#增加环境变量 9 from cfg import config10 #修改个信息 磁盘大小11 def set_info(gr_name,addse,name,pwd,ports):12     config_info=configparser.ConfigParser()#读数据13     file_dir='%s%s'%(config.AUTH_FILE,gr_name)#主机组用户名密码文件路径14 15     config_info[addse]={}#ip 主机16     config_info.set(addse,config.USER,name)#用户17     config_info.set(addse,config.PWD,pwd)#密码18     config_info.set(addse,config.PORTS,ports)#端口19     with open(file_dir,'a') as f:20         config_info.write(f)#写入文件21     #config_info.write(open(file_dir,'a'))#写入文件22     print('创建完成'.center(60,'='))23     print('组:【%s】\nIP:[%s]\n用户名:[%s]\n密码:[%s]\n端口:[%s]'%(gr_name,addse,name,pwd,ports))24 25 if __name__ == '__main__':26     gr_name=input('组名:')#组27     addse=input('IP地址:')#ip地址28     name=input('用户名:')#用户29     pwd=input('密码:')#密码30     ports=input('端口:')#端口31     32     set_info(gr_name,addse,name,pwd,ports)
View Code
|- - -cfg/#配置目录
|      |- - -__init__.py
|- - -config.py#配置文件
 1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4  5 import configparser 6 import os ,sys 7 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量 8 sys.path.append(BASE_DIR)#增加环境变量 9 10 AUTH_FILE='%s/db/'%BASE_DIR#主机组 信息用户名密码文件路径11 FILE_DIR='%s/put_file'%BASE_DIR#要上传文件所在的目录12 GET_FILE_DIR='%s/get_file'%BASE_DIR#要上传文件所在的目录13 #print(AUTH_FILE)14 PWD='pwd'#密码15 USER='user'16 PORTS='ports'17 INST_LIST=['put','get']#指令列表18 19 PUT='put'20 GET='get'
View Code
|- - -core/#下载文件目录
|      |- - -__init__.py
|      |- - -main.py#主要逻辑 类
  1 #!usr/bin/env python  2 #-*-coding:utf-8-*-  3 # Author calmyan  4   5 import configparser  6 import os ,sys  7 import threading,time  8 import paramiko,queue  9 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量 10 sys.path.append(BASE_DIR)#增加环境变量 11 from cfg import config 12  13 class Fabric_gr(object): 14     def __init__(self,gr_name):#组名 15         self.gr_name='%s%s'%(config.AUTH_FILE,gr_name)#主机组用户名密码文件路径 16         self.config_info=configparser.ConfigParser()#读数据对象 17         self.name_l=[]#定义一个列表 18         self.attr=[] 19         self.file_dir=''#上传文件路径 20         self.get_file=''#下载传文件路径 21  22     def group_open(self):#打开组文件 23         self.config_info.read(self.gr_name)#读取文件 24         for i in range(len(self.config_info.sections())): 25             self.name_l.append(self.config_info.sections()[i])#信息添加到列表 26         else: 27             print('主机列表:'.center(40,'=')) 28             for i in self.name_l: 29                 print(('[%s]'%i).center(40,' ')) 30  31     def inst_attr(self,inst):#获取指令 32         self.instruction=inst 33         self.attr=self.instruction.split() 34         self.inst_a=self.attr[0] 35  36     def inst(self):#指令判断 37         if self.inst_a in config.INST_LIST: 38             return True 39         else: 40             return False 41  42     def open_list(self):#创建 线程 方法 43         if self.inst_a==config.PUT: 44             if self.File_Dir():#查找本地文件 45                 pass 46             else: 47                 return 48         self.re_lilst=[]#定义一个列表 49         for j in range(len(self.name_l)): 50             sttr=self.config_info.sections()[j]#获取到对象 51             user_dict={}#创建一个空字典 52             for i,v in self.config_info[sttr].items():#可以循环输出 获ip 用户 密码 端口 53                 user_dict[i]=v 54             sttr=threading.Thread(target=self.thr_run,args=(sttr,user_dict[config.USER],user_dict[config.PWD],int(user_dict[config.PORTS])))#创建新线程 55             sttr.start()#启动线程 56             self.re_lilst.append(sttr)#不用JOIN,避免阻塞为串行 57         else: 58             for i in self.re_lilst:#等待线程 完成 59                 i.join() 60  61     def open_list2(self):#创建 线程 方法 62         self.re_lilst=[]#定义一个列表 63         for j in range(len(self.name_l)): 64             sttr=self.config_info.sections()[j]#获取到对象 65             user_dict={}#创建一个空字典 66             for i,v in self.config_info[sttr].items():#可以循环输出 获ip 用户 密码 端口 67                 user_dict[i]=v 68             sttr=threading.Thread(target=self.ssh_run,args=(sttr,user_dict[config.USER],user_dict[config.PWD],int(user_dict[config.PORTS])))#创建新线程 69             sttr.start()#启动线程 70             self.re_lilst.append(sttr)#不用JOIN,避免阻塞为串行 71         else: 72             for i in self.re_lilst:#等待线程 完成 73                 i.join() 74  75  76     def thr_run(self,addrs,user,paswd,ports):#传输通道 77         try: 78             transport=paramiko.Transport((addrs,ports))#传输模块  Transport  服务器地址 端口 79             transport.connect(username=user,password=paswd)#用户名,,密码 80             sftp=paramiko.SFTPClient.from_transport(transport)#调用传输方法 81             print('[%s]连接成功!'%addrs) 82             self.file_dir='%s/%s'%(config.FILE_DIR,self.attr[1])#上传文件路径 83             if self.inst_a==config.PUT: 84                 sftp.put(self.file_dir,self.attr[2])#上传文件 ,本地路径文件  ,服务器的路径文件 85                 print('【%s】文件上传完成!'%addrs) 86             elif self.inst_a==config.GET: 87                 self.get_file='%s/%s_%s'%(config.GET_FILE_DIR,addrs,self.attr[2])#下载文件路径 88                 print(self.get_file) 89                 sftp.get(self.attr[1],self.get_file)#下载文件 ,服务器的路径文件 ,本地路径文件 90                 print('【%s】文件下载完成!'%addrs) 91             else: 92                 print('【%s】文件相关操作失败!'%addrs) 93                 pass 94         except Exception as e: 95             print(e) 96  97     def File_Dir(self):#判断文件是否存在 98         file=self.attr[1] 99 100         print(file)101         self.file_dir='%s/%s'%(config.FILE_DIR,file)#文件路径102         if os.path.isfile(self.file_dir):103             print('成功找到文件!')104             return True105         else:106             print('文件不存在!')107             return False108     def ssh_run(self,addrs,user,paswd,ports):#ssh109         ssh =paramiko.SSHClient()#创建一个SSH连接对象110         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#允许连接不在KNOV_HOSTs文件中的主机 自动添加111         try:112             ssh.connect(hostname=addrs,port=ports,username=user,password=paswd)#连接,主机 端口  用户名 密码113             print('[%s]连接成功!'%addrs)114         except Exception as e:115             print(e)116             return117         stdin,stdout,stderr=ssh.exec_command(self.instruction)#.exec_command 为执行命令,返回结果  ,标准输入,标准输出,标准错误,错误与输出只会返回其一118         result=stdout.read()#获取结果119         try:120             if len(result)>>:')162                 if inst=='exit':163                     exit()164                 if inst=='quit':165                     continue166                 if inst=='helps':167                     print(info_l)168                     continue169                 lst.inst_attr(inst)#获取指令170                 if lst.inst():#指令判断171                     lst.open_list()#开启线程创建172                 else:173                     lst.open_list2()174                 pass175         except ValueError as e:176             print(e)
View Code

The above is the detailed content of Share examples about the development of Fabric-like host management programs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool