Пример #1
0
def autologin():
    seed_url = request.args.get("seedurl")
    username = request.args.get("username")
    password = request.args.get("password")
    open_in_browser = request.args.get("openinbrowser")

    hash = hashlib.sha1()
    hash.update(str(time.time()))
    db_name = "/tmp/" + hash.hexdigest()[:20] + ".db"
    
    if not seed_url or not username or not password:
        raise Exception("Missing a needed parameter")

    slfj = ScrapydLoginFinderJob(seed_url, username, password, db_name)
    slfj.schedule()
    slfj.block_until_done()
    
    al = AutoLogin(db_name)
    auth_info = al.get_auth_headers_and_redirect_url()

    if open_in_browser:

        tmp_response_file = "/tmp/openinbrowser.html" 
        f = open(tmp_response_file, "w")
        f.write(auth_info["response_body"].encode("utf-8"))
        webbrowser.open(tmp_response_file, new = 2)
    
    return Response(json.dumps(auth_info), mimetype = "application/json")
Пример #2
0
def autologin():
    seed_url = request.args.get("seedurl")
    username = request.args.get("username")
    password = request.args.get("password")
    open_in_browser = request.args.get("openinbrowser")

    hash = hashlib.sha1()
    hash.update(str(time.time()))
    db_name = "/tmp/" + hash.hexdigest()[:20] + ".db"

    if not seed_url or not username or not password:
        raise Exception("Missing a needed parameter")

    slfj = ScrapydLoginFinderJob(seed_url, username, password, db_name)
    slfj.schedule()
    slfj.block_until_done()

    al = AutoLogin(db_name)
    auth_info = al.get_auth_headers_and_redirect_url()

    if open_in_browser:

        tmp_response_file = "/tmp/openinbrowser.html"
        f = open(tmp_response_file, "w")
        f.write(auth_info["response_body"].encode("utf-8"))
        webbrowser.open(tmp_response_file, new=2)

    return Response(json.dumps(auth_info), mimetype="application/json")
Пример #3
0
def get_login_cookies():
    """
    Simple API for returning login cookies
    """
    if not request.json:
        abort(400)
    if 'url' not in request.json:
        abort(400)
    if 'username' not in request.json:
        abort(400)
    if 'password' not in request.json:
        abort(400)
    auto_login = AutoLogin()
    login_cookie_jar = auto_login.auth_cookies_from_url(
        url=request.json['url'],
        username=request.json['username'],
        password=request.json['password']
    )

    if login_cookie_jar is not None:
        login_cookies = auto_login.cookies_from_jar(login_cookie_jar)
    else:
        login_cookies = {}

    return jsonify({'cookies': login_cookies}), 201
Пример #4
0
def index():
    """
    Main app route.
    Hosts form used for testing autologin.
    User can submit credentials and URL,
    authenticated cookies returned.
    Also makes a request using extracted cookies,
    saves the source and allows you to view in browser.
    Useful for checking whether login was successful.
    """
    form = LoginForm(request.form)
    auto_login = AutoLogin()
    login_cookies = None
    login_links = None
    filename = None
    # Process form submission
    if request.method == 'POST' and form.validate():
        msg = 'Login requested for '
        msg += '{} '.format(form.url.data)
        msg += 'with username={} and '.format(form.username.data)
        msg += 'password={}'.format(form.password.data)
        # Grab html for login page
        html_source = auto_login.get_html(form.url.data)
        # Attempt login
        login_cookie_jar = auto_login.auth_cookies_from_html(
            html_source=html_source,
            username=form.username.data,
            password=form.password.data,
            base_url=form.url.data
        )
        # If we've extracted some cookies, 
        # use them to request a page and download html source
        # for viewing in browser,
        if login_cookie_jar is not None:
            download = download_page(form.url.data, auto_login.cookie_jar)
            login_cookies = login_cookie_jar.__dict__
            if download[0] != 'ok':
                flash(download, 'danger')
            else:
                flash(msg, 'success')
                filename = download[1]
        else:
            flash('No login form found', 'danger')
            login_links = auto_login.extract_login_links(html_source)
            if len(login_links) > 0:
                flash('{} login links found'.format(len(login_links)), 'success')
            else:
                flash('No login links found', 'danger')
    else:
        flash_errors(form)
    return render_template(
        'index.html',
        form=form,
        login_cookies=login_cookies,
        login_links=login_links,
        filename=filename
    )
Пример #5
0
 def __init__(self, baseUrl=None, userid=None, driver=None, from_file=None):
     super(TDPositions, self).__init__()
     self.mydriver = driver
     self.diff52Col = "diff_52VsCurrent(%)"
     self.from_file = from_file
     if self.from_file is None:
         self.baseUrl = baseUrl
         self.userId = userid
         al = AutoLogin("system", self.userId, self.mydriver)
         al.logon()
Пример #6
0
def main():
    url0 = "https://invest.ameritrade.com/grid/p/site#r=jPage/cgi-bin/apps/u/GainskeeperStart"
    url = "https://invest.ameritrade.com/grid/p/site#r=jPage/https://gainskeeper.ameritrade.com/amtdGP/GainLoss.aspx?c_name=invest_VENDOR"
    baseurl = "www.tdameritrade.com"
    userid = "36205503"
    mydriver = CustomDriver(CustomDriver.CHROME, baseurl)
    mydriver.initURL()
    al = AutoLogin(baseurl, userid, mydriver)
    al.logon()
    mydriver.getURL(url0)
Пример #7
0
def index():
    """
    Main app route.
    Hosts form used for testing autologin.
    User can submit credentials and URL,
    authenticated cookies returned.
    Also makes a request using extracted cookies,
    saves the source and allows you to view in browser.
    Useful for checking whether login was successful.
    """
    form = LoginForm(request.form)
    auto_login = AutoLogin()
    login_cookies = None
    login_links = None
    filename = None
    # Process form submission
    if request.method == 'POST' and form.validate():
        msg = 'Login requested for '
        msg += '{} '.format(form.url.data)
        msg += 'with username={} and '.format(form.username.data)
        msg += 'password={}'.format(form.password.data)
        # Grab html for login page
        html_source = auto_login.get_html(form.url.data)
        # Attempt login
        login_cookie_jar = auto_login.auth_cookies_from_html(
            html_source=html_source,
            username=form.username.data,
            password=form.password.data,
            base_url=form.url.data)
        # If we've extracted some cookies,
        # use them to request a page and download html source
        # for viewing in browser,
        if login_cookie_jar is not None:
            download = download_page(form.url.data, auto_login.cookie_jar)
            login_cookies = login_cookie_jar.__dict__
            if download[0] != 'ok':
                flash(download, 'danger')
            else:
                flash(msg, 'success')
                filename = download[1]
        else:
            flash('No login form found', 'danger')
            login_links = auto_login.extract_login_links(html_source)
            if len(login_links) > 0:
                flash('{} login links found'.format(len(login_links)),
                      'success')
            else:
                flash('No login links found', 'danger')
    else:
        flash_errors(form)
    return render_template('index.html',
                           form=form,
                           login_cookies=login_cookies,
                           login_links=login_links,
                           filename=filename)
Пример #8
0
def test_login_request():
    al = AutoLogin()
    html = '''
    <form method="POST" action=".">
        <input type="email" name="login">
        <input type="password" name="password">
        <input type="submit" value="Login">
    </form>
    '''
    req = al.login_request(html, username='******', password='******')
    assert req == {
        'body': 'login=admin&password=secret',
        'headers': {b'Content-Type': b'application/x-www-form-urlencoded'},
        'method': 'POST',
        'url': '.'}
    req = al.login_request(html, username='******', password='******',
                           base_url='/login/')
    assert req == {
        'body': 'login=admin&password=secret',
        'headers': {b'Content-Type': b'application/x-www-form-urlencoded'},
        'method': 'POST',
        'url': '/login/'}
Пример #9
0
def get_login_cookies():
    """
    Simple API for returning login cookies
    """
    if not request.json:
        abort(400)
    if 'url' not in request.json:
        abort(400)
    if 'username' not in request.json:
        abort(400)
    if 'password' not in request.json:
        abort(400)
    auto_login = AutoLogin()
    login_cookie_jar = auto_login.auth_cookies_from_url(
        url=request.json['url'],
        username=request.json['username'],
        password=request.json['password'])

    if login_cookie_jar is not None:
        login_cookies = auto_login.cookies_from_jar(login_cookie_jar)
    else:
        login_cookies = {}

    return jsonify({'cookies': login_cookies}), 201
from autologin import AutoLogin
print("PRESS CTRL-Z to EXIT")
f = open('zmap_output.txt', "r")
lines = f.readlines()
num_lines = sum(1 for line in open('zmap_output.txt'))
#Zmap_output.txt contains list of scanned IPs of Specified Range
f.close()
for i in range(0,num_lines):
 Ip_s = lines[i]
 url ="http://"+Ip_s
 username = '******'
 password = '******'
 al = AutoLogin()
 try:
    cookies = al.auth_cookies_from_url(url, username, password)
    print("Working Url: "+url)
    print(type(cookies))
    with open("output_au.txt",mode='a') as z:
     z.write(str(url)+'\n')
 except:
   print("Try Next Ip: "+url)
   
Пример #11
0
 def setUp(self):
     self.al = AutoLogin()
     self.mockserver = MockServer()
     self.mockserver.__enter__()
