示例#1
0
def get_network_health(event, context):
    requests.packages.urllib3.disable_warnings()
    url="https://10.10.1.2/dna/intent/api/v1/network-health"
    hdr = {'x-auth-token':get_token(event, context), 'content-type':'application/json'}
    resp=requests.get(url,headers=hdr,verify=False)
    network_health=resp.json()
    return network_health
示例#2
0
def get_headers(abid='1-100'):
    token = get_token.get_token()
    headers = {
        'Host': 'dev.api.kuai8.mobi',
        'cp-uuid': '4c51cc98f0bfca72d8a38e09c8c7b32bc9081902',
        'User-Agent': 'kuai8shi pai/1.1.3 (iPhone; iOS 12.1.4; Scale/2.00)',
        'cp-abid': abid,
        'cp-appid': '800',
        'cp-sign': '3657f82f2c814ff420d6ecfaafa8dab8',
        'cp-ver': '1.1.3',
        'cp-time': '1553224952',
        'cp-token': str(token),
        'cp - os': 'ios',
        'cp - vend': 'kuai8',
        'cp - oem': 'iphone8',
        'Accept - Language': 'zh-Hans-CN;q=1',
        'cp - sver': '12.1.4',
        'Accept': '* / *',
        'cp - channel': 'appstore',
        'Accept - Encoding': 'gzip, deflate',
        'BodyEncode': '1',
        'AppKey': 'kuai8-ios',
        'Connection': 'keep-alive'
    }
    return headers
示例#3
0
文件: get_vm.py 项目: juncgu/Heat
def get_vm(host):
    token = get_token.get_token() 
    head = ["X-Authr-Project-Id: admin", "Accept: application/json"]
    header = "X-Auth-Token: " + token
    head.append(header)
#    url = 'http://controller:5001/v1/probes/'
    url = globalValue.data_vm_url()
    url = url + host + '/servers'
    d = data()
    c = pycurl.Curl()
    c.setopt(c.HTTPHEADER, head)
#    c.setopt(c.HTTPHEADER, [header])
    c.setopt(c.CUSTOMREQUEST, "GET")
    c.setopt(pycurl.VERBOSE, 1)
    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.MAXREDIRS, 5)
    c.setopt(c.URL, url)
    c.setopt(c.HEADERFUNCTION, d.head_write)
    c.setopt(c.WRITEFUNCTION, d.body_write)
    try:
        c.perform()
    except:
        print 'Error: get_vm: c.perform()'
      
    c.close()
    print d.body
    if d.body['hypervisors'][0].has_key('servers') == True:
        return d.body['hypervisors'][0]['servers']
    else:
        return {}
示例#4
0
文件: get_probes.py 项目: juncgu/Heat
def get_probes():
    token = get_token.get_token() 
    head = ["Content-Type: application/json", "Accept: application/json"]
    header = "X-Auth-Token: " + token
    head.append(header)
#    url = 'http://controller:5001/v1/probes/'
    url = globalValue.data_probes_url()
    #d = data()
    body = cStringIO.StringIO()
    headd = cStringIO.StringIO()

    c = pycurl.Curl()
    c.setopt(c.HTTPHEADER, head)
#    c.setopt(c.HTTPHEADER, [header])
    c.setopt(c.CUSTOMREQUEST, "GET")
    c.setopt(pycurl.VERBOSE, 1)
    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.MAXREDIRS, 5)
    c.setopt(c.URL, url)
    c.setopt(c.HEADERFUNCTION, headd.write)
    c.setopt(c.WRITEFUNCTION, body.write)
    try:
        c.perform()
    except pycurl.error:
        print "Error: get_probes: c.perform()"
        emergency.turn_on_utility()
        
    c.close()
    re_dict = simplejson.loads(body.getvalue())
    pro = copy.copy(re_dict)
    print pro['probes']
    return pro['probes']
示例#5
0
def main(current_ip):
    
    with open('rax_config.pkl', 'rb') as f:
        domain_id, record_id, url, api_key, username  = pickle.load(f)

    token = get_token(username, api_key)

    update_record(token, current_ip, url, domain_id, record_id)
