Exemplo n.º 1
0
def linkedin():
        global opener
        cookie_filename = "cookies.txt"

        # Simulate browser with cookies enabled
        cj = cookielib.MozillaCookieJar(cookie_filename)
        if os.access(cookie_filename, os.F_OK):
            cj.load()

        # Load Proxy settings
        if len(config['proxylist']) > 0:
            proxy_handler = urllib2.ProxyHandler(
                {'https': config['proxylist'][0]})

            opener = urllib2.build_opener(
                proxy_handler,
                urllib2.HTTPRedirectHandler(),
                urllib2.HTTPHandler(debuglevel=0),
                urllib2.HTTPSHandler(debuglevel=0),
                urllib2.HTTPCookieProcessor(cj)
            )
        else:
            opener = urllib2.build_opener(
                urllib2.HTTPRedirectHandler(),
                urllib2.HTTPHandler(debuglevel=0),
                urllib2.HTTPSHandler(debuglevel=0),
                urllib2.HTTPCookieProcessor(cj)
            )

        user_agent = config['cookie']['User-Agent']

        opener.addheaders = [('User-Agent', user_agent)]

        # Get CSRF Token
        html = load_page("https://www.linkedin.com/")
        soup = BeautifulSoup(html, "html.parser")
        csrf = soup.find(id="loginCsrfParam-login")['value']

        # Authenticate
        login_data = urllib.urlencode({
            'session_key': config['username'],
            'session_password': config['password'],
            'loginCsrfParam': csrf,
        })

        html = load_page("https://www.linkedin.com/uas/login-submit", login_data)
        soup = BeautifulSoup(html, "html.parser")

        try:
            print(cj._cookies['.www.linkedin.com']['/']['li_at'].value)

        except Exception:
            print("error")

        cj.save()
        os.remove(cookie_filename)
Exemplo n.º 2
0
def auth(email, password, client_id, scope):
    def split_key_value(kv_pair):
        kv = kv_pair.split("=")
        return kv[0], kv[1]

    # Authorization form
    def auth_user(email, password, client_id, scope, opener):

        response = opener.open(
            'http://oauth.vk.com/oauth/authorize?' +
            'redirect_uri=http://oauth.vk.com/blank.html&response_type=token&' +
            'client_id=%s&scope=%s&display=wap' % (client_id, ",".join(scope))
        )
        html_dock = response.read().decode("utf-8")
        parser = FormParser()
        parser.feed(html_dock)
        parser.close()
        if not parser.form_parsed or parser.url is None or "pass" not in parser.params or "email" not in parser.params:
            raise RuntimeError("Something wrong")
        parser.params["email"] = email
        parser.params["pass"] = password
        if parser.method == "POST":
            response = opener.open(parser.url, urllib.parse.urlencode(parser.params).encode())
        else:
            raise NotImplementedError("Method '%s'" % parser.method)
        return response.read(), response.geturl()

    # Permission request form
    def give_access(html_dock, browser):
        parser = FormParser()
        parser.feed(html_dock.decode("utf-8"))
        parser.close()
        if not parser.form_parsed or parser.url is None:
            raise RuntimeError("Something wrong")
        if parser.method == "POST":
            response = browser.open(parser.url, urllib.parse.urlencode(parser.params).encode())
        else:
            raise NotImplementedError("Method '%s'" % parser.method)
        return response.geturl()

    if not isinstance(scope, list):
        scope = [scope]
    opener = request.build_opener(
        request.HTTPCookieProcessor(cooki.CookieJar()),
        request.HTTPRedirectHandler())
    doc, url = auth_user(email, password, client_id, scope, opener)
    if urlparse(url).path != "/blank.html":
        # Need to give access to requested scope
        url = give_access(doc, opener)
    if urlparse(url).path != "/blank.html":
        raise RuntimeError("Expected success here")
    answer = dict(split_key_value(kv_pair) for kv_pair in urlparse(url).fragment.split("&"))
    if "access_token" not in answer or "user_id" not in answer:
        raise RuntimeError("Missing some values in answer")
    return answer["access_token"], answer["user_id"]
