Background: Batch execution of commands for Linux servers and batch sending of files is the most fundamental part of the operations automation process, and this script is the implementation of this function, and the shell can also implement similar functions through expect.
This script uses the Pexpect module, without which the module needs to be installed manually.
The script has 4 features:
Batch execution of commands to managed servers
Bulk sending of local files to managed machines
Support for server grouping
Support for IP address sequences
The script configuration file is as follows:
[web]192.168.56.102 root liu123192.168.56.103 root liu123[db]192.168.56.101 root liu123192.168.56.102 root liu123
The WEB and DB are group names, the remaining first column is the IP address, the second column is the user name, and the third column is the password for the user name.
Functions run as follows:
IP Address Sequence Batch execution command
IP addresses are separated by commas, and the password corresponding to the IP address needs to be defined in the configuration file
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/58/C9/wKioL1S8vpCDLTVsAAKeGJsJWqY334.jpg "title=" IP Address Sequence Batch execution command 1.png "alt=" Wkiol1s8vpcdltvsaakegjsjwqy334.jpg "/>
Server grouping Batch execution commands
The server group name needs to be defined in the configuration file
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/58/C9/wKioL1S8v3LAsVhqAAFliBGHabc814.jpg "style=" float: none; "title=" Batch execution command-group 1.png "alt=" Wkiol1s8v3lasvhqaaflibghabc814.jpg "/>
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/58/CC/wKiom1S8vqCAPvy7AAJ2c9pesW8679.jpg "style=" float: none; "title=" Batch execution command-group 2.png "alt=" Wkiom1s8vqcapvy7aaj2c9pesw8679.jpg "/>
Send files in bulk
Use the group name or IP address sequence to
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/58/C9/wKioL1S8vzzwxHYtAAMVATLnDIo354.jpg "title=" Bulk group or IP address sequence send file. png "alt=" wkiol1s8vzzwxhytaamvatlndio354.jpg "/>
The Python code is implemented as follows:
# -*- coding: utf-8 -*-#作用: Batch execute command to server, or send file to other machine # usage: #执行命令:p ython bat_exec.py DB uptime or python bat_exec.py DB "Ls | wc -l" #发送文件: # python bat_exec.py db pexpect-3.3.tar.gz /home/#配置文件的格式如下 The following example needs to be removed, after configuring the password file, You need to modify the value of the variable ip_list_file: #[web] #192.168.56.102 root liu123#[db] #192.168.56.101 root liu123# 192.168.56.102 root liu123# #注意: If there is no Pexpect module in the release need to install the Pexpect module # Warning: the password needs to be written in clear text into the configuration file and may not be secure #import pexpectimport reimport sysdef format_ip_str (IP_STR): "" " checks the string, which conforms to the IP address sequence, processes the string as a list. Otherwise, depending on the string as the group name, call Srv_list () to find if the IP list file matches the group name ip. finally returns the IP address list . "" def check_ip (IP_ADDR): "" " receives the IP_ADDR variable, determines whether it is a legitimate IP address, returns TRUE if it is legal, or returns FALSE  &NBsp; "" " ip_pattern = Re.compile (R ' ^ (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) \. ( \D{1,2}|1\D\D|2[0-4]\D|25[0-5]) \. (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) \. (\d{1,2}|1\d\d|2[0-4]\d|25[0-5]) $ ') ip_match = ip_ Pattern.match (IP_ADDR) if ip_match: result = True else: result = False return result def Proc_srv_list (groupname): "" " receives the parameter server group name, processes the Ip_list_file configuration file, and returns the list of IP addresses. similar format: [' [DB] ', ' 172.16.7.17 ', ' 172.16.7.183 ', ' 172.16.7.184 '] where the first element is the group name "" " f = Open (Ip_list_file, ' R ') iplist = [] flag = 0 while True: line = f.readline () if not line:break line = line.strip () flag_pattern = re.compile (R ' ^\[(. *) \]$ ') flag_match = flag_ Pattern.match (line)    &NBsp; if flag_match: if flag_match.group (1) == groupname : flag = 1 elif (flag == 1) and flag_match.group (1) != groupname: break if flag == 1: iplist.append (line) f.close () if lEn (IPList) != 0: del iplist[0] return iplist list = ip_str.split (', ') loginfolist = [] ip_string  = CHECK_IP (list[0]) if ip_string: for element in list:   FLAG = CHECK_IP (Element) if not flag: break if flag: for element in list: f = open (Ip_list_file, ' R ') while True: line = f.readline () if not line:break line = line.strip () line_list = line.split (' ') if line_list[0] == element: Loginfolist.append (line) break #匹配到第一行即中断 f.close () else: loginfolist = proc_srv_list (IP_STR) return logInfoListdef Print_highlighted_red (str): print ' \033[1;44m %s \033[1;m ' % strclass batexec: def __init__ (SELF,IP,USER,PASSWD): self. ip = ip self. User = user self. Passwd = passwd def cmd (Self,command): child = pexpect.spawn (' ssh %[email protected]%s ' % (self). User,self. IP) print_highlighted_red (self). IP) try: i = child.expect ([' s password: ', ' continue connecting ( yes/no)? if i == 0: child.sendline (self. PASSWD) elif i == 1: child.sendline (' Yes ') child.expect (' s password: ') child.sendline (self. PASSWD) except pexpect. Eof: child.close () child.expect (' # ') child.sendline ( command) child.expect (' # ') print child.before def scpfile (Self,localpath,remotepath): child = pexpect.spawn ("scp %s %[email protected]%s:%s "% (localpath,self. USEr,self. Ip,remotepath)) print_highlighted_red (self. IP) try: i = child.expect ([' s password: ', ' continue connecting ( yes/no)? if i == 0: child.sendline (self. PASSWD) Child.read () elif i == 1 : Child.sendline (' yes ') child.expect (' S password:&nbSP; ') child.sendline (self.) PASSWD) Child.read () except pexpect. Eof: child.close () print child.beforeglobal ip_list_fileip_list_file = '/root/ Batexec/ip_password.conf ' If len (SYS.ARGV) == 3: ipstr = sys.argv[1] command = sys.argv[2] loginfolist = format_ip_str (IPSTR) for loginfo in loginfolist: ip = loginfo.split (' ') [0] user = loginfo.split (' ')) [1] passwd = loginfo.split (' ') [2] batexec = batexec (IP,USER,PASSWD) batexec.cmd (command) Elif len (SYS.ARGV) == 4: ipstr = sys.argv[1] localpath = sys.argv[2] Remotepath = sys.argv[3] loginfolist = format_ip_str (IPSTR) for loginfo in loginfolist: ip = loginfo.split (' ') [0] user = Loginfo.split (' ') [1] passwd = loginfo.split (' ') [2] batexec = batexec (IP,USER,PASSWD) &nbSp; batexec.scpfile (localpath,remotepath) else: print ' input error '
Note: You may need to modify the value of the Ip_list_file variable to point to a legitimate configuration file
Warning: Passwords written to plaintext may be unsafe, resulting in risks that require you to control
This article is from the "Pearl River Disease Tree-Blog" blog, please be sure to keep this source http://liushan2014.blog.51cto.com/5275814/1605858
Python script executes commands and sends files to a batch machine