Skip to content

Instantly share code, notes, and snippets.

@padeoe
Created June 19, 2020 09:06
Show Gist options
  • Save padeoe/3e6165cdf25f8038dca8d74f2d0eceb3 to your computer and use it in GitHub Desktop.
Save padeoe/3e6165cdf25f8038dca8d74f2d0eceb3 to your computer and use it in GitHub Desktop.
每隔 5 分钟执行一次p.nju.edu.cn在线检测,如果不在线则登录上线

功能特性

每隔 5 分钟执行一次网络系统登录检测,检查当前是否在线,如果不在线则登录上线。

  • 定时检测
  • 保存登录日志
  • 用户名密码参数化

依赖 Python 3.

1. 创建登陆脚本

创建和保存如下 nju_bras.py 文件。

nju_bras.py

import argparse
import logging
import os
from logging.handlers import RotatingFileHandler

import requests
import json

logger = logging.getLogger('nju portal')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

ch = logging.StreamHandler()
fh = RotatingFileHandler(os.path.join('/var/log/nju_bras', 'portal_login.log'),
                         mode='a', maxBytes=5 * 1024 * 1024, backupCount=2, encoding='utf-8', delay=0)

logger.addHandler(fh)
logger.addHandler(ch)
fh.setFormatter(formatter)
ch.setFormatter(formatter)


def login(username, password):
    try:
        response_content = requests.post('http://p.nju.edu.cn/portal_io/login',
                                         {'username': username, 'password': password}).text
        logger.info('Trying login' + response_content)
        item = json.loads(response_content)
        return item.get('userinfo', {}).get('username') == username
    except Exception as e:
        logger.error('Failed to login: ' + str(e))


def is_online(username):
    bool_online = False
    try:
        response_content = requests.post('http://p.nju.edu.cn/portal_io/getinfo').text
        item = json.loads(response_content)
        bool_online = item.get('userinfo', {}).get('username') == username
        if bool_online:
            logger.info('Already online: ' + response_content)
        else:
            logger.warning('Offline: ' + response_content)
    except Exception as e:
        logger.error('Failed to check status: ' + str(e))

    return bool_online


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='检查p.nju是否在线离线则执行登录的脚本')
    parser.add_argument('--username', help='用户名', required=True)
    parser.add_argument('--password', help='密码', required=True)
    args = parser.parse_args()

    if not is_online(args.username):
        login(args.username, args.password)

2. 设置定时任务

将如下命令中的 YOUR_USERNAMEYOUR_PASSWORD 替换为 p.nju.edu.cn 的用户名、密码。/PATH/TO/nju_bras.py 替换为脚本路径。其中的 5 指的是每 5 分钟执行一次登录检测,可修改。

echo '*/5 * * * * python3 /PATH/TO/nju_bras.py --username YOUR_USERNAME --password YOUR_PASSWORD' | sudo tee --append /etc/crontab

操作完成,就会每隔5分钟执行一次登录检测并上线了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment