Example #1
0
    def _send_tracking_requests(self):
        session = requests.Session()
        while True:
            params = self.queue.get()

            try:
                session.post(self.matomo_url, params=params[0])
                session.post(self.matomo_url, params=params[1])
            except Exception as ex:
                LOG.error("Error sending metrics request: " + str(ex))

            self.queue.task_done()
    def confirmReason(self, env: int, user: str, status: int) -> None:
        '''
        param1: env
        param2: account
        param3: status, 1: pass, 2: deny
        return: None
        '''
        session = requests.Session()

        url = f'{admin_url}/admin/Opterators/index?parma=sv2'

        # global admin_header not allow here
        header = {
            'Cookie': f"ANVOAID={cookies['ANVOAID']}",
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        header['User-Agent'] = admin_header['User-Agent']

        fundid_dict = self.selectFundid(env, user)
        for key in fundid_dict.keys():
            fund_id = fundid_dict[key][0]
            fund_type = fundid_dict[key][1]

            data = f'id={fund_id}&status={status}&typeId={fund_type}'

            res = session.post(url, data=data, headers=header)

            if res.json()['status'] == 'ok':
                print(f'{user}: reason {fund_type} confirm successfully!!')
            else:
                print(f'{user} fail to confirm reason')

        return None
Example #3
0
def login(username,password):
    header={
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
        "Content-Type": "application/json;charset=UTF-8",
        "Content-Length": "2",
        "Host": "gw.wozaixiaoyuan.com",
        "Accept-Language": "en-us,en",
        "Accept": "application/json, text/plain, */*"
    }
    loginUrl="https://gw.wozaixiaoyuan.com/basicinfo/mobile/login/username"
    data="{}"
    session=requests.session()
    url=loginUrl+"?username="******"&password="******"code"] == 0:
        print("登陆成功")
        jwsession = resp.headers['JWSESSION']
        return jwsession
    else:
        print(res)
        print("登录失败,请检查账号信息")
        status_code = 5
        return False
Example #4
0
    def get_certificate_using_session(self,
                                      session,
                                      server_url,
                                      pem_out_filepath=None):
        '''Obtain a create a new key pair and invoke the SLCS service to obtain
        a certificate using authentication method determined by input session
        object: the latter can be username/password using HTTPBasicAuth object
        or OAuth 2.0 access token with OAuth2Session

        :param session: Requests session containing the authentication context:
        either a session with a HTTBasicAuth object as its auth attribute or a
        requests_oauthlib.OAuth2Session
        :param server_url: URL for get certificate endpoint
        :param pem_out_filepath: optionally set output path for file containing
        concatenated private key and certificate issued
        :return: tuple of key pair object and certificate
        '''
        if not isinstance(session, requests.Session):
            raise TypeError('Expecting requests.Session or '
                            'oauthlib_requests.OAuth2Session type for session '
                            'object')

        key_pair = self.__class__.create_key_pair()
        cert_req = self.__class__.create_cert_req(key_pair)

        req = {self.__class__.CERT_REQ_POST_PARAM_KEYNAME: cert_req}

        res = session.post(server_url, data=req, verify=self.ca_cert_dir)
        if not res.ok:
            raise OnlineCaClientErrorResponse(
                'Error getting certificate'
                ': status: {} {}'.format(res.status_code, res.reason), res)

        # Response contains PEM-encoded certificate just issued + any additional
        # CA certificates in the chain of trust configured on the server-side.
        # Parse into OpenSSL.crypto.X509 objects
        cert_s = res.content.decode(encoding='utf-8')
        cert_list = []
        for pem_cert_frag in cert_s.split('-----BEGIN CERTIFICATE-----')[1:]:
            pem_cert = '-----BEGIN CERTIFICATE-----' + pem_cert_frag
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_cert)
            cert_list.append(cert)

        cert = crypto.load_certificate(crypto.FILETYPE_PEM, res.content)

        # Optionally output the private key and certificate together PEM
        # encoded in a single file
        if pem_out_filepath:
            pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair)
            pem_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

            with open(pem_out_filepath, 'wb', 0o400) as pem_out_file:
                pem_out_file.write(res.content)
                pem_out_file.write(pem_pkey)

        return key_pair, (cert, ) + tuple(cert_list)
Example #5
0
def login():
    global session
    values = {
    'username': os.environ.get('ROUTER_CONFIG_USER'),  # encode MD5
    'password': os.environ.get('ROUTER_CONFIG_PWD'),
    'sessionKey': random.random()
    }
    session = requests.Session()
    print('Connecting to', root_url, '...')
    r = session.post(login_url, data=values, timeout=5)
    if r.content == b'<script>location="/login.html?0"</script>':
        return -1