def queryRolePermission(button_name):  #查询出所有选中的按钮
    url = f'http://crm-{Environmental_Science}.dm-cube.com/crm/sys/permission/queryRolePermission?_t=1605578557&roleId={button_name}'
    header = {
        "Content-Type": "application/json",
        "X-Access-Token": get_token(Environmental_Science)
    }
    res = requests.get(url=url, headers=header)
    return res.json()['result']
def get_site_list(event, context):
    site_type = {'type' : 'building'}
    requests.packages.urllib3.disable_warnings()
    url = "https://10.10.1.2/dna/intent/api/v1/site"
    hdr = {'x-auth-token':get_token(event, context), 'content-type':'application/json'}
    resp = requests.get(url, headers=hdr, params=site_type, verify=False)
    site_list = resp.json()
    return site_list
示例#8
0
def main():
    '''
	Execution is done here
	'''
    ipaddress = input(" Print the IP Address of the Device :")
    username = input(" Username of the DNA Center :")
    password = input(" Password of the DNA Center :")
    token = get_token(username, password)
    print(add_device(token, ipaddress))
示例#9
0
 def get_ip_pool():
     requests.packages.urllib3.disable_warnings()
     url = "https://10.10.1.2/dna/intent/api/v1/global-pool"
     hdr = {
         'x-auth-token': get_token(event, context),
         'content-type': 'application/json'
     }
     resp = requests.get(url, headers=hdr, verify=False)
     ip_pool = resp.json()
     return ip_pool
示例#10
0
def get_device_list(event, context):
    requests.packages.urllib3.disable_warnings()
    url = "https://10.10.1.2/api/v1/network-device"
    hdr = {
        'x-auth-token': get_token(event, context),
        'content-type': 'application/json'
    }
    resp = requests.get(url, headers=hdr, verify=False)
    device_list = resp.json()
    return device_list
示例#11
0
def cluster_config(clustername):
    # create an instance of the API class
    # Configure API key authorization: BearerToken
    configuration = kubernetes.client.Configuration()
    configuration.api_key['authorization'] = get_token(clustername)
    configuration.host = 'https://B595B1603A2DF8F3ABA6D0A0DA363277.sk1.us-east-2.eks.amazonaws.com'
    configuration.verify_ssl = False
    # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    configuration.api_key_prefix['authorization'] = 'Bearer'
    return configuration
示例#12
0
 def get_site_device():
     requests.packages.urllib3.disable_warnings()
     url = "https://10.10.1.2/dna/intent/api/v1/membership/%s" % get_site_id(
         event, context)[n]
     hdr = {
         'x-auth-token': get_token(event, context),
         'content-type': 'application/json'
     }
     resp = requests.get(url, headers=hdr, verify=False)
     site_device = resp.json()
     return site_device
示例#13
0
def main(username, api_key, account_num, target_domain, domain):

    headers = {'X-Auth-Token': get_token(username, api_key)}
    url = 'https://dns.api.rackspacecloud.com/v1.0/' + account_num

    domain_id = find_domain_id(account_num, domain, headers, url)
    record_id = find_record_id(account_num, domain_id, headers, url,
                               target_domain)

    with open('rax_config.pkl', 'wb') as f:
        pickle.dump([domain_id, record_id, url, api_key, username], f)
示例#14
0
def main():
    '''
	Main Execution begins here
	'''
    # Get user inputs for username and password
    username = input("Username: "******"Password: "******"The management IP of all the Devices are ")
    get_devices_mgmt_ip(devices_list)
def floatModels_marqueeModels_popModels():
    url = 'http://crm-dev.dm-cube.com/crm/pageConfig/list'
    header = {
        "Content-Type": "application/json",
        "X-Access-Token": get_token()
    }
    res = requests.post(url=url, json={}, headers=header)
    floatModels = res.json()['payload']['floatModels'][0]['id']
    marqueeModels = res.json()['payload']['marqueeModels'][0]['id']
    popModels = res.json()['payload']['popModels'][0]['id']

    return floatModels, marqueeModels, popModels
