zhltom 发表于 2018-7-31 09:10:31

saltstack命令行管理通用脚本

#!/usr/bin/env python  
# -*- coding:utf8 -*-
  
# create by xmj 20170703
  

  
import sys,os
  
import time
  
import re
  
from ConfigParser import ConfigParser
  
import salt.client
  
import logging
  

  
PATH = os.path.split(os.path.realpath(__file__))
  

  
if not os.path.isdir('log'):
  
    os.makedirs('log')
  

  
log = open('log/%s.log' % time.strftime('%Y%m%d_%H%M%S'),'w+')
  
def WriteLogPrint(comment):
  
    log.write(comment + '\n')
  
    print comment
  

  
class OperationHostProfile():
  
    def __init__(self):
  
      self.hostlist = ConfigParser()
  
      self.hostlist.read("hostlist.ini")
  

  
    def get_sections(self):
  
      sections = self.hostlist.sections()
  
      return sections
  

  
    def get_hosts(self, section):
  
      hosts = self.hostlist.get(section, 'hosts').split(',')
  
      return hosts
  

  
class OperationStateProfile():
  
    def __init__(self):
  
      self.state = ConfigParser()
  
      self.state.read('state.ini')
  

  
    def get_sections(self):
  
      sections = self.state.sections()
  
      return sections
  

  
    def get_comment(self,section):
  
      comment = self.state.get(section, 'comment')
  
      return comment
  

  
    def get_operate(self,section):
  
      operate = []
  
      operate.append(self.state.get(section,'operate'))
  
      return operate
  

  

  

  
class OperationSalt():
  
    def __init__(self):
  
      self.OperationStateProfile = OperationStateProfile()
  
      self.OperationHostProfile = OperationHostProfile()
  

  
    def saltcmd(self,state,hostlist):
  
      try:
  
            client = salt.client.LocalClient()
  
      except Exception, e:
  
            print "Error: " + str(e)
  
      for host in hostlist:
  
            isalive = client.cmd(host,'test.ping')
  
            WriteLogPrint("--------------------------------------")
  
            if isalive:
  
                WriteLogPrint("%s 连通性检查:[\033" % host)
  
                jid = client.cmd_async(host,'state.sls',state)
  
                ret = client.get_cache_returns(jid)
  
                t = 0
  
                while not ret:
  
                  time.sleep(5)
  
                  if t == 12:
  
                        WriteLogPrint("Connection Failed!")
  
                        WriteLogPrint("%s 升级操作 [\033" % host)
  
                        break
  
                  else:
  
                     ret = client.get_cache_returns(jid)
  
                     t += 1
  
                if ret:
  
                  WriteLogPrint("jid: %s" % jid)
  
                  WriteLogPrint("%s 升级操作[\033,以下为详细信息" % host)
  
                  for operate in ret['ret'].keys():
  
                        if ret['ret']['result'] == True:
  
                            WriteLogPrint(ret['ret']['comment'] + " [\033")
  
                        else:
  
                            WriteLogPrint(ret['ret']['comment'] + " [\033")
  
                else:
  
                  WriteLogPrint("%s 升级操作 [\033" % host)
  
            else:
  
                WriteLogPrint("%s 连通性检查:[\033" % host)
  
                continue
  

  
    def get_state(self):
  
      sections = self.OperationStateProfile.get_sections()
  
      print "请输入[]中的数字,选择操作:"
  
      for section in sections:
  
            comment = self.OperationStateProfile.get_comment(section)
  
            print "    [%s]: %s" % (section, comment)
  
      state = raw_input("请输入: ")
  
      if state in map(str,range(1, len(sections) + 1)):
  
            comment = self.OperationStateProfile.get_comment(state)
  
            operate = self.OperationStateProfile.get_operate(state)
  
      else:
  
            print "Error Input!!"
  
            sys.exit()
  
      return comment, operate
  

  
    def set_user_host(self):
  
      host = raw_input("多个以逗号或者空格分隔: ")
  
      hosts = re.split(',| ', host)
  
      if '' in hosts:
  
            hosts.remove('')
  
      return hosts
  

  

  
    def get_host(self):
  
      sections =self.OperationHostProfile.get_sections()
  
      print "请输入[]中的数字,选择目标机器:"
  
      i = 1
  
      for section in sections:
  
            hosts = self.OperationHostProfile.get_hosts(section)
  
            if section == 'gray':
  
                print "    [%d]: %s" % (i , "灰度")
  
            else:
  
                print "    [%d]: %s" % (i, section)
  
            i += 1
  
            print "      ps:共%s台,他们是%s" % (len(hosts),hosts)
  
      print "    [%d]: 手动输入" % (i)
  
      print "请输入你的选项,",
  
      options = self.set_user_host()
  
      print options
  
      hosts = []
  
      for option in options:
  
            if option in map(str,range(1, len(sections) + 2)):
  
                if option == str(i):
  
                  print "请输入主机名,",
  
                  hosts = self.set_user_host()
  
                else:
  
                  host = self.OperationHostProfile.get_hosts(sections)
  
                  hosts.extend(host)
  
            else:
  
                print "Error Input!!"
  
                sys.exit()
  
      return hosts
  

  
    def main(self):
  
      os.system('clear')
  
      WriteLogPrint("Welcom To Use This Script!")
  
      comment, operate = self.get_state()
  
      hosts = self.get_host()
  
      WriteLogPrint("    你选择的操作是: %s" % comment)
  
      WriteLogPrint("    目标机器共%s台,分别是: %s" % (len(hosts), hosts))
  
      confirm = raw_input("请输入确认: ")
  
      if confirm == 'Yes':
  
            self.saltcmd(operate, hosts)
  
            log.flush()
  
      else:
  
            print "Error Input!!"
  
            sys.exit()
  

  
if __name__ == '__main__':
  
    a = OperationSalt()
  
    a.main()
页: [1]
查看完整版本: saltstack命令行管理通用脚本