Python script remote Batch execution command

Source: Internet
Author: User

Summary

This article mainly writes the Python script to connect multiple servers remotely, then executes the commands in bulk and returns the command execution results.

This can be said to be the simplest prototype of tools such as Ansible,puppet.

The students who do operation and maintenance should know.


Body

multi_task.py

#_ *_coding:utf-8_*_import  multiprocessingimport paramikoimport getpassimport  Configparserclass multitask (object):     "handles all the multi  Task works '     def __init__ (self):         msg = self._interactive ()         self.__run_cmd (msg)     def __show_cmd_list (self,msg):         " Show all available cmd list '         help_content  =  '         run_cmd     run  cmd on multiple hosts                     run_cmd -u remote_user -g group1,group2  -cmd pwd                     run_cmd -u remote_user -re regular expression -cmd pwd          '         def _interactive ( Self):
        msg = []         nodes = []         #parse  setting.conf         config = configparser.configparser ()          config.read ("./setting.conf")         groups  = config.sections ()         print groups         # Input group name         while True:            try:                 group =  Raw_input ("\033[33;1mplease input group name:\033[0m"). Strip ()            &nBsp;     if len (group)  == 0 : continue                 elif group not in  groups:                     print  "wrong group name ! please input again!"                      continue                 else :

 

                   print  "you have choose group %s , the children in this  group are : " % group                     break                         except  ( Keyboardinterrupt):                 print  ' \ n '                  exit (1)                  items = dict (Config.items (group))         for node  in items.values ():             nodes.append (node)              print node                 # Input command         while True:             try:                cmd  = raw_input ("\033[33;1mplease input command:\033[0m"). Strip ()                  if len (cmd)  == 0 :  continue                 else: break            except  ( Keyboardinterrupt):   &NBsp;             print  ' \ n '                  exit (1)          print  "command you input is %s"  % cmd

 

      # Input username and password         while True:             try:                 Username = raw_input ("\033[33;1mplease input username:\033[0m"). Strip ()                  if len (username)  ==  0 : continue                 else: break             except  (Keyboardinterrupt):                 print  ' \ n '                  exit (1)          password = getpass.getpass ()                  msg = [nodes,username, password,cmd]        print msg         return msg    def __run_cmd (self,msg):         pool = multiprocessing. Pool (5)         lock = multiprocessing. Manager (). Lock ()         res_list = []          #msg  = [[' 10.9.214.10 ', ' Haohzhang ', ' 871102_hadoop '],[' 10.9.214.105 ', ' Haohzhang ', '
871102_hadoop '],[' 10.9.214.106 ', ' Haohzhang ', ' 871102_hadoop ']]         For host in msg[0]:            p  = pool.apply_async (run_task, args= (host,msg[1:],lock))              res_list.append (P)          Pool.close ()         pool.join ()          print  '--------all task are finished!-------' Def run_task (host,msg,lock):         ip = host    username =  MSG[0]    PASSWORD = MSG[1]    CMD = MSG[2]     print  "ip %s, username %s, passwd %s, cmd %s"  %  (IP, USERNAME,&NBSp;password, cmd)     port = 22    s =  Paramiko. Sshclient ()      #绑定实例     s.load_system_host_keys ()    # Loads the native Know host host file     s.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())     try:        s.connect (Ip,port
, username,password,timeout=5)     #连接远程主机         stdin, Stdout,stderr = s.exec_command (cmd)     #执行命令          cmd_result = stdout.read (), Stderr.read ()      #读取命令结果          lock.acquire ()         print  '------ ----- HOST:%s  IP:%s -------------'  % (USERNAME,IP)          for line in cmd_result:             print line,        lock.release ()          s.close ()     except Exception,e:         print  '----------- HOST:%s  IP:%s -------------'  % (USERNAME,IP)         print  ' \033[31;1merror:%s\033[0m '  % e# vim:ts=4:sw=4 : Expandtab


Setting.conf

[Datanodes]node1=10.9.214.10node2=10.9.214.105node3=10.9.214.106node4=10.9.214.113[masternodes]masternode= 10.9.214.15


main.py

From Multi_task import multitask, run_tasktasks = multitask ()


How to run:

Python main.py


Explain:


This article from "Linux operation and Maintenance" blog, declined reprint!

Python script remote Batch execution command

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.