<file_sep># -*- coding:utf-8 -*-
import subprocess as sp
import json
import os
import requests
import urllib
import time
import logging
import datetime

class Connector():

    def __init__(self):
        now = int(time.time())     
        timeArray = time.localtime(now)
        _time = time.strftime("%Y-%m-%d-%H-%M-%S", timeArray)
        self.logfile = 'log_' + _time + '.log'
        self.config()
        self.set_logger()
    

    def set_logger(self):
        
        self.logger = logging.getLogger()
        self.logger.setLevel(level=logging.INFO)
        handler = logging.FileHandler(self.log_folder + self.logfile, encoding='utf-8')
        handler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        console = logging.StreamHandler()
        console.setLevel(logging.WARNING)

        
        self.logger.addHandler(handler)
        self.logger.addHandler(console)


    def is_connected(self):
        result = os.system('ping ' + self.ping_ip)
        if result == 0:
            return True
        else:
            return False


    def config(self):
        conf = open('conf.conf', 'r')
        s = conf.read()
        s = s.replace('\n', '')
        s = s.replace('\t', '')
        data = json.loads(s)
        conf.close()

        connect_info = data['connect']
        self.headers = connect_info['header']
        self.login_url = connect_info['url']
        self.send = connect_info['data-send']
        self.send['DDDDD'] = data['user']
        self.send['upass'] = data['pwd']
        self.ping_ip = connect_info['ip-ping']
        self.retry_connected = connect_info['retry']['connected']
        self.retry_disconnected = connect_info['retry']['disconnected']

        self.log_folder = './log/'
        if not os.path.exists(self.log_folder):
            os.makedirs(self.log_folder)
        with open(self.log_folder + self.logfile,'w') as f:
            f.write(self.logfile+'\n')
            

    def connect(self):
        requests.packages.urllib3.disable_warnings()
        session = requests.session()
        r = session.post(self.login_url, headers=self.headers, data=self.send, verify=False)
        # print(r.text)


    def run(self):
        while True:
            try:
                if self.is_connected():
                    self.logger.info('Connected')
                    time.sleep(60 * self.retry_connected)
                else:
                    self.logger.warning('Disconnected')
                    self.connect()
                    if self.is_connected():
                        self.logger.warning('Connection repaired')
                        time.sleep(60 * self.retry_connected)
                    else:
                        self.logger.warning('Connection not repaired')
                        time.sleep(60 * self.retry_disconnected)
            except Exception as e:
                self.logger.error('Unkown error, detail infomation: ' + str(e))
                time.sleep(60 * self.retry_disconnected)
<file_sep>from core.connector import Connector

if __name__ == "__main__":
    connection = Connector()
    connection.run()<file_sep>## Auto Connect
这是一个神奇的python脚本，可以维持你的设备与SZU网络的连接(仅限办公区域)

## 用法

### 配置 conf.conf 文件
* `user`: "你的账号" (保留引号)
* `pwd`:  "<PASSWORD>" (保留引号)
* `retry: connected`: 连接成功后下次尝试间隔，单位：分钟，默认: 10
* `retry: disconnected`: 连接失败后下次尝试间隔，单位：分钟，默认: 5

### 运行
* python >= 2.7
* SZU内网环境
* 正确的账号密码(填入conf.conf)和未欠费的套餐

执行命令
```
python main.py
```

### 测试
* 手动断开网络连接
* 运行脚本
* 查看对应./log下的日志文件，出现以下类似信息表示网络连接已经修复
```
2021-01-25 20:51:21,988 - WARNING - Disconnected
2021-01-25 20:51:25,502 - WARNING - Connection repaired
```
* 如果有任何问题，请留下你的issue

### 保持脚本常驻
* 设置BIOS来电自启动
* Windows 设置计划任务
* Linux & Mac 设置脚本自启动


## 申明
* 禁止用此脚本干扰他人正常上网
* 本脚本使用构造POST表单完成上网请求，完全安全可信
* 本脚本导致上网账号被封禁概不负责
* conf.conf 明文密码可能导致您的账号密码泄露