Пример #12
0
class TestAuthCookiesFromUrl(unittest.TestCase):

    base_url = 'http://127.0.0.1:{}'.format(PORT)
    url = base_url + Login.url
    url_no_change_cookie = base_url + LoginNoChangeCookie.url
    url_check_proxy = base_url + LoginCheckProxy.url

    def setUp(self):
        self.al = AutoLogin()
        self.mockserver = MockServer()
        self.mockserver.__enter__()

    def tearDown(self):
        self.mockserver.__exit__(None, None, None)

    def test_no_login_form(self):
        with pytest.raises(AutoLoginException) as e:
            self.al.auth_cookies_from_url(
                self.url + '?hide=', 'admin', 'secret')
        assert e.value.args[0] == 'nologinform'

    def test_wrong_password(self):
        with pytest.raises(AutoLoginException) as e:
            self.al.auth_cookies_from_url(self.url, 'admin', 'wrong')
        assert e.value.args[0] == 'badauth'

    def test_normal_auth(self):
        cookies = self.al.auth_cookies_from_url(
            self.url + '?foo=', 'admin', 'secret')
        assert {c.name: c.value for c in cookies} == {'_auth': 'yes'}

    def test_redirect_to_same_url(self):
        cookies = self.al.auth_cookies_from_url(self.url, 'admin', 'secret')
        assert {c.name: c.value for c in cookies} == {'_auth': 'yes'}

    def test_proxy(self):
        assert 'localhost' not in self.url, 'proxy_bypass bypasses localhost'
        with MockServer('tests.proxy'):
            with pytest.raises(AutoLoginException) as e:
                self.al.auth_cookies_from_url(
                    self.url_check_proxy, 'admin', 'secret')
            cookies = self.al.auth_cookies_from_url(
                self.url_check_proxy, 'admin', 'secret',
                settings={
                    'HTTP_PROXY': 'http://127.0.0.1:{}'.format(PROXY_PORT)
                },
            )
        assert {c.name: c.value for c in cookies} == {'_auth': 'yes'}

    def test_no_change_cookie(self):
        cookies = self.al.auth_cookies_from_url(
            self.url_no_change_cookie, 'admin', 'secret')
        assert {c.name: c.value for c in cookies} == {'session': '1'}

    def test_no_change_cookie_wrong_password(self):
        with pytest.raises(AutoLoginException) as e:
            self.al.auth_cookies_from_url(
                self.url_no_change_cookie, 'admin', 'wrong')
        assert e.value.args[0] == 'badauth'
Пример #13
0
def main():
    try:
        autologin = AutoLogin()                     # 实例化登录模块
        rest = autologin.main(GLOBAL_USERNAME,GLOBAL_PASSWORD)# 执行登录
        if rest != "0":                             # 如果返回值不是0
            print rest                              # 打印错误信息
            return
        print "登录模块已完成"
        time.sleep(5)                               # 程序暂停5秒
        autoquery = AutoQuery()                     # 实例化查询模块
                                                    # 从数据库查询信息并格式化数据
        format_data = autoquery.query_code(GQD["date"],GQD["from"],GQD["to"])
        a = 1
        while True:                                 # 死循环避免出票失败
            while True:                             # 死循环查询列车信息
                try:                                # 防止查询过多出现异常
                    data = autoquery.get_info(format_data)# 获取所有列车信息
                                                    # 获取指定列车信息
                    train_data = autoquery.query_train(GQD["train"],GQD["person"],GQD["seattype"],data)
                    if not train_data:
                        print "第"+str(a)+"次查询"
                        print "相关列车暂无座位"
                        time.sleep(3)
                        a += 1
                    else:
                        break
                except Exception as e:
                    pass
            print train_data
            print "列车数据已获取 执行预定"
            autoorder = AutoOrder()                 # 实例化预定模块
            rest = autoorder.checklogin()           # 判断是否登录
            if rest != "0":
                print rest
                time.sleep(5)
                continue                            # 获取预定页面
            rest = autoorder.destine(train_data[0],GQD["date"],GQD["from"],GQD["to"])
            if rest != "0":
                print rest
                time.sleep(5)
                continue
            token_key = autoorder.get_token()       # 获取token及key
            if token_key == "":
                time.sleep(5)
                continue                            # 获取乘车人信息
            person_list = autoorder.get_person(GQD["person"])
            if not person_list[0]:
                print "乘车人不存在"
                time.sleep(5)
                continue
            time.sleep(3)                           # 发送乘车人请求 格式化乘车人信息字符串
            person_info = autoorder.order_person_submit(GQD["seattype"],person_list,token_key)
            if person_info == "seat error":
                print "没有相应座位"
                time.sleep(5)
                continue                            # 发送车次信息
            rest = autoorder.order_train_submit(GQD["date"],train_data,person_info,token_key)
            if rest == "count error":               # 判读座位是否为空
                print "没有相关座位"
                time.sleep(5)
                continue
            elif rest != "0":
                print "车次提交失败"
                time.sleep(5)
                continue                            # 最后提交预定信息
            rest = autoorder.order_submit(person_info,token_key,train_data)
            if rest == "0":
                print "订单提交成功"
                rest = autoorder.queue_submit(token_key)# 查询订单结果 返回结果
                if rest == "0":
                    print rest
                    break
                else:
                    print rest
                    print "获取订单失败"
    except Exception as e:
        print e
        rest = sendemail("火车票预定异常")
        print rest
    else:
        print "预定成功 请及时登录12306支付订单"
        rest = sendemail("火车票预定情况")
        print rest