Exemplo n.º 3
0
    def __init__(self, login, password):
        self.login = login
        self.password = password

        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPRedirectHandler(), urllib2.HTTPHandler(debuglevel=0),
            urllib2.HTTPSHandler(debuglevel=0),
            urllib2.HTTPCookieProcessor(self.cj))
        user_agent = (
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"
        )
        self.opener.addheaders = [('User-agent', user_agent)]

        self.loginToLearn()
Exemplo n.º 4
0
    def __init__(self, user_agent, username, password):
        self.cj = get_persistent_cookiejar()

        # Older articles in Wiley's Online Library hit the default limit of 10
        # redirections.
        rh = request.HTTPRedirectHandler()
        rh.max_redirections = 20
        self.opener = request.build_opener(rh, request.HTTPCookieProcessor(self.cj))
        self.opener.addheaders = [('User-Agent', user_agent)]
        ###self.opener.process_request['http'][0].set_http_debuglevel(1)
        ###self.opener.process_request['https'][0].set_http_debuglevel(1)

        self.inputs = list(self.default_inputs)
        self.inputs.append(('username', username))
        self.inputs.append(('password', password))
Exemplo n.º 5
0
def get_need_dates(username, password):
    app_id = 7561984
    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(cookielib.CookieJar()),
        urllib2.HTTPRedirectHandler())
    html, url = auth_user(email=username,
                          password=password,
                          app_id=app_id,
                          scope=['friends', 'account'],
                          opener=opener)
    if urlparse(url).path != "/blank.html":
        url = give_access(html, opener)
    token = urlparse(url).fragment.split("&")[0].split("=")[1]
    id = urlparse(url).fragment.split("&")[2].split("=")[1]
    return id, token
Exemplo n.º 6
0
def get_stock_html(ticker_name):
    opener = urllib.build_opener(
        urllib.HTTPRedirectHandler(),
        urllib.HTTPHandler(debuglevel=0),
    )
  
    opener.addheaders = [
        ('User-agent',
        "Mozilla/4.0 (compatible; MSIE 7.0; "
        "Windows NT 5.1; .NET CLR 2.0.50727; "
        ".NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")
    ]

    url = "http://finance.yahoo.com/q?s=" + ticker_name
    response = opener.open(url)
    return b''.join(response.readlines())
Exemplo n.º 7
0
def login():
    cookie_filename = 'cookies.txt'

    cookie_jar = cookiejar.MozillaCookieJar(cookie_filename)

    opener = request.build_opener(request.HTTPRedirectHandler(),
                                  request.HTTPHandler(debuglevel=0),
                                  request.HTTPSHandler(debuglevel=0),
                                  request.HTTPCookieProcessor(cookie_jar))
    print("login1")
    html = load_page(opener, 'https://www.linkedin.com/checkpoint/lg/login')
    soup = BeautifulSoup(html, 'html.parser')

    print("login2")

    csrf = soup.find('input', {'name': 'csrfToken'}).get('value')
    loginCsrfParam = soup.find('input', {
        'name': 'loginCsrfParam'
    }).get('value')

    login_data = parse.urlencode({
        'session_key': config.USERNAME,
        'session_password': config.PASSWORD,
        'csrfToken': csrf,
        'loginCsrfParam': loginCsrfParam
    })

    load_page(opener, 'https://www.linkedin.com/checkpoint/lg/login-submit',
              login_data)

    try:
        cookie = cookie_jar._cookies['.www.linkedin.com']['/']['li_at'].value
        jsessionid = ''
        for ck in cookie_jar:
            # print cookie.name, cookie.value, cookie.domain
            if ck.name == 'JSESSIONID':
                jsessionid = ck.value
    except Exception as e:
        print(e)
        sys.exit(0)

    cookie_jar.save()
    os.remove(cookie_filename)

    return cookie, csrf