Example #6
0
def addroom():
    session = ll(18802094078, 'qq111111', 86)
    data = {
        'room': '哇哈哈',
        'hotel': '371',
        'name': '11',
        'price': '11',
        'charityPrice': '1'
    }
    addroomurl = 'https://www.meizhuyun.com/Home/Room/addRoom'
    resp = session.post(addroomurl, data)
    print(resp.content.decode('utf-8'))
Example #7
0
    def poc(self, target_url, domain, session):
        url = f'{target_url}/casa/nodes/thumbprints'
        headers = {'Content-Type': 'application/json;charset=UTF-8'}
        data = f'["{domain}"]'
        try:
            res = session.post(url=url,
                               headers=headers,
                               data=data,
                               verify=False,
                               timeout=20)

            return res.status_code
        except Exception as e:
            print("\033[31m[x] 请求失败 \033[0m", e)
Example #8
0
async def sauce(ctx, arg):
    provided_image = arg
    req_obj = {"url": provided_image}
    url = "https://saucenao.com/search.php"
    req = session.post(url, req_obj)
    error_message = "Specified file does not seem to be an image..."
    supplied_image_error = "Supplied URL is not usable..."
    dimension_image_error = "image dimensions too small..."
    check_for_error = req.html.find("body", first=True).text
    # this is hilarious and a switch statement would probably be more readable :^)
    if error_message == check_for_error:
        return await ctx.send("This isn't an image...")
    elif supplied_image_error == check_for_error:
        return await ctx.send("This isn't an image...")
    elif dimension_image_error == check_for_error:
        return await ctx.send("Image too small...")
    else:
        if req.html.find(".servererror", first=True):
            return await ctx.send("Something went wrong...")
        most_similar_image = req.html.find("#resImage0", first=True).attrs
        most_similar_title = req.html.find(".resulttitle", first=True).text
        most_similar_links = req.html.find(
            ".resultcontentcolumn", first=True
        ).absolute_links
        most_similar_text = req.html.find(".resultcontentcolumn", first=True).text
        if most_similar_links is not None:
            await ctx.send(
                "**{}**, \n {}".format(most_similar_title, most_similar_text)
            )
            filtered_links = [
                x
                for x in list(most_similar_links)
                if "?lookup_type=0" not in x and "?lookup_type=1" not in x
            ]
            await ctx.send("**Most Relevant Artist & Post**")
            for x in filtered_links[:]:
                await ctx.send("{}".format(x))
        else:
            await ctx.send("Something went wrong when getting the Artist.")
        if most_similar_image is not None:
            if "images/static/blocked.gif" in most_similar_image.get("src"):
                return
            await ctx.send(
                "**Most Relevant Image**\n{}\n".format(most_similar_image.get("src"))
            )
        else:
            return await ctx.send(
                "Something went wrong when getting the supplied image."
            )
    def adminLogin(self, env: int) -> None:
        '''
        param: env, 0: dev02, 1: 188
        return: None (get admin header and cookies)
        '''
        global admin_header, admin_url
        global cookies

        admin_dict = {
            0: 'http://admin.dev02.com',
            1: 'http://admin.joy188.com'
        }

        admin_url = admin_dict[env]
        url = f'{admin_url}/admin/login/login'

        admin_header = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.100 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        password = '******' if env == 0 else 'amberrd'
        admin_data = {
            'username': '******',
            'password': password,
            'bindpwd': 123456
        }

        # sent Request to Admin backplatform
        session = requests.Session()
        res = session.post(url, data=admin_data, headers=admin_header)

        # Maybe needs JSON decode ? (two lines below)
        decoded_data = res.text.encode().decode('utf-8-sig')
        data = json.loads(decoded_data)

        if data['isSuccess'] == 1:
            print(f'Success to Login Admin: {admin_dict[env]}')
        else:
            print(f'Fail to Login Admin: {admin_dict[env]}')

        # get cookies and add to admin header
        cookies = res.cookies.get_dict()
        admin_header['ANVOAID'] = cookies['ANVOAID']

        return None
Example #10
0
def Auto():
    jwsession=login(username,password)
    url = "https://student.wozaixiaoyuan.com/health/save.json"
    header={
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": "2",
        "Host": "student.wozaixiaoyuan.com",
        "Accept-Language": "en-us,en",
        "Accept": "application/json, text/plain, */*",
        "JWSESSION":str(jwsession)
    }
    data = {
        'answers': '["0","36.5","36.5","36.5"]',
        'latitude': '30.205023',
        'longitude': '115.018481',
        'country': '中国',
        'city': '黄石市',
        'district': '下陆区',
        'province': '湖北省',
        'township': '团城山街道',
        'street': '磁湖路',
        'areacode': '420204'
    }
    session = requests.session()
    response =session.post(url=url, data=data, headers=header)
    response = json.loads(response.text)
    if response['code'] == -10:
        print('jwsession 无效,将尝试使用账号信息重新登录')
        status_code = 4
        loginStatus =login()
    elif response["code"] == 0:
        print("打卡成功")
    elif response['code'] == 1: 
        print("打卡失败:今日健康打卡已结束")   
    else:
        print(response)
        print("打卡失败")
