Exemplo n.º 1
0
    def single_service(self, task):
        # work_log.info("service weblogic task: %s , host: %s port: %s" % (task, self.ip, self.port))
        work_log.info(
            f"service weblogic task: {task} , host: {self.ip} port: {self.port}"
        )

        try:
            if task == "start":
                return self.start_weblogic_single_service()
            elif task == "stop":
                return self.stop_weblogic_single_service()
            elif task == "accesslog":
                return self.showlogaccess()
            elif task == "projectlog":
                return self.showprojectlog()
            elif task == "gclog":
                return self.showgclog()
            elif task == "check":
                work_log.info('check task')
                info = WeblogicManagerCheck()
                data = info.get_wg_single_service_status(self.ip, self.port)
                return {"recode": 0, "redata": data}
        except Exception as e:
            work_log.error("single weblogic service run error")
            work_log.error(str(e))
            return {"recode": 2, "redata": str(e)}
Exemplo n.º 2
0
    def lock_ip(self, iplist):
        cmdlist = []

        lock_list = self.cache.setSmembers()
        for ip in iplist:
            work_log.debug(f"{ip}")
            if ip not in lock_list:
                cmd = (
                    f"""sed -i '/http_x_forwarded_for/s/")/|{ip}")/' {self.deny_conf}"""
                )
                cmdlist.append(cmd)

            else:
                work_log.error(f"lock: {ip} in lock_list")
        if not cmdlist:
            # 需解锁的IP并未屏蔽
            # 多个IP中部分存在的情况暂缓
            return {"redata": str(iplist) + " IP地址已经在锁定列表", "recode": 1}

        rundata = self.run_task_list(cmdlist)
        if rundata.get('recode') == 0:
            self.cache.setAdd(ip)
            work_log.info('cache lock')
        elif rundata.get('recode') == 8:
            self.cache.setAdd(ip)
            work_log.info(f'server run error, yes cache +lock')
        elif rundata.get('recode') == 9:
            work_log.info(f'server run error, not cache +lock')
        return rundata
Exemplo n.º 3
0
    def Shield(self, zone, ip, port, cancel=None):
        hosts = conf_data("service_info", "nginx", zone)
        if not cancel and port != "all":
            # 屏蔽某个服务
            cmd = f'sed -i "/{ip}:{port}/s/server/#server/g" {self.upstream_conf}'
        elif not cancel and port == "all":
            # 屏蔽某个主机
            cmd = f'sed -i "/{ip}/s/server/#server/g" {self.upstream_conf}'
        elif cancel and port != "all":
            # 解除某个服务的屏蔽
            # 遗留:配置本行末的注释会被影响
            # 如果有多个#,则每次取消一个
            cmd = f'sed -i "/{ip}:{port}/s/#//" {self.upstream_conf}'
        elif cancel and port == "all":
            cmd = f'sed -i "/{ip}/s/#//g" {self.upstream_conf}'
            # 解除某个主机的屏蔽

        info = HostGroupCmd(hosts, self.user)
        try:
            info.run_cmd_task(cmd)
            info.run_cmd_task(self.reload_cmd)
            # 没有报错就算成功了,暂时忽略了多个主机个别错误的情况
            return {"recode": 0, "redata": "success"}
        except Exception as e:
            work_log.error(str(e))
            return {"recode": 2, "redata": "remote run error"}
Exemplo n.º 4
0
def v3_nginx():
    work_log.info(str(request.path))
    work_log.info("request service interface, ip: %s " % (request.remote_addr))
    work_log.debug(str(request.json))
    try:
        if request.json.get("obj") != "dmz_nginx":
            return "", 404
    except Exception as e:
        return "", 404

    try:
        task = request.json.get("task")
        iplist = request.json.get("ip")

        if task in ["lock", "unlock", "clearlock", "showlock"]:
            info = Nginx_Acl()
            data = info.run_task(iplist, task)
            if task == "showlock":
                data = {"ip": data.get("redata")}
            work_log.info('return: ' + str(data))
            return jsonify(data)
        else:
            return jsonify({"redata": "req format error", "recode": 1})
    except Exception as e:
        work_log.error(str(e))
        return jsonify({"redata": "run error", "recode": 2})