Exemplo n.º 8
0
def post_junk(index, to_feed):
    url = "https://progbase.herokuapp.com/profile/update"
    params = {
        'method': 'POST',
        'text': random.choice(to_feed['text']),
        'email': random.choice(to_feed['email']),
        'number': random.choice(to_feed['number'])
    }
    data_to_post = urllib.urlencode(params)
    binary_data_to_post = data_to_post.encode('utf-8')
    print('{0}) Starting to get a response...'.format(index + 1))

    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(cookielib.CookieJar()),
        urllib2.HTTPRedirectHandler())
    response = opener.open(url, binary_data_to_post)
    print("Done!")
    return response
Exemplo n.º 9
0
 def getRandomMUID(self):
     opener = urllib.build_opener(urllib.HTTPErrorProcessor(),
                                  urllib.HTTPRedirectHandler(),
                                  urllib.HTTPHandler())
     request = urllib.Request(
         "http://gatherer.wizards.com/Pages/Card/Details.aspx?action=random"
     )
     c = 0
     while 1:
         try:
             response = opener.open(request)
         except Exception as e:
             i = int(e.__dict__['url'].split('=')[1])
             if i not in self.__used_muids__:
                 yield i
             elif (c > 100):  # this means at least 99.9% completion.
                 raise StopIteration()
             else:
                 c += 1
Exemplo n.º 10
0
def make_request(
    url: str,
    method: typing.Optional[str] = 'GET'
) -> typing.Tuple[request.OpenerDirector, request.Request]:
    """
    Creates a request and an opener to run it
    :param url: Initial URL for request
    :param method: HTTP Method for request
    :return: tuple containing the OpenerDirector instance and the Request object
    """
    rdh = request.HTTPRedirectHandler()
    rdh.max_repeats = 999
    rdh.max_redirections = 999

    cj = CookieJar()
    cjh = request.HTTPCookieProcessor(cj)

    opener = request.build_opener(rdh, cjh)

    return opener, request.Request(url, method=method)
Exemplo n.º 11
0
    def auth(self, app_id, scope, login, password):
        opener = request.build_opener(
            request.HTTPCookieProcessor(cookiejar.CookieJar()),
            request.HTTPRedirectHandler())

        try:
            response_auth = opener.open(
                "https://oauth.vk.com/authorize?client_id={}"
                "&display=page&redirect_uri=https://oauth.vk.com/blank.htm&scope={}"
                "&response_type=token&v={}".format(app_id, scope, self.v_api))
        except error.HTTPError:
            raise VKAuthError("Don't auth, may be wrong app id")

        parser = AuthFormParser()
        parser.feed(str(response_auth.read()))
        parser.close()

        parser.params['email'] = login
        parser.params['pass'] = password

        response_allow = opener.open(
            parser.url,
            parse.urlencode(parser.params).encode('utf8'))
        url_parse = parse.urlparse(response_allow.geturl())

        if url_parse.path != '/blank.html':
            query = parse.parse_qs(url_parse.query)
            if 'email' in query:
                raise VKAuthError("Wrong login or pass")
            action_allow = re.findall(
                r'(?<=<form\smethod=\"post\"\saction=\").*(?=\")',
                response_allow.read().decode("utf-8"))[0]
            response_allow = opener.open(action_allow)
            url_parse = parse.urlparse(response_allow.geturl())

        query_params = dict(
            (k, v) for k, v in (item.split('=')
                                for item in url_parse.fragment.split('&')))
        self.token = query_params['access_token']
        self.expires_in = query_params['expires_in']
        self.user_id = query_params['user_id']
Exemplo n.º 12
0
def build_token(scope=[], state='default', mail='123', password='******'):
    url = '&'.join(
        ('https://oauth.vk.com/authorize?client_id=5521254', 'display=page',
         'redirect_uri=https://oauth.vk.com/blank.html',
         'scope=%s' % ','.join(scope), 'response_type=token', 'v=5.53',
         'state=%s' % state), )
    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(cookielib.CookieJar()),
        urllib2.HTTPRedirectHandler())
    response = opener.open(url)
    vkform_parser = FormParser()
    vkform_parser.feed(response.read().decode("utf-8"))
    vkform_parser.params["email"] = mail
    vkform_parser.params["pass"] = password
    data_to_post = urllib.urlencode(vkform_parser.params)
    binary_data_to_post = data_to_post.encode('utf-8')
    print('Starting to get a response...')
    response = opener.open(vkform_parser.url, binary_data_to_post)
    print('Got the token!')
    vk_token = re.search(r'(.*)access_token=(.*)&expires_in(.*)', response.url)
    return vk_token.group(2)
