コード例 #1
0
    def select_listenerld(self):
        module = 'lb'
        action = 'DescribeForwardLBListeners'
        config = {
            'Region': 'ap-beijing',
            'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79',
            'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt',
        }

        action_params = {'Version': '2017-03-12', 'loadBalancerId': self.lb_id}
        # 接口参数

        try:
            service = QcloudApi(module, config)
            print(service.generateUrl(action, action_params))
            res = service.call(action, action_params)
            res = json.loads(res.decode())
            self.listen_id = res['listenerSet'][0]['listenerId']
            print(self.listen_id, '-----------------监听id---------------')
        except Exception as e:
            print(e)
            import traceback
            print('traceback.format_exc():\n%s' % traceback.format_exc())
コード例 #2
0
ファイル: qcloud.py プロジェクト: Near-Zhang/flex_cmdb
    def _old_request(self) -> dict:
        """
        使用老版 sdk 发送请求,返回响应结果
        :return: 包含响应结果的字典
        """
        # 传入密钥,获取客户端
        secret_params = ({
            'secretId': self._ak_sk[0],
            'secretKey': self._ak_sk[1]
        })
        client = QcloudApi(self._interface['module'], secret_params)
        client.generateUrl(self._interface['name'], self._params)

        # 进行请求,得到响应
        try:
            resp = client.call(self._interface['name'], self._params)
        except TencentCloudSDKException as e:
            if not e.requestId:
                raise CloudNativeSDKError(f'client error: {e.message}')
            return self._build_error_data(e)

        # 将结果反序列化为对象并输出
        return safe_json_loads(resp)
コード例 #3
0
ファイル: create_cdb.py プロジェクト: yanliangchen/demo_cloud
    def safe_group(self):
        '''

         给加一个安全组
        :return:
        '''

        self.module = 'dfw'
        '''
        action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名
        '''

        self.action = 'CreateSecurityGroup'
        '''
        config: 云API的公共参数
        '''
        self.config = {
            'Region': 'ap-beijing',
            'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79',
            'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt',
        }

        # 接口参数
        self.action_params = {
            'Version': '2017-03-12',
            'sgName': 'safe_group_one'
        }  #
        try:
            service = QcloudApi(self.module, self.config)
            print(service.generateUrl(self.action, self.action_params))
            res = service.call(self.action, self.action_params)
            print(eval(res))

        except Exception as e:
            print(e)
            import traceback
            print('traceback.format_exc():\n%s' % traceback.format_exc())
コード例 #4
0
 def getContent(url):
     '''
 parameter:
     url:The target url
 return:
     data:The result in json format.Fields contained:code,title,content
     use data['title'] to access
 '''
     module = 'wenzhi'
     action = 'ContentGrab'
     region = "sz"
     path = Util.getDataPath("keys/keys2.txt")
     with open(path) as f:
         secretId = f.readline().strip('\n')
         secretKey = f.readline().strip('\n')
     config = {
         'Region': region,
         'secretId': secretId,
         'secretKey': secretKey}
     action_params = {
         'url':url
     }
     try:
         service = QcloudApi(module, config)
         #print(service.generateUrl(action, action_params))
         result = service.call(action, action_params)
         #print(result)
     except Exception as e:
         print('traceback.format_exc():\n%s' % traceback.format_exc())
     if(result == None):
         return
     data = json.loads(result.decode('utf-8'))
     if(result != None and data["code"] != 0):
         return None
     else:
         return data
コード例 #5
0
ファイル: create_cdb.py プロジェクト: yanliangchen/demo_cloud
    def chush_cdb(self):
        self.module = 'cdb'
        '''
        action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名
        '''

        self.action = 'InitDBInstances'
        '''
        config: 云API的公共参数
        '''
        self.config = {
            'Region': 'ap-beijing',
            'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79',
            'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt',
        }

        # 接口参数
        self.action_params = {
            'action': 'InitDBInstances',
            'Version': '2017-03-12',
            'instanceIds': self.in_ids,
            'newPassword': '******',
            'parameters': [{
                'name': 'character_set_server',
                'value': 'utf8'
            }],
        }
        try:
            service = QcloudApi(self.module, self.config)
            print(type(service.generateUrl(self.action, self.action_params)))
            res = service.call(self.action, self.action_params)
            print(eval(res))
        except Exception as e:
            print(e)
            import traceback
            print('traceback.format_exc():\n%s' % traceback.format_exc())
