search
HomeBackend DevelopmentPython TutorialDetailed graphic explanation of Python's simple host batch management tool

I did a very simple small project today. I felt the power of the paramiko module, and I also felt that my Linux skills were not good~~

1. Requirements

Detailed graphic explanation of Pythons simple host batch management tool

2. Simple requirements analysis and flow chart


There are very few requirements, so I will simply say:
1. HostGroup can be configured fileimplemented (I use a dictionary to store data ).
2. The login function does not work. After selecting a group, you can view the host name and IP address of the corresponding host in the group. Depends on the host) Executed simultaneously)
Output:
-------------h1--------- ---
    …(data returned by the command)
                                                                                                                                                   by thereby -----
   ……
   >>>put test.yy (local file) file
name (put local The test.yy file is transferred to the /root directory of the remote host) 4. It can be written in the configuration file. Including the remote host: Host name IP User name Password Port

Flow chart

Detailed graphic explanation of Pythons simple host batch management tool

3.

Directory structure

and source code

Directory structure:

Detailed graphic explanation of Pythons simple host batch management tool##from_windows.py(to be

uploaded

file)

main

.py(Batch Host ManagementInterface)

"""批量主机管理接口"""

import core

if name == "main":
    core.run()
core.py( Core code, called by the interface)

"""核心代码"""
import settings
import paramiko
import threading
import os


class REMOTE_HOST(object):
    #远程操作主机
    def init(self, host, port ,username, password, cmd):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.cmd = cmd

    def run(self):
        """起线程连接远程主机后调用"""
        cmd_str = self.cmd.split()[0]
        if hasattr(self, cmd_str):      #反射 eg:调用put方法
            getattr(self, cmd_str)()
        else:
            #setattr(x,'y',v)is  equivalent  to   ``x.y=v''
            setattr(self, cmd_str, self.command)
            getattr(self, cmd_str)()  #调用command方法,执行批量命令处理

    def command(self):
        """批量命令处理"""
        ssh = paramiko.SSHClient()  #创建ssh对象
        #允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=self.host,port=self.port,username=self.username,password=self.password)
        stdin,stdout,stderr = ssh.exec_command(self.cmd)
        result = stdout.read()
        print("%s".center(50, "-") % self.host)
        print(result.decode())
        ssh.close()

    def put(self):
        """上传文件"""
        filename = self.cmd.split()[1]  #要上传的文件
        transport = paramiko.Transport((self.host, self.port))
        transport.connect(username=self.username, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.put(filename, filename)
        print("put sucesss")

        transport.close()


def show_host_list():
    """通过选择分组显示主机名与IP"""
    for index, key in enumerate(settings.msg_dic):
        print(index + 1, key, len(settings.msg_dic[key]))
    while True:
        choose_host_list = input(">>>(eg:group1)").strip()
        host_dic = settings.msg_dic.get(choose_host_list)
        if host_dic:
            #print(host_dic)
            for key in host_dic:
                print(key, host_dic[key]["IP"])
            return host_dic
        else:
            print("NO exit this group!")


def interactive(choose_host_list):
    """根据选择的分组主机起多个线程进行批量交互"""
    thread_list = []
    while True:
        cmd = input(">>>").strip()
        if cmd:
            for key in choose_host_list:
                host, port, username, password = choose_host_list[key]["IP"], choose_host_list[key]["port"], \
                                                 choose_host_list[key]["username"], choose_host_list[key]["password"]
                func = REMOTE_HOST(host, port, username, password, cmd)  # 实例化类
                t = threading.Thread(target=func.run)  # 起线程
                t.start()
                thread_list.append(t)
            for t in thread_list:
                t.join()  # 主线程等待子线程执行完毕
        else:
            continue


def run():
    choose_host_list = show_host_list()
    interactive(choose_host_list)
settings.py (configuration file)

"""配置文件"""

msg_dic = {
    "group1":{    #分组1
        "h1":{"IP":"192.168.1.1", "username":"11", "password":"aa", "port":22},
        "h2":{"IP":"192.168.1.2", "username":"22", "password":"bb", "port":22},
        "h3":{"IP":"192.168.1.3", "username":"33", "password":"cc", "port":22},
        "h4":{"IP":"192.168.1.4", "username":"44", "password":"dd", "port":22},
        "h5":{"IP":"192.168.1.5", "username":"55", "password":"ee", "port":22},
        "h6":{"IP":"192.168.1.6", "username":"66", "password":"ff", "port":22},
    },

    "group2":{    #分组2
        "h1":{"IP":"192.168.2.1", "username":"111", "password":"aaa", "port":22},
        "h2":{"IP":"192.168.2.2", "username":"222", "password":"bbb", "port":22},
        "h3":{"IP":"192.168.2.3", "username":"333", "password":"ccc", "port":22},
        "h4":{"IP":"192.168.2.4", "username":"444", "password":"ddd", "port":22},
        "h5":{"IP":"192.168.2.5", "username":"555", "password":"eee", "port":22},
        "h6":{"IP":"192.168.2.6", "username":"666", "password":"fff", "port":22},
        "h7":{"IP":"192.168.2.7", "username":"777", "password":"ggg", "port":22},
        "h8":{"IP":"192.168.2.8", "username":"888", "password":"hhh", "port":22},
    },

    "group3":{
        "h1":{"IP":"192.168.179.133", "username":"root", "password":"zcl", "port":22},
    }
}

Test:

Hardware limitations, I only need to connect to one virtual machine for testing~

C:\Python34\python3.exe C:/Users/Administrator/PycharmProjects/laonanhai/host_manage/main.py1 group1 6
2 group3 1
3 group2 8
>>>(eg:group1)group3
h1 192.168.179.133
>>>put from_windows.py
put sucesss>>>
>>>ls------------------------192.168.179.133------------------------anaconda-ks.cfg
database_test
from_windows.py
install.log
install.log.syslog
m
oot
\root
tmp\from_windows.py>>>

Before uploading There is no from_windows.py file, but there will be after uploading!


Detailed graphic explanation of Pythons simple host batch management tool

The above is the detailed content of Detailed graphic explanation of Python's simple host batch management tool. 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
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),