示例#16
0
def saveRolePermission(roleName, button_name):
    b = []
    b = get_role_permissions_list(button_name) + queryRolePermission(
        button_name)
    b = list(set(b))
    c = (',').join(str(c) for c in b)
    url = 'http://crm-dev.dm-cube.com/crm/sys/permission/saveRolePermission'
    header = {
        "Content-Type": "application/json",
        "X-Access-Token": get_token(Environmental_Science)
    }
    payload = {"permissionIds": c, "roleId": get_roleid(roleName)}
    res = requests.post(url=url, json=payload, headers=header)
    return print(res.json())
def handler(event, context):
    print(event)
    print(context)
    token = get_token(event)
    id_token = verify_token(token)
    print(id_token)
    if id_token and id_token.get('permissions'):
        scopes = '|'.join(id_token['permissions'])
        policy = generate_policy(id_token['sub'],
                                 'Allow',
                                 event['methodArn'],
                                 scopes=scopes)
        return policy
    else:
        policy = generate_policy(id_token['sub'], "Deny", event['methodArn'])
        return policy
示例#18
0
    def get_query_answer(self):
        """把异常写进日志"""
        try:
            self.__logger.info("获取token")  # #用query-作为分隔符
            access_token = get_token(self.__logger)
            self.__logger.info("access_token-" + access_token)

        except Exception as e:
            self.__logger.info("error:")
            self.__logger.info(e)
            self.__logger.info("traceback My:")
            self.__logger.info(
                traceback.format_exc())  # #返回异常信息的字符串,可以用来把信息记录到log里
            access_token = {}

        return access_token
示例#19
0
        def get_id(img):

            _token = gt.get_token()
            _url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' + _token + '&type=image'
            print('url=', _url)

            payload = {'file': ('upload.jpg', img, 'image/jpg')}
            m = MultipartEncoder(payload)
            headers = {
                'Content-Type': m.content_type,
                'other-keys': 'other-values'
            }
            _id = requests.post(_url, headers=headers, data=m).json()
            print('post request returns:', _id)
            _id = _id['media_id']
            print(_id)
            return _id
示例#20
0
def get_roleid(roleName):
    url = f'http://crm-{Environmental_Science}.dm-cube.com/crm/sys/role/list?_t=1605507756&column=createTime&order=desc&field=id,,,roleName,roleCode,description,createTime,updateTime,action&pageNo=1&pageSize=60'
    header = {
        "Content-Type": "application/json",
        "X-Access-Token": get_token(Environmental_Science)
    }
    res = requests.get(url=url, headers=header)
    total = res.json()['result']['total']
    roleid = []
    for i in range(0, total):
        roleid.append(res.json()['result']['records'][i])
    for y in roleid:
        # print(y)
        if y['roleName'] == roleName:
            roleid = y['id']
            print(roleid)
    return roleid
示例#21
0
def main():
    token = get_token()
    api_path = "https://sandboxdnac.cisco.com/dna"
    headers = {"Content-Type": "application/json", "X-Auth-Token": token}

    get_resp = requests.get(
        #f"{api_path}/intent/api/v1/network-device", headers=headers
        "https://sandboxdnac.cisco.com/dna/intent/api/v1/network-device",
        headers=headers)
    import json
    # print(json.dumps(get_resp.json(), indent=2))
    if get_resp.ok:
        for device in get_resp.json()["response"]:
            print(f"ID: {device['id']} IP: {device['managementIpAddress']}")
    else:
        print(f"Device collection failed with code {get_resp.status_code}")
        print(f"Fauilure body: {get_resp.txt}")
示例#22
0
def handler(event, context):
    print(event)
    print(context)
    token = get_token(event)
    id_token = verify_token(token)
    print(id_token)
    userinfo = requests.get('https://' + AUTH0_DOMAIN + '/userinfo',
                            headers={
                                "Authorization": "Bearer " + token
                            }).json()
    if id_token and userinfo['email_verified'] and id_token.get('permissions'):
        scopes = '|'.join(id_token['permissions'])
        policy = generate_policy(id_token['sub'],
                                 'Allow',
                                 event['methodArn'],
                                 scopes=scopes)
        return policy
    else:
        policy = generate_policy(id_token['sub'], "Deny", event['methodArn'])
        return policy