コード例 #6
0
def update_new_ssl():
    with open(CERTPATH, 'r') as f:
        cert = f.read()
    with open(KEYPATH, 'r') as f:
        key = f.read()
    try:
        action = 'CertUpload'
        action_params = {
            'Limit': 1,
            'cert': cert,
            'certType': "SVR",
            'key': key,
            'alias': "Auto upload from script"
        }
        service = QcloudApi(module, config)
        result_json = service.call(action, action_params)
        result = json.loads(result_json)
        if result['code'] != 0:
            raise Exception
        else:
            logging.info(result['message'])
    except Exception as e:
        logging.warning(result['message'])
        os._exit(0)
コード例 #7
0
def request_put(module, config, action, params):
    service = QcloudApi(module, config)
    str_results = service.call(action, params)
    json_results = json.loads(str_results)
    return json_results
コード例 #8
0
ファイル: ssserver.py プロジェクト: xfye/auto-ssserver
 def describe_zones(self):
     module = 'cvm'
     action = 'DescribeZones'
     params = {}
     service = QcloudApi(module, self._get_api_config())
     print(json.loads(service.call(action, params)))
コード例 #9
0
ファイル: ssserver.py プロジェクト: xfye/auto-ssserver
 def describe_instances(self):
     module = 'cvm'
     action = 'DescribeInstances'
     params = {'Limit': 1}
     service = QcloudApi(module, self._get_api_config())
     print(json.loads(service.call(action, params)))
コード例 #10
0
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(url='%s/api/sync/host/price' % url,
                          headers=headers,
                          data=json.dumps(data))
    req.get_method = lambda: 'PUT'
    urllib2.urlopen(req)


if __name__ == '__main__':
    # 获取腾讯云项目信息
    logger.info(u'处理项目信息开始')

    module = 'account'
    action = 'DescribeProject'

    service = QcloudApi(module, config)
    resp = service.call(action, {'Version': '2018-07-12'})
    projects = json.loads(resp)['data']
    headers = {'Content-Type': 'application/json'}
    req = urllib2.Request(url='%s/api/sync/project' % url,
                          headers=headers,
                          data=json.dumps(projects))
    req.get_method = lambda: 'PUT'
    urllib2.urlopen(req)
    logger.info(u'处理项目信息结束')

    # 获取腾讯云主机信息 (实例列表接口请求频率限制40次/每秒)
    logger.info(u'处理云主机信息开始')

    hosts = []
コード例 #11
0
def main_run():
    # 遍历字典
    for key, value in config_json.items():
        # 如果cert_filename为空,则将证书文件名为默认的[domain_name].crt
        # 否则则加载配置文件中的文件名
        if value['cert_filename'] == "":
            cert_filename = key + '.crt'
        else:
            cert_filename = value['cert_filename']

        # 如果cert_filename为空,则将证书文件名为默认的[domain_name].key
        # 否则则加载配置文件中的文件名
        if value['key_filename'] == "":
            key_filename = key + '.key'
        else:
            key_filename = value['key_filename']

        check_cert_info_dict = check_cert_info(cert_file_folder + cert_filename)

        open_temp_file = try_to_open_file(tmp_file_path, 0)
        if open_temp_file[0]:
            open_temp_file = json.loads(open_temp_file[1])
            if key in open_temp_file:
                if open_temp_file[key] == check_cert_info_dict['crt_serial_number']:
                    continue
                else:
                    pass
            else:
                pass
        else:
            pass

        if crt_chk_alt_name(key, check_cert_info_dict['crt_altname']):
            pass
        else:
            continue

        crt_not_valid_before = check_cert_info_dict['crt_not_valid_before']
        crt_not_valid_after = check_cert_info_dict['crt_not_valid_after']

        # 调用函数,检查证书是否合规
        crt_key_dict = format_cert_key(key, cert_filename, key_filename, crt_not_valid_before, crt_not_valid_after)

        # 不合规则跳过,进入下一循环
        if crt_key_dict:
            # 腾讯云基础设定
            config = {
                'secretId': value['secret_id'],
                'secretKey': value['secret_key'],
            }

            cdn_domain_list = get_cdn_domain(config)

            if key in cdn_domain_list:
                action = 'SetHttpsInfo'
                module = 'cdn'
                params = {
                    'host': key,
                    'httpsType': value['https_type'],
                    'forceSwitch': value['https_force_switch'],
                    'http2': value['http2'],
                    'cert': crt_key_dict['crt'],
                    'privateKey': crt_key_dict['key']
                }
                # 调用API
                service = QcloudApi(module, config)
                # 可输出编码后的URL,主要用于日志,也可以生成URL后手动执行
                # 自动化应用一般不需要
                # print(service.generateUrl(action, params))
                # 执行API
                qcloud_output = service.call(action, params).decode()
                print(qcloud_output)
                write_temp_file(qcloud_output, key, check_cert_info_dict['crt_serial_number'])
            else:
                continue
        else:
            continue