Exemplo n.º 13
0
    def __init__(self, login, password):
        """ Start up... """
        self.login = login
        self.password = password

        self.cj = cookiejar.CookieJar()
        self.opener = request.build_opener(
            request.HTTPRedirectHandler(), request.HTTPHandler(debuglevel=0),
            request.HTTPSHandler(debuglevel=0),
            request.HTTPCookieProcessor(self.cj))

        # Auth
        # print(('%s:%s' % (login, password)).encode("utf-8"))
        base64string = base64.b64encode(
            ('%s:%s' % (login, password)).encode("utf-8"))
        auth_str = str(base64string)[2:-1]
        # print(auth_str)

        self.opener.addheaders = [('User-agent',
                                   ('Mozilla/4.0 (compatible; MSIE 6.0; '
                                    'Windows NT 5.2; .NET CLR 1.1.4322)')),
                                  ("Authorization", "Basic %s" % auth_str)]
Exemplo n.º 14
0
    def _request(self, url, data=None, method=None):
        """
        Send an HTTP request to the remote server.

        :Args:
         - method - A string for the HTTP method to send the request with.
         - url - The URL to send the request to.
         - body - The message body to send.

        :Returns:
          A dictionary with the server's parsed JSON response.
        """
        LOGGER.debug('%s %s %s' % (method, url, data))

        parsed_url = parse.urlparse(url)

        if self.keep_alive:
            headers = {
                "Connection": 'keep-alive',
                method: parsed_url.path,
                "User-Agent": "Python http auth",
                "Content-type": "application/json;charset=\"UTF-8\"",
                "Accept": "application/json"
            }
            if parsed_url.username:
                auth = base64.standard_b64encode(
                    '%s:%s' %
                    (parsed_url.username, parsed_url.password)).replace(
                        '\n', '')
                headers["Authorization"] = "Basic %s" % auth
            self._conn.request(method, parsed_url.path, data, headers)
            resp = self._conn.getresponse()
            statuscode = resp.status
        else:
            password_manager = None
            if parsed_url.username:
                netloc = parsed_url.hostname
                if parsed_url.port:
                    netloc += ":%s" % parsed_url.port
                cleaned_url = parse.urlunparse(
                    (parsed_url.scheme, netloc, parsed_url.path,
                     parsed_url.params, parsed_url.query, parsed_url.fragment))
                password_manager = url_request.HTTPPasswordMgrWithDefaultRealm(
                )
                password_manager.add_password(
                    None, "%s://%s" % (parsed_url.scheme, netloc),
                    parsed_url.username, parsed_url.password)
                request = Request(cleaned_url,
                                  data=data.encode('utf-8'),
                                  method=method)
            else:
                request = Request(url,
                                  data=data.encode('utf-8'),
                                  method=method)

            request.add_header('Accept', 'application/json')
            request.add_header('Content-Type',
                               'application/json;charset=UTF-8')

            if password_manager:
                opener = url_request.build_opener(
                    url_request.HTTPRedirectHandler(), HttpErrorHandler(),
                    url_request.HTTPBasicAuthHandler(password_manager))
            else:
                opener = url_request.build_opener(
                    url_request.HTTPRedirectHandler(), HttpErrorHandler())
            resp = opener.open(request)
            statuscode = resp.code
            if not hasattr(resp, 'getheader'):
                if hasattr(resp.headers, 'getheader'):
                    resp.getheader = lambda x: resp.headers.getheader(x)
                elif hasattr(resp.headers, 'get'):
                    resp.getheader = lambda x: resp.headers.get(x)

        data = resp.read()
        try:
            if 399 < statuscode < 500:
                return {'status': statuscode, 'value': data}
            if 300 <= statuscode < 304:
                return self._request(resp.getheader('location'), method='GET')
            body = data.decode('utf-8').replace('\x00', '').strip()
            content_type = []
            if resp.getheader('Content-Type') is not None:
                content_type = resp.getheader('Content-Type').split(';')
            if not any([x.startswith('image/png') for x in content_type]):
                try:
                    data = utils.load_json(body.strip())
                except ValueError:
                    if 199 < statuscode < 300:
                        status = ErrorCode.SUCCESS
                    else:
                        status = ErrorCode.UNKNOWN_ERROR
                    return {'status': status, 'value': body.strip()}

                assert type(data) is dict, (
                    'Invalid server response body: %s' % body)
                assert 'status' in data, (
                    'Invalid server response; no status: %s' % body)
                # Some of the drivers incorrectly return a response
                # with no 'value' field when they should return null.
                if 'value' not in data:
                    data['value'] = None
                return data
            else:
                data = {'status': 0, 'value': body.strip()}
                return data
        finally:
            LOGGER.debug("Finished Request")
            resp.close()
