In daily operation and maintenance work, it is very common to batch host hosts. There are also many host batch management software on the market, but sometimes these software cannot fully meet our needs. Python just provides a module for host batch management. Today let us take a look at how to use python to implement host batch management.
Python mainly provides three modules for host batch management: paramiko, fabric and pexpect. Today we Mainly talking about the paramiko module, which is a third-party module.
Installation: pip install paramiko or yum install python-paramiko. If both installations fail, you can use the source code to install
Source code package download address: 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 automatic answer for the first connection is yes
ssh.connect('server ip', port, 'username', 'password') / /Connect to the server
stdin,stdout,stderr = ssh.exec_command("command") //Execute the command, standard output, the command will be returned successfully, the command failure will be returned
ssh.close() /Close the connection
Upload, download:
get_put = paramiko.Transport((ip,port)) //Server ip and port (used when using SFTP)
get_put .connect(username="root", password="123.com") //Connect to the server, username and password
sftp = paramiko.SFTPClient.from_transport(get_put) //Use SFTP protocol
sftp.put(The file to be uploaded, the location where the uploaded file is saved) //Upload
sftp.get(The location of the downloaded file, the location where the downloaded file is saved) //Download
Host Batch management:
#!/usr/bin/python
#-*- coding: utf-8 -*-
import paramiko
import os
def Connect(ip='127.0.0.1',Port=22,user='root',pwd='123.com'):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=Port, username=user, password=pwd) #Connect to server
Return ssh #Return the server handle
def IP_ADD(ip):
if len(__ip) == 2: #If it is an address range
‐ down ‐ ‐ ‐ ‐ ‐ ‐ , [1]) #Retrieve ip The maximum value
Host_ip_split = ip_add.split('.') #Separate the ip into 4 segments by .
Host_ip = int(host_ip_split.pop()) #Get the minimum value of the ip
ip_3 = '.'.join(host_ip_split)+'.' #Resplice the remaining parts that have removed the minimum value of ip
host_add_range = range(host_ip,ip_range+1) #Generate the range of connection IP
Add_pool = []
for i in host_add_range:
Add = ip_3+str(i) #Splicing into a legal ip address
add_pool.append (add)
# 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] #Detect the legality of ip
[int(i) for i in ip_value]
# Return __IP#Return address
If __Name__ == '__main __Main __Main __N:
## OSYSTEM (' Clear ')## Fa = True
while Fa:
ip = raw_input('Please enter an ip address or an address range: ')
exclude_ip = raw_input('Please enter the address to be excluded: ' ')
try:
ip_list = IP_ADD(ip) #Leave the IP input by the user to the function
if exclude_ip.strip(): #Determine whether the user wants to Excluding the address in the address pool
Exclude_add = Exclude_ip.split (',')#define the exclusion format
[ip_list.remove (i) for I in Exclude_add]
## '''Example: 127.0.0.1 Pay operation operation operation 127.0.0.1- 254 The host execution operation of a address range 127.0.0.8,127.0.0.10 Eliminate the address to eliminate the address The address in the pool '' # counter \ 033 [31M Input Script_exit Exit Programs \ 033 [0m '##Aile True:
Shell_comd = raw_input ('Please enter the command of executing:')#The command of executing
iF shell_comd == 'script_exit':
## Break# for i in ip_list: #Cycle address pool
try:
’s ’ s ’ s out out out through out out through off ‐ ‐ ‐ ‐ ‐ ‐ um stdin, stdout, stderr = comd.exec_command( shell_comd) #Execute the command
stderr = stderr.read() #The result of the correct execution of the command
stdout = stdout.read() #The command of the wrong execution
If Stdout:
PRINT '\ 033 [31m +++++++++ ++++ +++++++++ 033 [0m'%i
Print Stdout
Else:
Print '\ 033 [31m +++++++++++ +++++++++++ \ 033 [0m'%i
# Except: PRINT '\033[31m%s connection failed\033[0m' %iparamiko can also implement batch download and batch upload of files. The principle is basically the same as batch execution of commands.The above is the detailed content of Using python to implement host batch management. For more information, please follow other related articles on the PHP Chinese website!