示例#1
0
class db(object):
    """
    @summary 封装db模块
    """
    def __init__(self, table, charset='utf8'):
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
        conf_path = path + "/conf/db.conf"
        cf = configparser.ConfigParser()
        cf.read(conf_path)

        self.host = cf.get('monkey_test_db', 'host')
        self.port = int(cf.get('monkey_test_db', 'port'))
        self.user = cf.get('monkey_test_db', 'user')
        self.passward = cf.get('monkey_test_db', 'passward')
        self.table = table
        self.charset = charset
        self.log = Logger()

    def db_execute(self, sql):
        """
        @summary 除查询外的操作使用该方案
        """
        db = MySQLdb.connect(host=self.host,
                             port=self.port,
                             user=self.user,
                             passwd=self.passward,
                             db=self.table,
                             charset=self.charset)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            db.commit()
        except:
            db.rollback()
            self.log.error("'{}'sql语句执行失败".format(sql))
        db.close()

    def db_check(self, sql):
        """
        @summary 查询操作
        """
        db = MySQLdb.connect(host=self.host,
                             port=self.port,
                             user=self.user,
                             passwd=self.passward,
                             db=self.table,
                             charset=self.charset)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            results = cursor.fetchall()
            self.log.error('test')
        except:
            db.rollback()
            self.log.error("'{}'sql语句执行失败".format(sql))
            results = False
        db.close()
        return results
示例#2
0
class BaseClient(object):
    def __new__(cls, *args, **kwargs):
        if cls is not __class__:
            return super().__new__(cls)
        else:
            raise TypeError('基类不允许实例化')  # 因为基类中exec_shell_cmd未实现

    def __init__(self):
        self.logger = Logger()
        self.test_mode = getattr(settings, 'TEST_MODE', False)
        self.asset_api = settings.ASSET_API
        self.key = settings.KEY
        self.key_header_name = settings.AUTH_KEY_NAME
        self.key_header = self.auth_key()

    @classmethod
    def exec_shell_cmd(cls, cmd, hostname):
        raise NotImplementedError(
            '请在子类中实现exec_shell_cmd方法:用于在待采集资产机器上执行该命令,返回结果')

    def process(self):
        raise NotImplementedError('请在子类中实现process方法:用于采集资产,并发送给API')

    def auth_key(self):
        """ 接口认证 """
        ha = hashlib.md5(self.key.encode('utf-8'))
        time_span = time.time()
        ha.update(bytes("{}|{}".format(self.key, time_span), encoding='utf-8'))
        encryption = ha.hexdigest()
        result = "{}|{}".format(encryption, time_span)
        return {self.key_header_name: result}

    def get_asset(self, hostname):
        response = BaseResponse()

        ret = {}
        entries = asset.get_asset_entries()
        for asset_name, method in entries.items():
            asset_resp = BaseResponse()
            cmds, parse_method = method
            lst = []
            try:
                for cmd in cmds:
                    lst.append(self.exec_shell_cmd(cmd, hostname))
                asset_resp.data = parse_method('\n'.join(lst))
            except Exception:
                print('------------------', asset_name)
                msg = '{} {} plugin error: {}'.format(hostname, asset_name,
                                                      traceback.format_exc())
                self.logger.error(msg)
                asset_resp.status = False
                asset_resp.error = msg
            ret[asset_name] = asset_resp

        response.data = ret
        return response

    def post_asset(self,
                   name,
                   data,
                   callback=None):  # TODO 发送数据前,数据中有response类实例需先处理
        """ 向API提交数据 """
        print('-------------------:', name, type(Json.dumps(data)),
              Json.dumps(data))
        try:
            response = requests.post(
                url=self.asset_api,
                headers=self.key_header,
                json=Json.dumps(data),
            )
            status = True
        except Exception as e:
            print(e)
            response = e
            status = False
        if callback:
            callback(status, response)

    def callback(self, status, response):
        """
            提交资产后的回调函数
        :param status:      请求是否成功
        :param response:    请求成功,返回的是响应报文; 请求失败,则是异常对象
        :return:
        """
        if not status:
            self.logger.error(str(response))
            return
        ret = json.loads(response.text)
        if ret['code'] == 1000:
            self.logger.info(ret['message'])
        else:
            self.logger.error(ret['message'])
示例#3
0
class RequestBase(object):
    """
    @summary 封装request模块
    """
    def __init__(self):
        self.log = Logger()
        #self.cookid = dict(anonymid=jk63khrk-y97r4p; _r01_=1; [email protected])

    def get_json(self, **kw):
        """
        @summary  get请求返回结果处理为json
        @param    kw    request请求的参数
        @return   返回处理后的请求结果 
        """
        try:
            request = requests.get(**kw)
            result = request.json()
            self.log.info('GET请求返回json为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送GET请求,json结果解析失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def post_json(self, **kw):
        """
        @summary  post请求返回结果处理为json
        @param    kw    request请求的参数 
        @return   返回处理后的请求结果        
        """
        try:
            request = requests.post(**kw)
            result = request.json()
            self.log.info('POST请求返回json为:\n{}'.format(result))
            return result
        except Exception as e:
            self.log.error('发送POST请求,并将结果解析json失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def get_status_code(self, **kw):
        """
        @summary  get请求状态码
        @param    kw    request请求的参数 
        @return   返回处理后的请求结果       
        """
        try:
            request = requests.get(**kw)
            result = request.status_code
            self.log.info('GET请求返回status_code为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送GET请求,并获取请求状态失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def post_status_code(self, **kw):
        """
        @summary  post请求状态码
        @param    kw    request请求的参数 
        @return   返回处理后的请求结果        
        """
        try:
            request = requests.post(**kw)
            result = request.status_code
            self.log.info('POST请求返回status_code为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送POST请求,并获取请求状态失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def get_text(self, **kw):
        """
        @summary  get请求返回结果处理为text
        @param    kw    request请求的参数
        @return   返回处理后的请求结果 
        """
        try:
            request = requests.get(**kw)
            result = request.text
            self.log.info('GET请求返回text为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送GET请求,并将结果解析text失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def post_text(self, **kw):
        """
        @summary  post请求返回结果处理为text
        @param    kw    request请求的参数 
        @return   返回处理后的请求结果 
        """
        try:
            request = requests.post(**kw)
            result = request.text
            self.log.info('POST请求返回text为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送POST请求,并将结果解析text失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def post_multipart(self, url, files):
        """
        @summary  post请求表单上传
        @param    url  str  请求url
        @param    file 文件存储路径 
        @return   返回处理后的请求结果 
        """
        try:
            files = {'file': (file, 'rb')}
            result = requests.post(url=url, files=files)
            return result
        except Exception:
            self.log.error('POST表单上产失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))

    def delete_json(self, **kw):
        """
        @summary  delete请求返回结果处理为json
        @param    kw    request请求的参数
        @return   返回处理后的请求结果 
        """
        try:
            request = requests.delete(**kw)
            result = request.json()
            self.log.info('delete请求返回json为:\n{}'.format(result))
            return result
        except Exception:
            self.log.error('发送delete请求,json结果解析失败,错误堆栈:\n{}'.format(
                traceback.format_exc()))