Exemplo n.º 15
0
    def _request(self, method, url, body=None):
        """
        Send an HTTP request to the remote server.

        :Args:
         - method - A string for the HTTP method to send the request with.
         - url - A string for the URL to send the request to.
         - body - A string for request body. Ignored unless method is POST or PUT.

        :Returns:
          A dictionary with the server's parsed JSON response.
        """
        LOGGER.debug('%s %s %s' % (method, url, body))

        parsed_url = parse.urlparse(url)
        headers = self.get_remote_connection_headers(parsed_url, self.keep_alive)

        if self.keep_alive:
            if body and method != 'POST' and method != 'PUT':
                body = None
            try:
                self._conn.request(method, parsed_url.path, body, headers)
                resp = self._conn.getresponse()
            except (httplib.HTTPException, socket.error):
                self._conn.close()
                raise

            statuscode = resp.status
        else:
            password_manager = None
            if parsed_url.username:
                netloc = parsed_url.hostname
                if parsed_url.port:
                    netloc += ":%s" % parsed_url.port
                cleaned_url = parse.urlunparse((
                    parsed_url.scheme,
                    netloc,
                    parsed_url.path,
                    parsed_url.params,
                    parsed_url.query,
                    parsed_url.fragment))
                password_manager = url_request.HTTPPasswordMgrWithDefaultRealm()
                password_manager.add_password(None,
                                              "%s://%s" % (parsed_url.scheme, netloc),
                                              parsed_url.username,
                                              parsed_url.password)
                request = Request(cleaned_url, data=body.encode('utf-8'), method=method)
            else:
                request = Request(url, data=body.encode('utf-8'), method=method)

            for key, val in headers.items():
                request.add_header(key, val)

            if password_manager:
                opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                  HttpErrorHandler(),
                                                  url_request.HTTPBasicAuthHandler(password_manager),
                                                  proxy_handler)
            else:
                opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                  HttpErrorHandler(),
                                                  proxy_handler)
            resp = opener.open(request, timeout=self._timeout)
            statuscode = resp.code
            if not hasattr(resp, 'getheader'):
                if hasattr(resp.headers, 'getheader'):
                    resp.getheader = lambda x: resp.headers.getheader(x)
                elif hasattr(resp.headers, 'get'):
                    resp.getheader = lambda x: resp.headers.get(x)

        data = resp.read()
        try:
            if 300 <= statuscode < 304:
                return self._request('GET', resp.getheader('location'))
            body = data.decode('utf-8').replace('\x00', '').strip()
            if 399 < statuscode <= 500:
                return {'status': statuscode, 'value': body}
            content_type = []
            if resp.getheader('Content-Type') is not None:
                content_type = resp.getheader('Content-Type').split(';')
            if not any([x.startswith('image/png') for x in content_type]):
                try:
                    data = utils.load_json(body.strip())
                except ValueError:
                    if 199 < statuscode < 300:
                        status = ErrorCode.SUCCESS
                    else:
                        status = ErrorCode.UNKNOWN_ERROR
                    return {'status': status, 'value': body.strip()}

                assert type(data) is dict, (
                    'Invalid server response body: %s' % body)
                # Some of the drivers incorrectly return a response
                # with no 'value' field when they should return null.
                if 'value' not in data:
                    data['value'] = None
                return data
            else:
                data = {'status': 0, 'value': body.strip()}
                return data
        finally:
            LOGGER.debug("Finished Request")
            resp.close()