Exemplo n.º 5
0
    def HostCpuData(self, data):
        ip = data.get("ip")
        # current_time = time.strftime('%Y-%m-%d %H:%M:%S')
        old_time = time.strftime("%Y-%m-%d_%X",
                                 time.localtime(time.time() - 3600))

        try:
            abc = (db.session.query(
                func.date_format(t_host_cpu.ctime, "%H:%i:%s").label("ctime"),
                t_host_cpu.cpu,
            ).filter(t_host_cpu.ip == ip, t_host_cpu.ctime > old_time).all())
        except Exception as e:
            work_log.error('select db HostCpuData error')
            work_log.error(str(e))
            return {"recode": 9, "redata": str(e)}

        x_name = []
        cpu = []
        work_log.debug(str(abc))
        for i in abc:
            x_name.append(str(i.ctime))
            cpu.append(format(i.cpu, ".2f"))

        value = {"x_name": x_name, "y_data": {"cpu": cpu}}

        return {"recode": 0, "redata": value}
Exemplo n.º 6
0
 def add_host(self, mess):
     work_log.info(str(mess))
     data = t_conf_host(
         ip_v4=mess.get("ip_v4"),
         ip_v6=mess.get("ip_v6"),
         ip_v4_m=mess.get("ip_v4_m"),
         name=mess.get("name"),
         operating_system=mess.get("operating_system"),
         hostname=mess.get("hostname"),
         cpu_number=mess.get("cpu_number"),
         memory_size=mess.get("memory_size"),
         sn=mess.get("sn"),
         address=mess.get("address"),
         belong_machineroom=mess.get("belong_machineroom"),
         rack=mess.get("rack"),
         manufacturer=mess.get("manufacturer"),
         dev_type=mess.get("type"),
         dev_category=mess.get("dev_category"),
         produce=mess.get("produce"),
         level=mess.get("level"),
         info=mess.get("info"),
     )
     try:
         db.session.add(data)
         db.session.commit()
         work_log.info("add host --- yes")
         return {"recode": 0, "redata": "ok"}
     except Exception as e:
         work_log.error("add host --- error")
         work_log.error(str(e))
         return {"recode": 9, "redata": "error"}
Exemplo n.º 7
0
    def down(self):
        try:
            ip = self.data.get("ip")
            file = self.data.get("file")
            user = self.data.get("user")
            if self.data.get("task") != 'remote_file_down':
                return {"recode": 1, "redata": "req arg error"}

            work_log.info(
                f"down file, ip: {ip}, filename: {file}, user: {user}")

            tmp_dir = conf_data("work_tmp_dir")
            filename = os.path.basename(file)
            local_tmp = os.path.join(tmp_dir, filename)

            info = UpDownFile(ip, user)
            data = info.down(file, local_tmp)
            if data:
                return {"recode": 0, "redata": f"api/v2/downfile/{filename}"}
            else:
                return {"recode": 2, "redata": "file not fount"}

        except Exception as e:
            work_log.error("down file run error")
            work_log.error(str(e))
            return {"recode": 9, "redata": str(e)}
Exemplo n.º 8
0
def v2_upload():
    work_log.debug(str(request.path))
    work_log.info("request host interface ip: %s" % (request.remote_addr))

    try:
        file = request.files["file"]
        ip = request.form["ip"]
        destdir = request.form["dir"]
        user = request.form["user"]
        if not ip or not destdir:
            return "", 404

        work_log.info(
            f"upload file, ip: {ip}, filename: {file.filename}, dest: {destdir}, user: {user}"
        )
        tmp_dir = conf_data("work_tmp_dir")
        local_tmp = os.path.join(tmp_dir, file.filename)
        dest = os.path.join(destdir, file.filename)
        file.save(local_tmp)  # 保存临时文件

        info = UpDownFile(ip, user)
        data = info.upload(local_tmp, dest)
        os.remove(local_tmp)  # 删除临时文件
        return jsonify(data)

    except Exception as e:
        work_log.error("upload file run error")
        work_log.error(str(e))
        return jsonify({"recode": 9, "redata": str(e)})
    else:
        return "", 200
