Using Python for host batch management

Source: Internet
Author: User
In the daily operation and maintenance work in the bulk of the host is very common, there are many host batch management software, but sometimes these software does not fully meet our needs. Python provides a module on host batch management, so let's take a look at how to implement host batch management with Python today.

Python provides host batch management module mainly has three Paramiko, fabric and pexpect, today we are mainly talking about Paramiko module, Paramiko module is a third-party module

Installation: Pip install Paramiko or yum install Python-paramiko if the installation fails, you can use the source to install

SOURCE 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 ())//First time connection auto Answer Yes

Ssh.connect (' Server IP ', port, ' username ', ' password ')//Connect to Server

Stdin,stdout,stderr = Ssh.exec_command ("command")//execute command, standard output, command successfully returned, command failed to return

Ssh.close ()//close connection

Upload, Download:

Get_put = Paramiko. Transport ((Ip,port))//server IP and port (used with SFTP)

Get_put.connect (username= "root", password= "123.com")//connection server, username and password

SFTP = Paramiko. Sftpclient.from_transport (get_put)//using the SFTP protocol

Sftp.put (need to upload the file, upload the file to save the location)//upload

Sftp.get (download file location, download saved location)//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) #连接服务器

return SSH #返回服务器句柄

def ip_add (IP): #判断用户输入的是一个地址还是地址范围

__IP = Ip.split ('---')

If Len (__ip) = = 2: #如果是地址范围

Ip_add = __ip[0] #取出ip

ip_range = Int (__ip[1]) #取出ip的最大值

Host_ip_split = Ip_add.split ('. ') #将ip以. Separated into 4 segments

host_ip = Int (Host_ip_split.pop ()) #取出ip的最小值

Ip_3 = '. '. Join (Host_ip_split) + '. ' #将已经去除了ip的最小值的剩余部分重新拼接

Host_add_range = Range (host_ip,ip_range+1) #生成连接ip的范围

Add_pool = []

For I in Host_add_range:

Add = Ip_3+str (i) #拼接为合法的ip地址

Add_pool.append (ADD) #生成地址池

return Add_pool #返回地址池

Elif len (__ip) = = 1: #如果输入的为单个地址

VALID_IP = __ip[0]

Ip_value = Valid_ip.split ('. ') [0:4] #检测ip的合法性

[Int (i) for I in Ip_value]

return __IP #返回地址

if __name__ = = ' __main__ ':

Os.system (' Clear ')

Fa = True

While Fa:

ip = raw_input (' Please enter an IP address or an address range: ')

EXCLUDE_IP = raw_input (' Please enter an address to exclude: ')

Try

Ip_list = Ip_add (IP) #将用户输入的ip交给函数处理

If Exclude_ip.strip (): #判断用户是否要排除地址池中的地址

Exclude_add = Exclude_ip.split (', ') #定义排除格式

[Ip_list.remove (i) for i in Exclude_add] #排除ip地址

Fa = False #退出循环

Except

print ' \033[31m address format error \033[0m '

Print "' Example:

127.0.0.1 performing operations on a single host

127.0.0.1--254 performing operations on a host of an address range

127.0.0.8,127.0.0.10 exclude addresses from the address pool

'''

Continue

print ' \033[31m input script_exit exit program \033[0m '

While True:

SHELL_COMD = raw_input (' Please enter command to execute: ') #执行的命令

if shell_comd = = ' Script_exit ':

Break

For i in Ip_list: #循环地址池

Try

comd = Connect (ip=i) #连接服务器

stdin, stdout, stderr = Comd.exec_command (SHELL_COMD) #执行命令

stderr = Stderr.read () #命令正确执行的结果

stdout = Stdout.read () #命令错误执行的命令

If stdout:

print ' \033[31m++++++++++++%s+++++++++++\033[0m '%i

#那台服务器执行的命令

Print stdout

Else

print ' \033[31m++++++++++++%s+++++++++++\033[0m '%i

Print stderr

Except

print ' \033[31m%s connection failed \033[0m '%i

paramiko can also achieve file bulk download and bulk upload, the principle and the bulk execution of commands are basically the same.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.