Exemplo n.º 16
0
    def _request(self, url, data=None, method=None):
        """
        Send an HTTP request to the remote server.

        :Args:
         - method - A string for the HTTP method to send the request with.
         - url - The URL to send the request to.
         - body - The message body to send.

        :Returns:
          A dictionary with the server's parsed JSON response.
        """
        LOGGER.debug('%s %s %s' % (method, url, data))

        parsed_url = parse.urlparse(url)
        password_manager = None
        if parsed_url.username:
            netloc = parsed_url.hostname
            if parsed_url.port:
                netloc += ":%s" % parsed_url.port
            cleaned_url = parse.urlunparse((parsed_url.scheme,
                                               netloc,
                                               parsed_url.path,
                                               parsed_url.params,
                                               parsed_url.query,
                                               parsed_url.fragment))
            password_manager = url_request.HTTPPasswordMgrWithDefaultRealm()
            password_manager.add_password(None,
                                          "%s://%s" % (parsed_url.scheme, netloc),
                                          parsed_url.username,
                                          parsed_url.password)
            request = Request(cleaned_url, data=data.encode('utf-8'), method=method)
        else:
            request = Request(url, data=data.encode('utf-8'), method=method)

        request.add_header('Accept', 'application/json')
        request.add_header('Content-Type', 'application/json;charset=UTF-8')

        if password_manager:
            opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                          HttpErrorHandler(),
                                          url_request.HTTPBasicAuthHandler(password_manager))
        else:
            opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                          HttpErrorHandler())
        response = opener.open(request)
        try:
            if response.code > 399 and response.code < 500:
                return {'status': response.code, 'value': response.read()}
            body = response.read().decode('utf-8').replace('\x00', '').strip()
            content_type = [value for name, value in response.info().items() if name.lower() == "content-type"]
            if not any([x.startswith('image/png') for x in content_type]):
                try:
                    data = utils.load_json(body.strip())
                except ValueError:
                    if response.code > 199 and response.code < 300:
                        status = ErrorCode.SUCCESS
                    else:
                        status = ErrorCode.UNKNOWN_ERROR
                    return {'status': status, 'value': body.strip()}

                assert type(data) is dict, (
                    'Invalid server response body: %s' % body)
                assert 'status' in data, (
                    'Invalid server response; no status: %s' % body)
                # Some of the drivers incorrectly return a response
                # with no 'value' field when they should return null.
                if 'value' not in data:
                    data['value'] = None
                return data
            else:
                data = {'status': 0, 'value': body.strip()}
                return data
        finally:
            response.close()