コード例 #12
0
ファイル: tensdk.py プロジェクト: fishforks/myops
 def connect(self):
     if self.conn or self.conn_image:
         return
     self.conn = QcloudApi(self.module, self.config)
     self.conn_image = QcloudApi("image", self.config)
コード例 #13
0
def get_domain_id(ip):
    module = 'cns'

    # 对应接口的接口名,请参考wiki文档上对应接口的接口名
    action = 'RecordList'

    # 云API的公共参数
    config = {
        'secretId': 'XXXX',
        'secretKey': "XXX",
        'method': 'GET',
        'SignatureMethod': 'HmacSHA1',
        # 只有cvm需要填写version,其他产品不需要

    }

    # 接口参数,根据实际情况填写,支持json
    # 例如数组可以 "ArrayExample": ["1","2","3"]
    # 例如字典可以 "DictExample": {"key1": "value1", "key2": "values2"}
    action_params = {
        'domain': 'wdbefore.com',
    }

    try:
        service = QcloudApi(module, config)

        # 请求前可以通过下面几个方法重新设置请求的secretId/secretKey/Region/method/SignatureMethod参数
        # 重新设置请求的Region
        # service.setRegion('ap-shanghai')

        # 打印生成的请求URL,不发起请求
        print(service.generateUrl(action, action_params))
    # 调用接口,发起请求,并打印返回结果
        data = service.call(action, action_params)
    except Exception as e:
        import traceback
        print('traceback.format_exc():\n%s' % traceback.format_exc())
    data = json.loads(data)

    # 处理json 读记录ID Type Value

    records = data['data']['records']

    print(json.dumps(records, sort_keys=True, indent=4))
    for record in records:
        id_lst = []
        if record['type'] == 'AAAA' and record['name'] == 'home':
            action = 'RecordModify'
            # 例如字典可以 "DictExample": {"key1": "value1", "key2": "values2"}
            action_params = {
                'domain': 'wdbefore.com',
                'subDomain': 'home',
                'recordId': record['id'],
                'recordType': 'AAAA',
                'recordLine': '默认',
                'value': ip

            }

            try:
                service = QcloudApi(module, config)

                # 请求前可以通过下面几个方法重新设置请求的secretId/secretKey/Region/method/SignatureMethod参数
                # 重新设置请求的Region
                # service.setRegion('ap-shanghai')

                # 打印生成的请求URL,不发起请求
                print(service.generateUrl(action, action_params))
                # 调用接口,发起请求,并打印返回结果
                data = service.call(action, action_params)
            except Exception as e:
                print('traceback.format_exc():\n%s' %
                      traceback.format_exc())
