python3.5自动登录网页的小工具

  • 需求分析

每隔15分钟对网页进行自动登录:用户输入用户名密码之后,对密码进行加密保存到文件中,自动登录程序在获取密码之后进行解密,并登录网页。通过task schedule设置trigger对登录程序进行定时触发

  • 实现代码:

  1. 初始化用户数据,并进行加密保存init_db.py

#!/usr/bin/env python
#_*_coding:utf-8_*_

#初始化用户数据表 user_list.db

import os
import json
import  sys
import base64

def encrypt(string):
    s1 = base64.encodestring(bytes(string,encoding='utf-8'))
    return s1.decode('utf-8')
    
def init_db_user():
    _db_file = os.path.join(DATABASE['dbpath'],"user.db")            
    username = input('please input username:')
    password = input('please input password:')
    #自动添加后缀
    temp = [username,'@******']
    tmpusername = ''.join(temp)
    
    with open(_db_file,"w+") as fp:
        for k,v in _user_list.items():

            _user_list['username'] = tmpusername
            #对密码进行加密
            encrypassword = encrypt(password)
            #修改明文密码            
            _user_list['password']=encrypassword
            
        fp.write(json.dumps(_user_list))     
           
def init_database(): 
    tables = list(DATABASE['tables'].values())#数据表名称列表
    database = DATABASE['dbpath'] #数据表存放路径
 
    for _table in tables:
        #如果表不存在
        if not os.path.exists(os.path.join(database,"{0}.db".format(_table))):
            print("Table {0}.db create successfull".format(_table))
            
        if hasattr(sys.modules[__name__],"init_db_{0}".format(_table)):
            init_func = getattr(sys.modules[__name__],"init_db_{0}".format(_table))
            init_func()

        else:
            print("init table {0} failed, no function init_db_{0} found".format(_table))

if __name__ == "__main__":
    #程序文件主目录
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    #添加环境变量
    sys.path.append(BASE_DIR)
    #数据库信息
    DATABASE = dict(engineer="file",dbpath=BASE_DIR,tables={"user":"user"})
    #用户列表初始化    
    _user_list = {"username":'',"password":''}
    
    init_database()
    print('init_db success')
View Code

  2. 解密用户数据,自动登录程序login.py

#!/usr/bin/env python
#_*_coding:utf-8_*_
import os,sys
import requests
import urllib
import json
import base64

class Admin():
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(BASE_DIR)
    DATABASE = dict(engineer="file",dbpath=BASE_DIR,tables={"user":"user"})
    __database = "{0}.db".format(os.path.join(DATABASE['dbpath'], DATABASE["tables"]["user"]))

    def __init__(self):
        self.password = ""
        self.username = ""
        self.userinfo = {}
        self.userinfo = self.db_load() 
        self.login()
        
    def load_data_from_db(self,tablename):
        try:
            with open(tablename,'r+') as f:
                return json.load(f)
        except Exception as e:
            print(e)
        
    def db_load(self):
        self.dict_user = self.load_data_from_db(self.__database)
        return self.dict_user
    
    def decryption(self,string):
        result = base64.decodestring(string)
        return result.decode('utf-8')
       
    def login(self):           
        header = {
        
                  'Connection': 'Keep-Alive',
                  'Accept-Language': 'zh-CN',
                  'Accept': 'text/html, application/xhtml+xml, */*',
                  'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0; chromeframe/29.0.1547.57) like Gecko',
                  'Accept-Encoding': 'gzip, deflate',
                  'Host': '*.*.*.*',
                  }
        s = requests.Session()
        s.headers = header
        
        url = '*******'
        username = self.userinfo['username']
        tmppassword = self.userinfo['password'].encode('utf-8')
        password = self.decryption(tmppassword)
        postDict = {
                    'tz_offset':'480',
                    'realm':'***',
                    'username':username,
                    'password':password,
                    'btnSubmit':'Sign In',
                    }
        
        postData = urllib.parse.urlencode(postDict).encode()
        result = s.post(url,data=postData,verify=False)
        print('login status %s' % result.status_code)

if __name__=="__main__":        
    admin = Admin()
View Code

  3.task schedule设置定时触发

  windws->start menu->control panel, find adminitrative tools, then find task scheduler

  • 在Trigger里面设置定时:repeat task every 15min
  • 在Actions里面添加代码的路径:*****/login.exe

  4. 使用Pyinstaller进行程序打包生成可执行文件init_db.exe和login.exe

  • 安装pyinstaller:pip3 intstall pyinstaller
  • 生成可执行文件:

  pyinstaller -F init_db.py

  pyinstaller -F login.py

 

  

转载于:https://www.cnblogs.com/candychen20170109/p/6558166.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值