def uploadImages(directory):
    api_addr = 'https://sm.ms/api/v2'
    upload_api = '/upload'
    url = api_addr + upload_api
    headers = {'Authorization': '5NUSX0M5dr3ewDHK5x8cqpfCCMHfB6e4'}
    session = requests.Session()

    # In windows, directory should be in raw text, r'C:\Users\xq127\Pictures\temp'
    for dirpath, dirnames, filenames in os.walk(directory):
        urlStoredFileName = time.strftime("%Y%m%d%H%M%S",
                                          time.localtime()) + '.txt'
        urlStoredFilePath = Path(dirpath) / urlStoredFileName

        for file in filenames:
            # upload image file
            file = Path(dirpath) / file
            files = {'smfile': open(file, 'rb')}
            # resp = session.post(
            #     url, files=files, headers=headers, verify=False).json()

            resp = session.post(url,
                                files=files,
                                headers=headers,
                                verify=False).json()
            # print(json.dumps(resp, indent=4))

            # get image url
            code = resp.get('code')
            print(code)
            if code == 'image_repeated':
                imageUrl = resp.get("images")
            elif code == 'success':
                imageUrl = resp["data"]["url"]
            else:
                raise ValueError("API Error")
            print(imageUrl)

            with open(urlStoredFilePath, 'a') as fh:
                fh.write(imageUrl)
                fh.write('\n')
    def addRsason(self, env: int, user: str, fund_type: int,
                  cost: float) -> None:
        '''
        param1: env
        param2: account
        param3: fund_type refer to 後台-資金-新建人工單
        param4: number of amount changing(inculde increase and decrease)
        return: None
        '''
        userid = self.selectUserid(env, user)
        url = f'{admin_url}/admin/Opterators/index?parma=opter1'

        # global admin_header not allow here
        header = {
            'Cookie': f"ANVOAID={cookies['ANVOAID']}",
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        header['User-Agent'] = admin_header['User-Agent']

        data = f'rcvAct={user}&depositAmt={cost}&memo=test&id=&userId={userid}&sSelectValue={fund_type}&note=test&chargeSn='

        session = requests.Session()

        if fund_type in [10, 12, 13]:  # reasons about pt
            print('pt is producted, dont use it!!')
            pass
        elif fund_type in [32, 33, 34]:  # reasons about ag
            print('ag is producted, dont use it!!')
            pass
        else:
            res = session.post(url, data=data, headers=header)

            if res.json()['status'] == 'ok':
                print(f'{user}: reason {fund_type} build successfully!!')
            else:
                print(f'{user} fail to build reason')

        return None
Example #13
0
def login_cheapss(order):
    # 從All_account獲取帳號
    user = cheapss()[0]
    password = cheapss()[1]

    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }

    payload = {
        'referer': 'https://cheapsslsecurity.com/quicklogin.html?isauth=false&ReturnUrl=%2fclient%2fordersummary.html',
        '__VIEWSTATE': '/wEPDwUKMTY0Nzg0NzU0N2RkcweFlpgG3cvff6LrQyzoJkQhxetcYszKQQlHepcyA3c=',
        'ctl00$RapidSSLContent$txtUsername': user,
        'ctl00$RapidSSLContent$txtPassword': password,
        'ctl00$RapidSSLContent$btnLogin': '******',
        '__VIEWSTATEGENERATOR': '5F89FC59',
        '__EVENTVALIDATION': '/wEdAAQjkL3jJcqYFrkHnvBRdsxAcO1dB7UA/''GyDQStrVSOCjHfNGizx3lC8jGKGqxi1PhAlY6eIPpktbY3NBsQ56uSJzyNWoPoZW2Kb0YAmoEVdDHE07pO3YOp2SYd5w0n6Nxk=',
    }

    try:
        # 登入的URL
        login_url = "https://cheapsslsecurity.com/quicklogin.aspx?isauth=false&ReturnUrl=%2fclient%2fordersummary.html"

        # 使用session函數可保留登入後訊息(cookies之類)
        session = requests.session()
        r = session.post(login_url, headers=header, data=payload,
                         timeout=120)  # 獲取網頁120秒為限
        r.raise_for_status()  # 如果狀態不是200引發HTTPERROR異常
        r.encoding = r.apparent_encoding  # 用預測的解碼 EX:UTF-8

        # 下載鏈接(order會根據證書不同變換)
        file_url = "https://cheapsslsecurity.com/client/orderdtl.html?orderdetailid=" + \
            order+"&isdownload=true"
        file = session.get(file_url, timeout=120)  # 獲取網頁120秒為限
    except error as e:
        print(e, '請確認帳號或連線是否正常')
    # 返回get到的下載鏈接
    return file