示例#23
0
def get_role_permissions_list(button_name):  #请输入按钮的名称 查询、导出、新增.....
    url = f'http://crm-{Environmental_Science}.dm-cube.com/crm/sys/role/queryTreeList?_t=1605513356'
    header = {
        "Content-Type": "application/json",
        "X-Access-Token": get_token(Environmental_Science)
    }
    res = requests.get(url=url, headers=header)
    pprint.pprint(len(res.json()['result']['treeList']))
    secondary_menu = []
    amount = 0
    skip = []
    c = 0
    b = 0
    button_key = []
    for i in range(0, 19):
        if res.json()['result']['treeList'][i]['children'] != None:
            secondary_menu.append(
                len(res.json()['result']['treeList'][i]['children']))
            amount += 1  #有效条数
        else:
            skip.append(i)  #跳过
    for y in range(c, amount):
        if y in skip:
            print('skip')
        else:
            for xx in range(0, secondary_menu[b]):
                if res.json(
                )['result']['treeList'][y]['children'][xx]['children'] != None:
                    button = len(res.json()['result']['treeList'][y]
                                 ['children'][xx]['children'])  #全部按钮的数量
                    # print(res.json()['result']['treeList'][y]['children'][xx]['children'])  #可以查看全部按钮
                    for xxx in range(0, button):
                        if res.json()['result']['treeList'][y]['children'][xx][
                                'children'][xxx]['slotTitle'] == button_name:
                            button_key.append(
                                res.json()['result']['treeList'][y]['children']
                                [xx]['children'][xxx]['key'])

    return button_key
