In Daily O & M work, batch host management is very common. There are also a lot of software on the market for batch host management, but sometimes these software cannot fully meet our needs. In python, the module about batch host management is provided. today, let's take a look at how to use python to implement batch host management. in Daily O & M work, batch host management is very common, there are also a lot of software for batch host management on the market, but sometimes these software cannot fully meet our needs. In python, the module about batch host management is provided. today, let's take a look at how to implement batch host management using python.
Python provides three main modules for batch host management: paramiko, fabric, and pexpect. today we mainly talk about the paramiko module, and the paramiko module is a third-party module.
Installation: pip install paramiko or yum install python-paramiko. if installation fails, use the source code for installation.
SOURCE package: https://github.com/paramiko/paramiko/archive/master.zip
Common operations:
Ssh = paramiko. SSHClient () // instantiation, ssh session class
Ssh. set_missing_host_key_policy (paramiko. AutoAddPolicy () // The first connection automatically returns yes
Ssh. connect ('server IP', port, 'username', 'password') // connect to the server
Stdin, stdout, stderr = ssh.exe c_command ("command") // run the command, standard output, return successful command, return failed command
Ssh. close () // close the connection
Upload and download:
Get_put = paramiko. Transport (ip, port) // server ip address and port (used when SFTP is used)
Get_put.connect (username = "root", password = "123.com") // connect to the server, user name, and password
Sftp = paramiko. SFTPClient. from_transport (get_put) // use the SFTP protocol
Sftp. put (the file to be uploaded, the location where the uploaded file is saved) // Upload
Sftp. get (Download location, download location) // download
Batch host management:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
Import paramiko
Import OS
Def Connect (ip = '2017. 0.0.1 ', Port = 22, user = 'root', pwd = '2017. com '):
Ssh = paramiko. SSHClient ()
Ssh. set_missing_host_key_policy (paramiko. AutoAddPolicy ())
Ssh. connect (hostname = ip, port = Port, username = user, password = pwd) # connect to the server
Return ssh # return server handle
Def IP_ADD (ip): # determines whether the user inputs an address or an address range.
_ Ip = ip. split ('--')
If len (_ ip) = 2: # if it is an address range
Ip_add = _ ip [0] # retrieve the ip address
Ip_range = int (_ ip [1]) # retrieve the maximum value of an ip address
Host_ip_split = ip_add.split ('.') # Separate the ip addresses by. into 4 segments.
Host_ip = int (host_ip_split.pop () # obtain the minimum ip address.
Ip_3 = '.'. join (host_ip_split) + '.' # splice the remaining parts that have been removed from the minimum ip value.
Host_add_range = range (host_ip, ip_range + 1) # Generate the connection ip range
Add_pool = []
For I in host_add_range:
Add = ip_3 + str (I) # splice to a valid IP address
Add_pool.append (add) # generate an address pool
Return add_pool # return address pool
Elif len (_ ip) = 1: # if the input is a single address
Valid_ip = _ ip [0]
Ip_value = valid_ip.split ('.') [0: 4] # Check ip validity
[Int (I) for I in ip_value]
Return _ ip # return address
If _ name _ = '_ main __':
OS. system ('clear ')
Fa = True
While Fa:
Ip = raw_input ('Enter an ip address or address range :')
Exclude_ip = raw_input ('Enter the address to be excluded :')
Try:
Ip_list = IP_ADD (ip) # hand over the ip address entered by the user to the function for processing
If exclude_ip.strip (): # determine whether the user wants to exclude the addresses in the address pool.
Exclude_add = exclude_ip.split (',') # define the exclusion format
[Ip_list.remove (I) for I in exclude_add] # exclude IP addresses
Fa = False # exit the loop
Except t:
Print '\ 033 [31m address format error \ 033 [0m'
Print ''' example:
127.0.0.1 perform operations on a single host
127.0.0.1 -- 254 perform operations on hosts in the same address range
127.0.0.8, 127.0.0.10 exclude addresses in the address pool
'''
Continue
Print '\ 033 [31m input script_exit exit program \ 033 [0m'
While True:
Shell_comd = raw_input ('Enter the command to execute: ') # The command to be executed
If shell_comd = 'script _ exit ':
Break
For I in ip_list: # Loop address pool
Try:
Comd = Connect (ip = I) # Connect to the server
Stdin, stdout, stderr = comd.exe c_command (shell_comd) # run the command
Stderr = stderr. read () # Result of correct command execution
Stdout = stdout. read () # command executed incorrectly
If stdout:
Print '\ 033 [31 m ++ % s ++ \ 033 [0m' % I
# Commands executed by that server
Print stdout
Else:
Print '\ 033 [31 m ++ % s ++ \ 033 [0m' % I
Print stderr
Except t:
Print '\ 033 [31 m % s connection failed \ 033 [0m' % I
Paramiko can also be used to download and upload files in batches. The principle is basically the same as that of executing commands in batches.
The above describes how to implement batch host management using python. For more information, see other related articles in the first PHP community!