Example #14
0
    def test_request_response(self):
        url = 'http://localhost:{port}/users'.format(
            port=self.mock_server_port)

        # Implement retry mechanism
        session = requests.Session()
        retry_strategy = Retry(total=5,
                               backoff_factor=1,
                               status_forcelist=[400],
                               method_whitelist=['POST'])

        adapter = HTTPAdapter(max_retries=retry_strategy)
        session.mount("http://", adapter)
        session.mount("https://", adapter)
        response = session.post(url=url)

        # Normal version
        # Send a request to the mock API server and store the response.
        response = requests.get(url)

        # Confirm that the request-response cycle completed successfully.
        print(f"response: {response}")
        assert_true(response.ok)
Example #15
0
 "Accept-Language": "ko,en-US;q=0.9,en;q=0.8",
 "Cache-Control": "max-age=0",
 "Connection": "keep-alive",
 "Content-Length": "588",
 "Content-Type": "application/x-www-form-urlencoded",
 "Cookie": "WMONID=sZViNtz61vJ; JSESSIONID=azzAwqA4v7da7ZMpTUZnakIKXdDPn29laeGqE1vQbqNm6y21VEyVYZmAFVUXaumC.b3BpbmV0X2RvbWFpbi9vcGluZXQxLTE=; NetFunnel_ID=5002%3A200%3Akey%3DCD1FA963BDBA67F749822E2E1FD568A12B59DE7CB9456AA675AEC1FBDA3CE9F3591E3E543E076439F9E9A56E2B079EE39512A42EF93688E05898BEAEA5132364D81C7703A9CB6C9C3EC52EC3E7349681C05C4FB4A117B63488D854A91AD6BDF1AD0F18A36EF9F31178B8EEAEA42BD451%26nwait%3D0%26nnext%3D0%26tps%3D0%26ttl%3D0%26ip%3Dnfl.opinet.co.kr%26port%3D443",
 "Host": "www.opinet.co.kr",
 "Origin": "https://www.opinet.co.kr",
 "Referer": "https://www.opinet.co.kr/searRgSelect.do",
 "Sec-Fetch-Dest": "document",
 "Sec-Fetch-Mode": "navigate",
 "Sec-Fetch-Site": "same-origin",
 "Sec-Fetch-User": "******",
 "Upgrade-Insecure-Requests": "1",
 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
 response=session.post(URL,data=data,headers=headers)
 html = response.text
 soup = BeautifulSoup(html,'html.parser')
 li_list = soup.select('tbody tr')
 for li in li_list:
     #dateq =li.find("a")["href"]
     try:
         dateq =li.select_one("a").attrs["href"]
         dateqset=re.findall(r"'.*?'",dateq)
         sector = i
         price = int(dateqset[2].strip("''"))
         if dateqset[22] == "'SKE'":
             name = dateqset[23].strip("''")
             brand = dateqset[22].strip("''")
         else:
             name = dateqset[22].strip("''")
Example #16
0
def ll(mobile, password, areaCode):
    data = {'mobile': mobile, 'password': password, 'areaCode': areaCode}
    login_url = "https://www.meizhuyun.com/Home/Public/login"
    session = requests.Session()
    session.post(login_url, data)
    return session
Example #17
0
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:54.0) Gecko/20100101 Firefox/54.0',
    'X-Requested-With': "XMLHttpRequest",
    'Accept-Encoding': "gzip, deflate, br",
    # 'Cookie': random.choice(cookies)
}
# proxyMeta = "http://*****:*****@proxy.abuyun.com:9020"
# self.proxies = {
# 	"http": proxyMeta,
# 	"https": proxyMeta,
# }
session = session()
# session.cookies = cookielib.LWPCookieJar(filename="cookies.txt")
# try:
#     session.cookies.load(ignore_discard=True)
# except:
# 	print ("cookie未能加载")

form_data = {
    'companyId': 188673,
    'pageNo': 1,
    'pageSize': 10,
    'positionFirstType': '全部',
}
url = 'https://www.lagou.com/gongsi/searchPosition.json'
res = session.post(url, headers=headers, data=form_data)
with open('text.json', 'w') as f:
    f.write(res.text)
# session.cookies.save()

print(res.cookies)