Exemplo n.º 17
0
    def _request(self, method, url, body=None):
        """Send an HTTP request to the remote server.

        :param method: A string for the HTTP method to send the request with.
        :type method: str
        :param url: A string for the URL to send the request to.
        :type url: str
        :param body: A string for request body. Ignored unless method is POST or PUT.
        :type body: str
        :returns: A dictionary with the server's parsed JSON response.
        """
        self.logger.debug('%s %s %s' % (method, url, body))
        
        for _ in range(3):
            try:
                parsed_url = parse.urlparse(url)
        
                if self.keep_alive:
                    headers = {"Connection": 'keep-alive', method: parsed_url.path,
                               "User-Agent": "Python http auth",
                               "Content-type": "application/json;charset=\"UTF-8\"",
                               "Accept": "application/json"}
                    if parsed_url.username:
                        auth = base64.standard_b64encode(('%s:%s' %
                               (parsed_url.username, parsed_url.password)).encode('ascii')).decode('ascii').replace('\n', '')
                        headers["Authorization"] = "Basic %s" % auth
                    if body and method != 'POST' and method != 'PUT':
                        body = None
                    try:
                        self._conn.request(method, parsed_url.path, body, headers)
                        resp = self._conn.getresponse()
                    except (httplib.HTTPException, socket.error):
                        self._conn.close()
                        raise
        
                    statuscode = resp.status
                else:
                    password_manager = None
                    if parsed_url.username:
                        netloc = parsed_url.hostname
                        if parsed_url.port:
                            netloc += ":%s" % parsed_url.port
                        cleaned_url = parse.urlunparse((parsed_url.scheme,
                                                           netloc,
                                                           parsed_url.path,
                                                           parsed_url.params,
                                                           parsed_url.query,
                                                           parsed_url.fragment))
                        password_manager = url_request.HTTPPasswordMgrWithDefaultRealm()
                        password_manager.add_password(None,
                                                      "%s://%s" % (parsed_url.scheme, netloc),
                                                      parsed_url.username,
                                                      parsed_url.password)
                        request = Request(cleaned_url, data=body.encode('utf-8'), method=method)
                    else:
                        request = Request(url, data=body.encode('utf-8'), method=method)
        
                    request.add_header('Accept', 'application/json')
                    request.add_header('Content-Type', 'application/json;charset=UTF-8')
        
                    if password_manager:
                        opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                          HttpErrorHandler(),
                                                          url_request.HTTPBasicAuthHandler(password_manager),
                                                          url_request.ProxyHandler({}))
                    else:
                        opener = url_request.build_opener(url_request.HTTPRedirectHandler(),
                                                          HttpErrorHandler(),
                                                          url_request.ProxyHandler({}))
                    resp = opener.open(request, timeout=self._timeout)
                    statuscode = resp.code
                    if not hasattr(resp, 'getheader'):
                        if hasattr(resp.headers, 'getheader'):
                            resp.getheader = lambda x: resp.headers.getheader(x)
                        elif hasattr(resp.headers, 'get'):
                            resp.getheader = lambda x: resp.headers.get(x)
        
                data = resp.read()
                try:
                    if 300 <= statuscode < 304:
                        return self._request('GET', resp.getheader('location'))
                    body = data.decode('utf-8').replace('\x00', '').strip()
                    if 399 < statuscode < 500:
                        return {'status': statuscode, 'value': body}
                    content_type = []
                    if resp.getheader('Content-Type') is not None:
                        content_type = resp.getheader('Content-Type').split(';')
                    if not any([x.startswith('image/png') for x in content_type]):
                        try:
                            data = json.loads(body.strip())
                        except ValueError:
                            if 199 < statuscode < 300:
                                status = ErrorCode.SUCCESS
                            else:
                                status = ErrorCode.UNKNOWN_ERROR
                            return {'status': status, 'value': body.strip()}
        
                        assert type(data) is dict, (
                            'Invalid server response body: %s' % body)
                        # Some of the drivers incorrectly return a response
                        # with no 'value' field when they should return null.
                        if 'value' not in data:
                            data['value'] = None
                        return data
                    else:
                        data = {'status': 0, 'value': body.strip()}
                        return data
                finally:
                    self.logger.debug("Finished Request")
                    resp.close()
                
            except socket.timeout:
                self.logger.exception('Remote Connection timeout')
                raise XCTestAgentTimeoutException('XCTestAgent response is timed out')
            except Exception, e:
                self.logger.error('Remote Connection:%s' % str(e))
