智慧运维平台之Linux批量操作功能


俏皮保卫大门
俏皮保卫大门 2023-10-20 15:39:08 50770
分类专栏: 资讯
场景背景
随着目前运维的机器越来越多,管理机器的任务也越来越繁重,当出现对机器进行批量操作时,登录不同的机器上去操作则需要耗费大量时间。

为减少现场运维的重复性工作、减轻现场运维工作的繁杂性,提升现场运维工作效率,为此实现批量操作功能。

巡检配置

2.1 场景脚本

#!/home/bomc/miniconda2/bin/python2.7
# -*- coding:utf-8 -*-

from paramiko import SSHClient, AutoAddPolicy
import os
import sys
import time
import datetime
sys.path.append("/home/bomc/chenjinyun/python")
import passwd
import cx_Oracle
reload(sys)
sys.setdefaultencoding('utf-8')



class data_process:
    def __init__(self,data_user,word,data_name):
        try:
            self.password = passwd.crypto.decode(word)
            self.db = cx_Oracle.connect(data_user,self.password,data_name)
        except Exception as e:
            print datetime.datetime.now(),"Failed to connect to the database--------"

    def sql_insert(self,SQL,data):
        '''insert'''
        try:
            curs = self.db.cursor()
            #SQL = "INSERT INTO process_err_message(applytime,host,process,cprocess,application,condition,amount,amount_number,cpu,cpu_number,mem,mem_number,status) VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)"
            curs.executemany(SQL,data)
            self.db.commit()
            curs.close()
        except Exception, e:
            print (e)

    def sql_update_delete(self,sql):
        '''update,delete'''
        try:
            curs = self.db.cursor()
            # SQL = "INSERT INTO task_process_err(applytime,user_id,status,WORKING_DIR,EXE_NAME,ARGS,stdout_file,proc_no,NAME,ip_addr,proc_id) VALUES(:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11)"
            curs.execute(sql)
            self.db.commit()
            curs.close()
        except Exception, e:
            print (e)

    def sql_select(self,sql1):
        '''
        select
        '''
        try:
            #sql1="select t.process, t.application, t.path, t.patch, t.keyword, t.host from process_yy t where t.status = 1 and t.patch in ('START', 'STOP') and t.node = '%s' " % host
            curs = self.db.cursor()
            result = curs.execute(sql1)
            rows = curs.fetchall()
        except Exception as e:
            return []
        else:
            curs.close()
            return rows

    def close(self):
        self.db.close()
        print datetime.datetime.now(),"Successfully disconnect the database-------------"

class AutoTask:
    def __init__(self, ip, port, username, password,rusername,rpasword,cmd):
        self.ip = ip
        self.port = int(port)
        self.username = username
        self.pasword = password
        self.rusername = rusername
        self.rpasword = rpasword
        self.cmd = cmd
        self.client = SSHClient()
        self.client.set_missing_host_key_policy(AutoAddPolicy())

    def root_sshclient(self):
      try:
        self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
        self.cmd = self.cmd.replace('"','\\"')
        command = 'echo \'{}\' | su -l -c "{}" "{}"'.format(self.rpasword,self.cmd.replace('\n',';'),self.rusername)
        #print command
        stdin,stdout,stderr=self.client.exec_command(command)
        result = stdout.read().split('\n')
        #print result
        result.insert(0,'host'+' '+self.ip)
      except Exception as e:
        print "ERR:unable to connect%s %s\n"%(self.ip,e)
        return []
      else:
        self.client.close()
        return result

    def user_sshclient(self):
      try:
        self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
        stdin,stdout,stderr=self.client.exec_command(self.cmd)
        result = stdout.read().split('\n')
        result.insert(0,'host'+' '+self.ip)
      except Exception as e:
        print "ERR:unable to connect%s %s\n"%(self.ip,e)
        return []
      else:
        self.client.close()
        return result

    def create_sshclient(self):
        try:
            self.client.connect(self.ip, port=self.port, username=self.username, password=self.pasword,timeout=5)
            chan=self.client.invoke_shell()
            time.sleep(0.1)
            chan.send("export LANG=us.en \n")
            chan.send("su - "+self.rusername+"\n")
            buff = ''
            while not buff.endswith(('Password: ','Password:')):
                resp = chan.recv(9999)
                buff +=resp
            chan.send(self.rpasword+"\n")
            time.sleep(0.1)
            buff=''
            chan.send("export PS1='[shsnc_client]#' \n")
            while not buff.decode('utf-8').endswith(('#','# \n','~ # ')):
                resp = chan.recv(9999)
                buff +=resp
            chan.send(self.cmd+" \n")
            buff=''
            time.sleep(0.01)
            while not buff.endswith(('[shsnc_client]#')):
                resp = chan.recv(9999)
                buff +=resp
            result_data = buff.split('\n')[1:-1]
            if 'shsnc_client' in  result_data[0]:
               result_data[0] = 'host'+' '+self.ip
            else:
               result_data.insert(0,'host'+' '+self.ip)
            return result_data
            chan.close()
        except Exception as e:
            log_file_err.write("ERR:unable to connect%s %s\n"%(self.ip,e))
            return []


    def auto_sshclient(self):
      try:
        if self.rusername == '' or self.rpasword == '':
          client_result = self.user_sshclient()
        else:
          client_result = self.root_sshclient()
          if client_result == [] or client_result[1] == '':
            client_result = self.create_sshclient()
      except :
        return []
      else:
        return client_result


