Table of Contents
1. Requirements" >1. Requirements
2. Simple requirements analysis and flow chart" >2. Simple requirements analysis and flow chart
Home Backend Development Python Tutorial Detailed graphic explanation of Python's simple host batch management tool

Detailed graphic explanation of Python's simple host batch management tool

Mar 15, 2017 pm 03:28 PM
python

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)

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)
Copy after login
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},
    }
}
Copy after login

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>>>
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is distinctIdistinguish related? Is distinctIdistinguish related? Apr 03, 2025 pm 10:30 PM

Although distinct and distinct are related to distinction, they are used differently: distinct (adjective) describes the uniqueness of things themselves and is used to emphasize differences between things; distinct (verb) represents the distinction behavior or ability, and is used to describe the discrimination process. In programming, distinct is often used to represent the uniqueness of elements in a collection, such as deduplication operations; distinct is reflected in the design of algorithms or functions, such as distinguishing odd and even numbers. When optimizing, the distinct operation should select the appropriate algorithm and data structure, while the distinct operation should optimize the distinction between logical efficiency and pay attention to writing clear and readable code.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to understand !x in C? How to understand !x in C? Apr 03, 2025 pm 02:33 PM

!x Understanding !x is a logical non-operator in C language. It booleans the value of x, that is, true changes to false, false changes to true. But be aware that truth and falsehood in C are represented by numerical values ​​rather than boolean types, non-zero is regarded as true, and only 0 is regarded as false. Therefore, !x deals with negative numbers the same as positive numbers and is considered true.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

What does sum mean in C language? What does sum mean in C language? Apr 03, 2025 pm 02:36 PM

There is no built-in sum function in C for sum, but it can be implemented by: using a loop to accumulate elements one by one; using a pointer to access and accumulate elements one by one; for large data volumes, consider parallel calculations.

Copy and paste Love code Copy and paste Love code for free Copy and paste Love code Copy and paste Love code for free Apr 04, 2025 am 06:48 AM

Copying and pasting the code is not impossible, but it should be treated with caution. Dependencies such as environment, libraries, versions, etc. in the code may not match the current project, resulting in errors or unpredictable results. Be sure to ensure the context is consistent, including file paths, dependent libraries, and Python versions. Additionally, when copying and pasting the code for a specific library, you may need to install the library and its dependencies. Common errors include path errors, version conflicts, and inconsistent code styles. Performance optimization needs to be redesigned or refactored according to the original purpose and constraints of the code. It is crucial to understand and debug copied code, and do not copy and paste blindly.

What is the meaning of sum in C language? What is the meaning of sum in C language? Apr 03, 2025 pm 02:09 PM

Methods for summing array elements in C language: Use a loop to accumulate array elements one by one. For multidimensional arrays, use nested loops to traverse and accumulate. Be sure to check the array index carefully to avoid out-of-bounds access causing program crashes.

See all articles