Exemplo n.º 18
0
def main():
    print('''
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+   This is Only For Practise And Educational Purpose Only  +
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

''')
    number = int(raw_input(' [+] Please Enter Your Username : '******' [+] Please Enter Your Password : '******'http://site24.way2sms.com/Login1.action'
    data = {'username': str(number), 'password': str(password)}
    data = urllib.urlencode(data)
    # ********************************************************
    cj = cookielib.CookieJar()
    header = {
        'User-Agent':
        'Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.0'
    }
    req = urllib2.Request(url, data, headers=header)
    opennr = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj),
                                  urllib2.HTTPRedirectHandler())
    print('[+] Please Wait. Trying To Login In ')
    req = opennr.open(req)
    sucess = str(req.info())
    sucess = sucess.find('Set-Cookie')
    if (sucess == -1):
        print('\n', '[+] Login Successful [+]')
        pass
    else:
        print('\n', '[+] Login Failed [+]')
        raw_input('')
        sys.exit(0)
    # ****** Tokken Receiving Mechanizem ******************
    tokken = cook(cj)
    print('\n [+] Tokken Received : ', tokken)
    # *******************************************************************
    # ********* Sms Sending System Configuration ************************
    url = 'http://site24.way2sms.com/smstoss.action'
    head = {
        'User-Agent':
        'Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.0',
        'Refere': str('http://site24.way2sms.com/sendSMS?Token=' + tokken)
    }
    mobile = int(
        raw_input(' [*] Please Enter Mobile Number For Sending SMS : '))
    #================   Checking Mechanizam =====================================
    if len(str(mobile)) == 10:
        pass
    else:
        print(" [*] Invalid Username")
        sys.exit(0)

    while True:
        message_raw = str(
            raw_input(
                ' [*] Please Enter Message For Sending. Note ! Not More Then 140 Words: '
            ))
        message = message_raw.replace(' ', '+')
        msglen = 140 - len(message)
        if len(message) < 140:
            break
        else:
            pass
    data = 'ssaction=ss&Token=' + tokken + '&mobile=' + str(
        mobile) + '&message=' + str(message) + '&msgLen=' + str(msglen)
    req = urllib2.Request(url, data=data, headers=head)
    print('[+] Sending SMS . Please Wait [+]')
    req = opennr.open(req)
    print('\n', ' [+] Task Complete Thanks For Using [+]')
    raw_input('\n\n')
Exemplo n.º 19
0
from traceback import print_exc
from urllib import request
from sys import version

try:
    args = ArgumentParser()
    args.add_argument('url', help='Set short url.')
    args.add_argument('-r',
                      dest='redirect',
                      default=10,
                      type=int,
                      help='Set max redirects.')
    args.add_argument('-p', dest='proxy', help='Set http proxy.')
    args = args.parse_args()

    handle_redirect = request.HTTPRedirectHandler()
    handle_redirect.max_redirections = args.redirect

    handle_cookie = request.HTTPCookieProcessor()
    request.install_opener(request.build_opener(handle_redirect,
                                                handle_cookie))

    req = request.Request(args.url, method='HEAD')
    version = version.split()
    req.add_header('User-Agent', 'Python v{}'.format(version))

    if args.proxy:
        proxy = request.urlparse(args.proxy)
        req.set_proxy('{}:{}'.format(proxy.hostname, proxy.port), proxy.scheme)

    with request.urlopen(req) as req:
Exemplo n.º 20
0
from http.cookiejar import CookieJar
from html.parser import HTMLParser
from bs4 import BeautifulSoup as bs
from urllib.parse import urlparse
from .authData import authData

from functions.splitKeyValue import splitKeyValue

encoding = 'utf-8'
client_id = 5512115
# scope = 'offline,messages'
scope = 'messages'
email = authData['email']
password = authData['password']
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(CookieJar()),
                              urllib2.HTTPRedirectHandler())


def vkAuth():

    ########################## GET AUTH FROM TIME ##################################
    authUrl = "http://oauth.vk.com/oauth/authorize?" + \
    "redirect_uri=http://oauth.vk.com/blank.html&response_type=token&" + \
    "client_id=%s&scope=%s&display=wap" % (client_id, scope)

    authResponse = opener.open(authUrl)
    authForm = bs(authResponse.read()).find('form')

    ########################## SEND AUTH DATA TIME #################################
    authData = {}
    # Collect form inputs
Exemplo n.º 21
0
Arquivo: apk.py Projeto: gaochun/share
 def _create_request(url, market_da):
     opener = urllib_request_compat.build_opener(
         urllib_request_compat.HTTPRedirectHandler())
     opener.addheaders.append(('Cookie', 'MarketDA=%s' % market_da))
     return opener.open(url)