Exemplo n.º 9
0
 def run_cmd_task(self, cmd):
     try:
         recode, data = self.ssh_cmd(cmd, stdout=True)
         return {"recode": recode, "redata": data}
     except Exception as e:
         work_log.error("run_cmd_task error")
         work_log.error(str(e))
         return {"recode": 9, "redata": str(e)}
Exemplo n.º 10
0
 def ssh_file_put(self, source_file, des_file):
     work_log.info("ssh_file_put host: %s =>> %s" % (source_file, des_file))
     try:
         self.put(source_file, des_file)
         work_log.info("ssh_file_put success")
     except Exception as e:
         work_log.error("ssh_file_put error")
         work_log.error(str(e))
         return False
Exemplo n.º 11
0
 def upload(self, src, dest):
     work_log.info(f"upload: {src} -> {dest}")
     try:
         self.put(src, dest)
         return {"recode": 0, "redata": "上传成功"}
     except Exception as e:
         work_log.error("upload error")
         work_log.error(str(e))
         return {"recode": 9, "redata": "上传失败"}
Exemplo n.º 12
0
 def down(self, src, localfile):
     work_log.info(f"down: {src}, {localfile}")
     try:
         self.get(src, localfile)
         return True
     except Exception as e:
         work_log.error("upload error")
         work_log.error(str(e))
         return False
Exemplo n.º 13
0
 def stats(self):
     try:
         data = self.mc.stats_str()
         work_log.info(data)
         return {"recode": 0, "redata": data}
     except Exception as e:
         work_log.error("get memcached data error")
         work_log.error(str(e))
         return {"recode": 9, "redata": "error"}
Exemplo n.º 14
0
 def _ssh_cmd(self, host, cmd, stdout=False):
     try:
         ssh = HostBaseCmd(host, self.user)
         data = ssh.ssh_cmd(cmd, stdout=stdout)
         data.append(host)
         return data
     except Exception as e:
         work_log.error(str(e))
         return [2, str(e), host]
Exemplo n.º 15
0
 def check_url_status(self, url):
     '''检查一个URL-返回状态码'''
     try:
         x = CheckWebInterface()
         recode = x.get_url_status_code(url, timeout=2)
         return recode
     except Exception as e:
         work_log.error(f"check wg url error: {url}")
         work_log.error(str(e))
         return 999
Exemplo n.º 16
0
 def check_weblogic_url(self, url):
     '''检查一个URL-返回数组'''
     try:
         x = CheckWebInterface()
         recode = x.get_url_status_code(url, timeout=2)
         return [url, recode]
     except Exception as e:
         work_log.error(f"check wg url error: {url}")
         work_log.error(str(e))
         return [url, 1]
Exemplo n.º 17
0
 def _weblogic_ssh_cmd(self, cmd):
     work_log.info("weblogic_ssh host: %s cmd: %s" % (self.ip, cmd))
     try:
         ssh = HostBaseCmd(self.ip, user=self.user)
         data = ssh.ssh_cmd(cmd, stdout=True)
         work_log.debug("_weblogic_ssh_cmd redata: %s" % str(data))
         return data
     except Exception as e:
         work_log.error("_weblogic_ssh_cmd Exception error")
         work_log.error(str(e))
         return [2, str(e)]
Exemplo n.º 18
0
 def _mc_ssh_cmd(self, cmd):
     work_log.info("_mc_ssh_cmd host: %s cmd: %s" % (self.ip, cmd))
     try:
         ssh = HostBaseCmd(self.ip, user=self.user)
         status = ssh.ssh_cmd(cmd)
         work_log.info(status)
         work_log.info("_mc_ssh_cmd exec success")
         return status
     except Exception as e:
         work_log.error("_mc_ssh_cmd Exception error")
         work_log.error(str(e))
         return str(e)
Exemplo n.º 19
0
 def run(self):
     work_log.debug(str(self.data))
     task = self.data.get("task")
     arg = self.data.get("arg")
     if task == 'cmd':
         return self.cmd(arg)
     elif task == 'unit':
         return self.unit(arg)
     elif task == 'script':
         return self.script(arg)
     else:
         work_log.error('form error')
         return {"recode": 1, "redata": "format error"}