コード例 #14
0
    def create_cvm(self):

        module = 'cvm'
        '''
        action: 对应接口的接口名,请参考产品 API 文档上对应接口的接口名
        '''
        action = 'RunInstances'
        '''
        config: 云API的公共参数

        # region = input('请输入您想要建立的地域:\n例如:beijing \n')
        # print(region)
        # print('------------------------')
        # num=input('请输入可用区:\n例如您想选择北京1区 您只需要输入数字 "1" \n')
        # print('------------------------')
        '''

        config = {
            'Region': 'ap-beijing',
            'secretId': 'AKIDTp13vccxugHgv0QjOsBJG2d2HMH0Lv79',
            'secretKey': '2vfFetxqZ7UghWBfy51nZROK5f5KOIBt',
        }
        '''
        print('地域和地区选择成功')
        print('------------------------')
        charge_type = input('请输入您所需要的计费模式:\n例如:按量计费则请输入:POSTPAID_BY_HOUR\n按年计费则输入:PREPAID\n')
        print('------------------------')
        system_type = input('请选择您所需要/系统盘,类型如下:\n本地硬盘 : LOCAL_BASIC \n本地SSD硬盘 : LOCAL_SSD\n普通云硬盘 : CLOUD_BASIC\n云硬盘 : CLOUD_SSD\n')
        system_size =  input('请选择您所需要的系统盘大小\n')
        print('系统盘大小和类型填写成功')
        print('------------------------')
        data_type = input('请选择您要的数据盘,类型如下:\n本地硬盘 : LOCAL_BASIC\n本地SSD硬盘 : LOCAL_SSD\n普通云硬盘 : CLOUD_BASIC\n高性能云硬盘 : CLOUD_PREMIUMSSD\n云硬盘 : CLOUD_SSD\n')
        data_size = input('请选择您所需要的数据盘大小\n')
        print('数据盘大小和类型填写成功')
        print('------------------------')
        cvm_name = input('请给您的实例进行命名\n')
        print('命名成功')
        print('------------------------')
        gongwang_ip = int(input('是否分配公网ip,如需分配请输入1 ,不分配则输入0\n'))
        print('分配成功')
        print('------------------------')
        '''

        # 接口参数
        action_params = {
            # API  版本号
            'Version': '2017-03-12',
            # 计费类型 按量计费
            'InstanceChargeType': 'POSTPAID_BY_HOUR',
            # 选择地域和可用区
            'Placement.Zone': 'ap-beijing-3',
            # 镜像
            'ImageId': 'img-8toqc6s3',
            # 镜像机型1C1G 标准型
            'InstanceType': 'S2.SMALL1',
            # 系统盘的类型
            'SystemDisk.DiskType': 'CLOUD_BASIC',
            # 'SystemDisk.DiskType':'CLOUD_BASIC',
            # 系统盘的大小
            'SystemDisk.DiskSize': '60',
            # 数据盘类型
            'DataDisks.0.DiskType': 'CLOUD_BASIC',
            # 数据盘大小  50
            'DataDisks.0.DiskSize': '60',
            # 外网带宽上限10
            'InternetAccessible.InternetMaxBandwidthOut': 10,
            # 分配公网ip
            'InternetAccessible.PublicIpAssigned': True,
            # 实例命名
            'InstanceName': 'liyanliang',
        }

        try:
            service = QcloudApi(module, config)
            print(service.generateUrl(action, action_params))
            res = service.call(action, action_params)
            print(eval(res))
            res = json.loads(res.decode())
            print(res)
            self.res = res['Response']['InstanceIdSet'][0]
            print('云主机创建成功')

        except Exception as e:
            print(e)
            import traceback
            print('traceback.format_exc():\n%s' % traceback.format_exc())
コード例 #15
0
    def __init__(self, secretId, secretKey, domain):
        module = 'cns'
        config = {'secretId': secretId, 'secretKey': secretKey}
        self.service = QcloudApi(module, config)

        self.domain = domain
コード例 #16
0
 def request_put(self):
     service = QcloudApi(self.module, self.config)
     str_results = service.call(self.action, self.params)
     json_results = json.loads(str_results)
     return json_results
コード例 #17
0
ファイル: tushareData.py プロジェクト: wqj97/QuantResearch
from QcloudApi.qcloudapi import QcloudApi
import requests as rq

import json

Wenzhi_config = {
    'Region': 'bj',
    'secretId': 'AKID99jjLdep9fbPZP96VmYfRkjORy3gocKV',
    'secretKey': 'rNSnqdmBIqB65Je73GoJIwCulXdXp9Pt',
    'method': 'POST',
    'SignatureMethod': 'HmacSHA1'
}

Wenzhi_action = 'TextSentiment'
Wenzhi_module = 'wenzhi'
service = QcloudApi(Wenzhi_module, Wenzhi_config)

# number_to_claw = input('输入想要抓取的新闻数, 默认为10\r\n')
# if not number_to_claw:
number_to_claw = 10

while True:
    print("开始抓取数据")
    data = ts.get_latest_news(number_to_claw, True)
    for index, val in data.iterrows():
        print('processing {}/{}'.format(index + 1, len(data)))
        exist = rq.post('https://www.lyquant.com/api/news/check',
                        {'url': val['url']})
        if exist.status_code == 200:
            continue
        analysis = service.call(Wenzhi_action, {