示例#24
0
def run_regression_script(container_list):
    global log
    product_list = []
    for cnt in container_list:
        total_tested = 0
        total_failed = 0
        split_val = cnt[1].split('.')
        DEPLOYMENT_URL = cnt[3]
        DEPLOYMENT_ROUTE = cnt[2]
        TOKEN = get_token(cnt[4], cnt[5])
        module = split_val[0]
        container = split_val[1]
        banner = get_banner(container)
        print(banner)
        features = get_all_services(auth, module, container)
        container_test_root = PROJECT_ROOT + '/' + module + '-service/tests/regression/' + container + '-service'
        product_dict = {'product': container}
        product_dict['path'] = container_test_root
        product_dict['path-exists'] = True if os.path.exists(
            container_test_root) else False
        # print(SERVICE_PATH)
        feature_list = []
        for f in features:
            feature = list(f.keys())
            services = list(f.values())
            feature_dict = {'feature': feature[0]}
            feature_dict[
                'path'] = container_test_root + '/python/' + container + '-' + feature[
                    0]
            feature_dict['path-exists'] = True if os.path.exists(
                container_test_root + '/python/' + container + '-' +
                feature[0]) else False
            service_list = []
            for s in services[0]:
                service_dict = {'service': s}
                script_dir = container_test_root + '/python/' + container + '-' + feature[
                    0] + '/' + s
                service_dict['path'] = script_dir
                if os.path.exists(script_dir):
                    service_dict['path-exists'] = True
                    os.chdir(script_dir)
                    print("Found Directory : " + script_dir)
                    if os.path.exists('./run_regression.sh'):
                        service_dict['scripts-path-exists'] = True
                        cmd = './run_regression.sh'
                        result = subprocess.run(
                            [cmd, DEPLOYMENT_URL, DEPLOYMENT_ROUTE, TOKEN],
                            stdout=subprocess.PIPE)
                        result = result.stdout.decode('utf-8')
                        print(result)

                        passed_regex = re.findall(r'TestPassed.*', result)
                        tests = []
                        id = 0
                        pass_count = 0
                        for line in passed_regex:
                            id += 1
                            m = re.compile(r'service_test_.*\.py').search(
                                line).group()
                            tests.append([id, m, 'Passed'])
                            pass_count += 1
                        service_dict['tests-pass-count'] = pass_count

                        failed_regex = re.findall(r'TestFailed.*', result)
                        fail_count = 0
                        for line in failed_regex:
                            id += 1
                            m = re.compile(r'service_test_.*\.py').search(
                                line).group()
                            tests.append([id, m, 'Failed'])
                            fail_count += 1
                        service_dict['tests-fail-count'] = fail_count
                        service_dict['tests-count'] = pass_count + fail_count
                        service_dict['tests'] = tests
                        if fail_count > 0:
                            service_dict['coverage-status'] = False
                        else:
                            service_dict['coverage-status'] = True

                        tested_regex = re.compile(r'\( [0-9]+ \) test executed'
                                                  ).search(result).group()
                        tested = re.compile(r'[0-9]+').search(
                            tested_regex).group()

                        failed_regex = re.compile(r'\( [0-9]+ \) test failed'
                                                  ).search(result).group()
                        failed = re.compile(r'[0-9]+').search(
                            failed_regex).group()

                        total_tested = total_tested + int(tested)
                        total_failed = total_failed + int(failed)
                    else:
                        service_dict['scripts-path-exists'] = False
                        service_dict['coverage-status'] = False
                        print(script_dir + '/run_regression.sh not found')
                else:
                    service_dict['path-exists'] = False
                    service_dict['coverage-status'] = False
                    print(script_dir + ' Not Found')
                service_list.append(service_dict)
            feature_dict['services'] = service_list
            feature_dict['services-count'] = len(service_list)
            # print(service_list)
            feature_dict['services-fail-count'] = sum(
                1 for x in feature_dict['services']
                if x['coverage-status'] == False)
            feature_dict['services-pass-count'] = feature_dict[
                'services-count'] - feature_dict['services-fail-count']
            feature_dict['coverage-status'] = False if feature_dict[
                'services-fail-count'] > 0 else True
            feature_list.append(feature_dict)

        product_dict['features-count'] = len(feature_list)
        product_dict['features'] = feature_list

        product_dict['features-fail-count'] = sum(
            1 for x in product_dict['features']
            if x['coverage-status'] == False)
        product_dict['features-pass-count'] = product_dict[
            'features-count'] - product_dict['features-fail-count']
        product_dict['services-count'] = sum(x['services-count']
                                             for x in product_dict['features'])
        product_dict['services-fail-count'] = sum(
            x['services-fail-count'] for x in product_dict['features'])
        product_dict['services-pass-count'] = product_dict[
            'services-count'] - product_dict['services-fail-count']
        product_dict['coverage-status'] = False if product_dict[
            'services-fail-count'] > 0 else True
        product_list.append(product_dict)

        success = total_tested - total_failed
        if total_tested == 0:
            print(SUMMARY)
            print(
                f"\033[{COLOR_FAIL}{container.ljust(15) + str(total_tested).ljust(10) + str(success).ljust(10) + str(total_failed).ljust(10)}\033[00m"
            )
        elif total_failed != 0:
            print(SUMMARY)
            print(
                f"\033[{COLOR_FAIL}{container.ljust(15) + str(total_tested).ljust(10) + str(success).ljust(10) + str(total_failed).ljust(10)}\033[00m"
            )
        else:
            print(SUMMARY)
            print(
                f"\033[{COLOR_GREEN}{container.ljust(15) + str(total_tested).ljust(10) + str(success).ljust(10) + str(total_failed).ljust(10)}\033[00m"
            )
    return product_list