Exemplo n.º 20
0
    def run(self):
        task = self.data.get("task")
        arg = self.data.get("arg")
        ip = self.data.get("ip")
        user = self.data.get("user")
        work_log.info(str(self.data))

        if not user:
            user = conf_data("user_info", "default_user")
        elif user not in conf_data("user_info"):
            return {"recode": 1, "redata": "input user error"}

        if task == 'shell':
            try:
                info = HostBaseCmd(ip, user=user)
                return info.run_cmd_task(arg)
            except AttributeError as e:
                work_log.error("ssh session create error")
                work_log.error(str(e))
                return {"recode": 1, "redata": "input format error"}
            except Exception as e:
                work_log.error("run_cmd_task error")
                work_log.error(str(e))
                return {"recode": 9, "redata": "run other error"}

        elif task == 'unit':
            info = HostBaseCmd(ip, user=user)
            return info.run_unit_task(arg)
        elif task == 'script':
            info = HostBaseCmd(ip, user=user)
            return info.run_cmd_task(arg)
        else:
            work_log.info("req format error")
            return {"recode": 1, "redata": "format error"}
Exemplo n.º 21
0
 def check_url(self, url):
     work_log.info("checkweburl: " + str(url))
     try:
         info = CheckWebInterface()
         recode = info.get_url_status_code(url, timeout=2)
         work_log.debug(str(recode))
         if recode == 200:
             return {"recode": 0, "redata": "success 成功"}
         else:
             return {"recode": recode, "redata": "error"}
     except Exception as e:
         work_log.error("checkweburl error")
         work_log.error(str(e))
         return {"recode": 9, "redata": "server error"}
Exemplo n.º 22
0
    def run_unit_task(self, arg):

        if arg in conf_data('shell_unit'):
            cmd = conf_data('shell_unit', arg)
        else:
            return {"recode": 9, "redata": 'unit error'}

        try:
            recode, data = self.ssh_cmd(cmd, stdout=True)
            return {"recode": recode, "redata": data}
        except Exception as e:
            work_log.error("run_unit_task error")
            work_log.error(str(e))
            return {"recode": 9, "redata": str(e)}
Exemplo n.º 23
0
    def ssh_cmd(self, cmd, stdout=False):
        work_log.info("ssh_cmd host: %s cmd: %s" % (self.ip, cmd))
        try:
            run_stdout, run_stderr = self.runshell(cmd)

            if run_stderr:
                # 先记录执行的错误输出
                work_log.error("ssh_cmd is error stdout")
                work_log.error(str(run_stderr))

            # 需要标准输出的情况
            if stdout:
                if run_stderr:
                    return [2, run_stderr.decode("utf-8")]
                else:
                    work_log.debug("ssh_cmd success, run_stdout")
                    work_log.debug(str(run_stdout))
                    return [0, run_stdout.decode("utf-8")]

            # 不需要标准输出的情况
            if run_stderr:
                return [2, run_stderr.decode("utf-8")]
            else:
                work_log.debug("ssh_cmd success, run_stdout")
                work_log.debug(str(run_stdout))
                return [0, "success"]
        except Exception as e:
            work_log.error("ssh_cmd Exception error")
            work_log.error(str(e))
            return False
Exemplo n.º 24
0
    def remote_check_port(self, server, ip, port):
        work_log.info('login remote server check port')
        try:
            info = HostBaseCmd(server, scp=True)
            redata = info.net_port_scan(ip=ip, port=port)
        except Exception as e:
            work_log.error(str(e))
            return {"recode": 9, 'redata': '连接服务器失败'}

        work_log.debug("port scan status: "+str(redata))
        if redata == 0:
            return {"recode": 0, 'redata': '探测成功'}
        else:
            return {"recode": 4, 'redata': '探测失败'}
Exemplo n.º 25
0
 def local_check_port(self, ip, port):
     work_log.debug('local exec remote port test')
     info = NetworkManager()
     try:
         recode = info.port_scan(ip, port)
         if recode == 0:
             return {"recode": recode, 'redata': '成功'}
         elif recode == 1:
             return {"recode": 4, 'redata': '主机存在端口不可访问'}
         else:
             return {"recode": 4, 'redata': '目标不能访问'}
     except Exception as e:
         work_log.error(str(e))
         redata = "scan error"
         return {"recode": 2, 'redata': '程序错误'}