def host_def(sql_select):
    password = passwd.crypto.decode("gAAAAABcpVuKaEnScGgRGl7Z2zVurdZZpWHYIKm-hjkBkbV9BXbIR3frFvsf3YfmjArD7G156t9c22SZVZAGoYMyxUVMDAYlIQ==")
    try:
        db = cx_Oracle.connect('shsnc',password,'shsnc')
        # sql1="select t.* from nfs_host_info t where t.status= %s " % worktype
        curs = db.cursor()
        result = curs.execute(sql_select)
        rows = curs.fetchall()
        db.close()
    except Exception as e:
        raise e
    return rows


def main():
  host = host_list_input.split()
  cmd = cmd_input
  root_user = root_user_input
  #print host,cmd,root_user
  password = "gAAAAABcpVuKaEnScGgRGl7Z2zVurdZZpWHYIKm-hjkBkbV9BXbIR3frFvsf3YfmjArD7G156t9c22SZVZAGoYMyxUVMDAYlIQ=="
  db_connect = data_process('shsnc',password,'shsnc')
  for host_message in host :
    sql1="select * from crm_machine_info t where t.hostip='%s' and rownum = 1" % (host_message)
    line = db_connect.sql_select(sql1)
    if len(line) < 1:
      message = "Error : Crm_machine_info 表无该主机 %s" % host_message
      print message
    else :
      print line
      host = line[0][2]
      username = line[0][4]
      password1 = line[0][5]
      password = passwd.crypto.decode(password1)
      port = 22
      if line[0][6] != None:
          bomcname = 'root'
          bomcword1 = line[0][6]
          bomcword = passwd.crypto.decode(bomcword1)
      elif  line[0][7] != None:
          bomcname = 'bomc'
          bomcword1 = line[0][7]
          bomcword = passwd.crypto.decode(bomcword1)
      elif  line[0][7] == None and line[0][6] == None:
          bomcname = ''
          bomcword = ''
      if root_user == 'no':
        client_result = AutoTask(host_message,port,username,password,'','',cmd)
      elif root_user == 'yes' :
        client_result = AutoTask(host_message,port,username,password,bomcname,bomcword,cmd)

      cmd_result = client_result.auto_sshclient()
      for result in  cmd_result:
          print result




if __name__ == '__main__':
main()
获取输入的ip、输入的命令、是否使用root执行,在数据库中找到登录需要的信息,在主机上依次执行并将结果在日志中整合,依次输出结果。

2.2 场景参数介绍

图片
参数名
参数释义
是否必填
默认值
主机ip
选择单台或多台主机
/
命令行
输入需要批量执行的命令(可使用多个命令)
/
是否使用root
选择root用户或非root用户
/

 

2.3 执行操作

将所有参数填完以后,点击执行等待执行成功即可。
图片

2.4 执行完成

执行完成,查询作业结果即可查询到批量执行后的结果,以批量查询主机序列号为例,在执行日志中即可查看多台主机的输出结果,具体如下:

图片

总 结:
利用智慧运维管理平台,使用Linux批量操作功能,极大的提高现场工作效率,减少误操作,现场相关其他类似操作,均已实现自动化操作

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=27738
赞同 0
评论 0 条
俏皮保卫大门L0
粉丝 0 发表 6 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2941
【软件正版化】软件正版化工作要点  2860
统信UOS试玩黑神话:悟空  2819
信刻光盘安全隔离与信息交换系统  2712
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1246
grub引导程序无法找到指定设备和分区  1213
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  163
点击报名 | 京东2025校招进校行程预告  162
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  160
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  157
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
信创开放社区邀请他人注册的具体步骤如下 15
如何玩转信创开放社区—从小白进阶到专家 15
方德桌面操作系统 14
我有15积分有什么用? 13
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!