示例#25
0
def fetch_run(run):
    print("Fetching run %s..." % run)
    db_access.dispose_engine()
    runs_url = (
        "https://cmsoms.cern.ch/agg/api/v1/runs?filter[run_number][eq]=%s&fields=start_time,end_time,b_field,energy,delivered_lumi,end_lumi,recorded_lumi,l1_key,hlt_key,l1_rate,hlt_physics_rate,duration,fill_number"
        % run)

    try:
        token = get_token.get_token()
        headers = {"Authorization": "Bearer %s" % (token)}
        response = requests.get(runs_url, headers=headers, verify=False).json()
        oms_runs_json = response
        fills_url = (
            "https://cmsoms.cern.ch/agg/api/v1/fills?filter[fill_number][eq]=%s&fields=injection_scheme,era"
            % oms_runs_json["data"][0]["attributes"]["fill_number"])

        oms_fills_json = requests.get(fills_url, headers=headers,
                                      verify=False).json()

        # TODO: Change to prod url, add cookies and certificate
        dcs_collisions_lumis_url = (
            """https://cmsoms.cern.ch/agg/api/v1/lumisections?filter[run_number][eq]=%s
&filter[cms_active][eq]=true
&filter[bpix_ready][eq]=true
&filter[fpix_ready][eq]=true
&filter[tibtid_ready][eq]=true
&filter[tecm_ready][eq]=true
&filter[tecp_ready][eq]=true
&filter[tob_ready][eq]=true
&filter[ebm_ready][eq]=true
&filter[ebp_ready][eq]=true
&filter[eem_ready][eq]=true
&filter[eep_ready][eq]=true
&filter[esm_ready][eq]=true
&filter[esp_ready][eq]=true
&filter[hbhea_ready][eq]=true
&filter[hbheb_ready][eq]=true
&filter[hbhec_ready][eq]=true
&filter[hf_ready][eq]=true
&filter[ho_ready][eq]=true
&filter[dtm_ready][eq]=true
&filter[dtp_ready][eq]=true
&filter[dt0_ready][eq]=true
&filter[cscm_ready][eq]=true
&filter[cscp_ready][eq]=true
&filter[gem_ready][eq]=true
#&filter[gemm_ready][eq]=true #	gemm_ready and gemp_ready is not supported yet in oms
#&filter[gemp_ready][eq]=true
&fields=run_number
&page[limit]=1""" % run)

        dcs_cosmics_lumis_url1 = (
            """https://cmsoms.cern.ch/agg/api/v1/lumisections
?filter[run_number][eq]=%s
&filter[dtm_ready][eq]=true
&filter[dtp_ready][eq]=true
&filter[dt0_ready][eq]=true
&filter[gem_ready][eq]=true
#&filter[gemm_ready][eq]=true # gemm_ready and gemp_ready is not supported yet in oms
#&filter[gemp_ready][eq]=true
&fields=run_number
&page[limit]=1""" % run)
        dcs_cosmics_lumis_url2 = (
            """https://cmsoms.cern.ch/agg/api/v1/lumisections
?filter[run_number][eq]=%s
&filter[cscm_ready][eq]=true
&filter[cscp_ready][eq]=true
&fields=run_number
&page[limit]=1""" % run)

        is_dcs = False

        # For cosmics, we need to OR two terms. If first query if false, make a second one.
        if "cosmic" in oms_runs_json["data"][0]["attributes"]["hlt_key"]:
            dcs_lumisections_json = requests.get(
                dcs_cosmics_lumis_url1.replace("\n", ""),
                headers=headers,
                verify=False).json()

            if len(dcs_lumisections_json["data"]):
                is_dcs = True
            else:
                dcs_lumisections_json = requests.get(
                    dcs_cosmics_lumis_url2.replace("\n", ""),
                    headers=headers,
                    verify=False,
                ).json()
                if len(dcs_lumisections_json["data"]):
                    is_dcs = True
        else:
            dcs_lumisections = requests.get(
                dcs_collisions_lumis_url.replace("\n", ""),
                headers=headers,
                verify=False,
            )  # PROBLEMATISKAS
            dcs_lumisections_json = json.loads(dcs_lumisections.text)
            # dcs_lumisections_json = {"data": []}
            if len(dcs_lumisections_json["data"]):
                is_dcs = True

        # Add to cache
        session = db_access.get_session()
        try:
            oms_item = db_access.OMSDataCache(
                run=run,
                lumi=0,
                start_time=datetime.datetime.strptime(
                    oms_runs_json["data"][0]["attributes"]["start_time"],
                    "%Y-%m-%dT%H:%M:%SZ",
                ),
                end_time=datetime.datetime.strptime(
                    oms_runs_json["data"][0]["attributes"]["end_time"],
                    "%Y-%m-%dT%H:%M:%SZ",
                ),
                b_field=oms_runs_json["data"][0]["attributes"]["b_field"],
                energy=oms_runs_json["data"][0]["attributes"]["energy"],
                delivered_lumi=oms_runs_json["data"][0]["attributes"]
                ["delivered_lumi"],
                end_lumi=oms_runs_json["data"][0]["attributes"]["end_lumi"],
                recorded_lumi=oms_runs_json["data"][0]["attributes"]
                ["recorded_lumi"],
                l1_key=oms_runs_json["data"][0]["attributes"]["l1_key"],
                l1_rate=oms_runs_json["data"][0]["attributes"]["l1_rate"],
                hlt_key=oms_runs_json["data"][0]["attributes"]["hlt_key"],
                hlt_physics_rate=oms_runs_json["data"][0]["attributes"]
                ["hlt_physics_rate"],
                duration=oms_runs_json["data"][0]["attributes"]["duration"],
                fill_number=oms_runs_json["data"][0]["attributes"]
                ["fill_number"],
                is_dcs=is_dcs,
            )

            try:
                oms_item.injection_scheme = oms_fills_json["data"][0][
                    "attributes"]["injection_scheme"]
                oms_item.era = oms_fills_json["data"][0]["attributes"]["era"]
            except:
                oms_item.injection_scheme = None
                oms_item.era = None

            session.add(oms_item)
            session.commit()
        except IntegrityError as e:
            print("IntegrityError inserting OMS item: %s" % e)
            session.rollback()
            print("Updating...")

            try:
                oms_item_existing = (session.query(
                    db_access.OMSDataCache).filter(
                        db_access.OMSDataCache.run == oms_item.run,
                        db_access.OMSDataCache.lumi == oms_item.lumi,
                    ).one_or_none())

                if oms_item_existing:
                    if isinstance(oms_item.start_time, datetime.datetime):
                        oms_item_existing.start_time = oms_item.start_time
                    else:
                        oms_item_existing.start_time = datetime.datetime.strptime(
                            oms_item.start_time, "%Y-%m-%dT%H:%M:%SZ")

                    if isinstance(oms_item.end_time, datetime.datetime):
                        oms_item_existing.end_time = oms_item.end_time
                    else:
                        oms_item_existing.end_time = datetime.datetime.strptime(
                            oms_item.end_time, "%Y-%m-%dT%H:%M:%SZ")

                    oms_item_existing.b_field = oms_item.b_field
                    oms_item_existing.energy = oms_item.energy
                    oms_item_existing.delivered_lumi = oms_item.delivered_lumi
                    oms_item_existing.end_lumi = oms_item.end_lumi
                    oms_item_existing.recorded_lumi = oms_item.recorded_lumi
                    oms_item_existing.l1_key = oms_item.l1_key
                    oms_item_existing.l1_rate = oms_item.l1_rate
                    oms_item_existing.hlt_key = oms_item.hlt_key
                    oms_item_existing.hlt_physics_rate = oms_item.hlt_physics_rate
                    oms_item_existing.duration = oms_item.duration
                    oms_item_existing.fill_number = oms_item.fill_number
                    oms_item_existing.injection_scheme = oms_item.injection_scheme
                    oms_item_existing.era = oms_item.era
                    oms_item_existing.is_dcs = oms_item.is_dcs
                    session.commit()
                    print("Updated.")
            except Exception as e:
                print(e)
                session.rollback()
        except Exception as e:
            print(e)
            session.rollback()
        finally:
            session.close()
    except Exception as e:
        print(e)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