Exemplo n.º 26
0
def v2_monitor():
    work_log.info("request MonitorTask interface ip: %s" %
                  (request.remote_addr))
    try:
        key = request.json.get("key")
        if verify_key(key) and request.json.get("obj") == "monitor":
            info = MonitorTask()
            data = info.run(request.json.get("content"))
            work_log.info(str(data))
            return jsonify(data)
        else:
            work_log.error("format error")
            return "", 404
    except Exception as e:
        work_log.error(str(e))
        return jsonify({"recode": 1, "redata": "run error"})
Exemplo n.º 27
0
    def __init__(self, ip, user=None, scp=None):
        if not user:
            ssh_user = conf_data("user_info", "default_user")
        else:
            ssh_user = user
        try:
            ssh_pw = conf_data("user_info", str(ssh_user), "ssh_passwd")
            key = conf_data("user_info", str(ssh_user), "ssh_key")
            ssh_port = conf_data("user_info", "ssh_port")
        except Exception as e:
            work_log.info("ssh arg input error")
            work_log.info(str(e))
            raise e

        self.ip = ip

        if key:
            ssh_key = conf_data("work_conf_dir") + "/" + key

        try:
            if ssh_key and not scp:
                Myssh.__init__(self, ip, ssh_user, keys=ssh_key, port=ssh_port)
            elif ssh_key and scp:
                Myssh.__init__(self,
                               ip,
                               ssh_user,
                               keys=ssh_key,
                               port=ssh_port,
                               scp=True)
            elif ssh_pw and scp:
                Myssh.__init__(self,
                               ip,
                               ssh_user,
                               passwd=ssh_pw,
                               port=ssh_port,
                               scp=True)
            elif ssh_pw and not scp:
                Myssh.__init__(self,
                               ip,
                               ssh_user,
                               passwd=ssh_pw,
                               port=ssh_port)

        except Exception as e:
            work_log.error('ssh login server error')
            work_log.error(str(e))
            raise e
Exemplo n.º 28
0
 def single_host_server(self, task):
     work_log.info("server weblogic task not port, all service")
     try:
         if task == "start":
             return self.start_wg_single()
         elif task == "stop":
             return self.stop_wg_single()
         elif task == "check":
             info = WeblogicManagerCheck()
             data = info.get_wg_single_server_status(self.ip)
             return {"recode": 0, "redata": data}
         else:
             return {"recode": 4, "redata": "不支持该操作"}
     except Exception as e:
         work_log.error("single weblogic service run error")
         work_log.error(str(e))
         return {"recode": 2, "redata": str(e)}
Exemplo n.º 29
0
 def run_task_list(self, cmdlist):
     cmdlist.append(self.reload_cmd)  # add reload
     work_log.debug(f"{cmdlist}")
     hosts = conf_data("service_info", "nginx", "dmz")
     try:
         info = HostGroupCmd(hosts, self.user)
         for i in cmdlist:
             work_log.info(f"nginx lock task, exec: {i}")
             run_data_list = info.run_cmd_task(i)
             work_log.info(str(run_data_list))
             work_log.debug("--------------------------")
         # 遗留问题,此处只处理了最后一个返回结果
         return self.get_run_data(run_data_list)
         work_log.debug("lock task all run")
         # return {"redata": "success", "recode": 0}
     except Exception as e:
         work_log.error(str(e))
         return {"recode": 2, "redata": "nginx server error"}
Exemplo n.º 30
0
    def run_task_group(self, task):
        work_log.debug(f"weblogic group: {self.group}, task: {task}")
        try:
            if task == "start":
                data = self.start_wg_group()
            elif task == "stop":
                data = self.stop_wg_group()
            else:
                return {"recode": 9, "redata": "参数错误"}

            if any(map(self.checkRunData, data)):
                return {"recode": 2, "redata": data}
            else:
                return {"recode": 0, "redata": data}

        except Exception as e:
            work_log.error("run_task_group task error")
            work_log.error(str(e))
            return {"recode": 9, "redata": str(e)}