USERNAME = '******'
PASSWORD = '******'

if __name__ == '__main__':
    from get_token import get_token
    token = get_token(USERNAME, PASSWORD)

    params = {
        'wstoken': token,
        'wsfunction': 'core_user_get_users_by_field',
        'moodlewsrestformat': 'json',
        'field': 'username',
        'values[0]': USERNAME,
    }

    import requests
    rs = requests.get('http://newlms.magtu.ru/webservice/rest/server.php',
                      params=params)
    print(rs)

    json_data = rs.json()
    print('Response: {}'.format(json_data))

    if 'errorcode' in json_data:
        print(json_data['errorcode'])
        quit()
r = requests.post(ALF_MERGE_URL, json=merge_payload, auth=admin_basic_auth)

pre_upload = r.json()

print('POST ' + ALF_MERGE_URL)
print(r.status_code)
print(json.dumps(pre_upload, indent=2))
print()

# Simulate SBSYS POSTing of the pre-uploaded document

success = False
while not success:
    input('Press enter to upload...')

    payload = {
        'preUploadId': pre_upload.get('preUploadId'),
        'token': {
            'token': get_token()
        }
    }

    r = requests.post(ALF_UPLOAD_URL, json=payload, auth=admin_basic_auth)

    print('POST ' + ALF_UPLOAD_URL)
    print(r.json())
    print(r.status_code)

    if r.status_code == 200:
        success = True
示例#28
0
'''
Author: Sheetanshu Shekhar
Purpose: Main Python program to import modules and interact with
Cisco DevNet Sandbox
'''
from get_token import get_token
from get_devices_list import get_devices_list, get_devices_mgmt_ip
import json

username = input(" Username : "******" Password : ")
#Use the Password and Username to get token
token = get_token(username, password)
#Use the generated token to print the devices_list
get_devices_mgmt_ip(get_devices_list(token))
示例#29
0
 def get_token(self):   
     self.token = get_token.get_token()
示例#30
0
from pprint import pprint

import requests
from get_token import get_token
import json

cookies = get_token()
url = "https://sbx-nxos-mgmt.cisco.com/api/node/mo/sys/intf/phys-[eth1/34].json?"

payload = {"l1PhysIf": {"attributes": {"descr": ""}}}
headers = {}

response = requests.put(url,
                        headers=headers,
                        data=json.dumps(payload),
                        cookies=cookies,
                        verify=False).json()
pprint(response)
示例#31
0
import sqlalchemy
import json
import requests
import db
import time
import urllib

from db import Task, Association
from get_token import get_token

TOKEN = get_token()
URL = "https://api.telegram.org/bot{}/".format(TOKEN)


def get_url(url):
    response = requests.get(url)
    content = response.content.decode("utf8")
    return content


def get_json_from_url(url):
    content = get_url(url)
    js = json.loads(content)
    return js


def get_updates(offset=None):
    url = URL + "getUpdates?timeout=100"
    if offset:
        url += "&offset={}".format(offset)
示例#32
0
import requests
import json
from get_token import get_token

token = get_token()
# headers
headers = {"Authorization": f"Bearer {token}"}


def hotels(cityCode):
    lst = []
    url = f'https://test.api.amadeus.com/v2/shopping/hotel-offers?cityCode={cityCode}&roomQuantity=1&adults=2&radius=50&radiusUnit=KM&paymentPolicy=NONE&includeClosed=false&view=FULL&sort=NONE'
    # url1 = f'https://test.api.amadeus.com/v2/shopping/hotel-offers?adults=2&cityCode={cityCode}&includeClosed=false&paymentPolicy=NONE&radius=20&radiusUnit=KM&roomQuantity=1&sort=NONE&view=FULL&page[offset]=95EWTRHOTCN3_100'
    # url2 = f'https://test.api.amadeus.com/v2/shopping/hotel-offers?adults=2&cityCode={cityCode}&includeClosed=false&paymentPolicy=NONE&radius=20&radiusUnit=KM&roomQuantity=1&sort=NONE&view=FULL&page[offset]=95EWTRHOTCN3_200'

    response = requests.get(url, headers=headers).json()
    print(json.dumps(response, indent=2))
    # print(len(response['data']))

    # response = requests.get(url1, headers=headers).json()
    # print(json.dumps(response, indent=2))

    # response = requests.get(url2, headers=headers).json()
    # print(json.dumps(response, indent=2))
    if "meta" in response.keys():
        while True:
            # print(json.dumps(response, indent=2))
            url = response['meta']['links']['next']
            response = requests.get(url, headers=headers).json()
            # print(len(response['data']))
            print(json.dumps(response, indent=2))
示例#33
0
文件: main.py 项目: xcipi/skpcve
get CVE database from Cisco API Oauth2 

"""

import requests
import json
from pprint import pprint
import get_token
import get_csas
import yaml

print 'Parsing configs ...'
with open("config.yaml", 'r') as yamlfile:
    cfg = yaml.load(yamlfile)

for section in cfg:
    clientId = cfg['CiscoCreds']['clientId']
    clientSecret = cfg['CiscoCreds']['clientSecret']
print 'done ...'

#clientID = 'zetgk3mrfy58nwvbe239tqtr'
#clientSecret = 'JkSydPCAnS28M82dKXG94RfY'

ciscoToken = get_token.get_token(clientId, clientSecret)

#print clientId
#print clientSecret

print 'Getting CSAs ...'
get_csas.get_csas(ciscoToken, 'LATEST', '5')
print 'done getting CSAs ...'