用樹莓派為平臺實現校園網登錄

小半年前由于疫情原因,實驗室的各位都只能遠程搞科研。 然而大家都碰到了一個很現實的問題:學校雖然有免費的校園網,但是學校的網絡系統會在每天凌誠把所有在線的人踢下線,于是乎大家的遠程就

全 部 木 大

只能等著第二天導師上班的時候到實驗室?guī)兔Φ卿浺幌?。再后來(大概七月二十來號)我被導師抓到學校當了工具人,工具人之余就有了下面的對話:

導師:“xxx啊,你知不知道對面實驗室搞了個每天自動登錄校園網的東西啊”
我:“我不知道,不過可以去問問”(內心OS:“怕不是又要當工具人搞自動登錄”)
導師:“好像是一個什么腳本跑在路由器上,這樣吧,我去買個路由器,回來刷下系統,你把我們實驗室的自動登錄也弄好。”
我:“好的”(內心OS:“果然,但是有新的華碩路由器玩感覺也挺不錯的”)

后續(xù)又問了問,發(fā)現腳本不是我想的那樣用shell寫的,居然是用Python寫的,那不就是爬蟲了么。嗚呼哀哉,哪家路由器這么強能跑Python解釋器啊。細問才知道腳本是跑在服務器上的,我們實驗室泡在服務器上怕不是會被臭罵一頓,剛好我還有塊吃灰很久的樹莓派3B+,干脆就拿這個搭自動登錄了。
結果由于各種神奇的原因(中間家里有事,大家回學校不需要自動登陸了),這套東西一個月之前(十月左右)才正式搭好開始運行,后面又被導師要求出個配置手冊,美其名曰“你走了不就沒人會用這個了?”(你還能阻止我拔樹莓派么233),又摸了兩周終于把手冊寫出來了。具體內容就放下面了,總之大家就看個笑話,我也是菜雞一個,大家多多批評哈。

校園網自動登錄腳本配置手冊

系統搭建在Raspberry Pi Model 3B+上,系統信息如圖下:

neofetch.png

一,樹莓派系統燒錄

需要準備的材料:

  • 一塊樹莓派(不能是Raspberry Pi 0
  • 一張大于等于16G的SD卡和讀卡器,或一塊U盤

1,使用Raspberry Pi imager燒寫

國內網絡原因,不是很建議使用這種方式,下載過于慢

訪問樹莓派官網,并下載官方燒錄工具

根據自己對應的系統類型下載

rasp_download.png

對于Raspberry Pi OS,可以直接使用apt命令安裝,安裝命令如下:

sudo apt install rpi-image

軟件安裝完成后進入,Operating system選擇Raspbarry Pi OS(32bit),如果對其他操作系統更熟悉的話,也可選擇其他鏡像。SD Card 選擇準備好的內存卡/U盤,按下write等待系統刷寫完成。

2,下載并刷寫系統鏡像

訪問樹莓派鏡像下載地址,選擇Raspberry Pi OS with desktop and recommended software項下載。

download_image.png

下載BelenaEtcher并安裝。安裝完成后打開,選擇下載的鏡像和代刷寫的SD卡,按下Flash完成刷寫。

belena.png

二,樹莓派配置

1,通過SSH訪問樹莓派

系統刷寫完成后,在文件管理器中打開SD卡,創(chuàng)建名為“SSH”的文件,完成后將SD卡插入樹莓派,連接網線上電啟動。

訪問路由器管理界面,查看樹莓派的ip地址(426的路由器應該是固定為了192.168.50.114),路由器賬號密碼如下:

user:xxxxxx
password:*********

查看ip地址位于路由器首頁閱覽名單位置,樹莓派名稱應為raspberrypiaabbcco-s-pi

pi_ip.png

使用Powershell(Windows)或Terminal(Linux)訪問樹莓派,命令為

ssh pi@<raspberry ip>

raspberry ip為樹莓派對應的ip地址,初始密碼為raspberry

rasplogin.png

至此完成登陸步驟

2,更新軟件源

a.清華源

清華源由清華大學TUNA協會(清華大學學生網絡與開源軟件協會)提供,網址在此,網站上有如何使用該軟件園的幫助文檔,摘抄基于Debian10(buster)的換源方法如下:

# 編輯 `/etc/apt/sources.list` 文件,刪除原文件所有內容,用以下內容取代:
deb http://mirrors.tuna.tsinghua.edu.cn/raspbian/raspbian/ buster main non-free contrib rpi
deb-src http://mirrors.tuna.tsinghua.edu.cn/raspbian/raspbian/ buster main non-free contrib rpi

# 編輯 `/etc/apt/sources.list.d/raspi.list` 文件,刪除原文件所有內容,用以下內容取代:
deb http://mirrors.tuna.tsinghua.edu.cn/raspberrypi/ buster main ui

b.中科大源

中科大源由中國科學技術大學網絡信息中心提供支持,由LUG@USTC(中國科學技術大學Linux用戶協會)維護.同樣的,在軟件源網站上也有如何使用該源的幫助文檔,摘抄于網頁的換源方法如下:

將 /etc/apt/sources.list 文件中默認的源地址 http://raspbian.raspberrypi.org/ 替換為 http://mirrors.ustc.edu.cn/raspbian/ 即可。

raspbian 2018-04-19 之后的鏡像默認源已經更改,用如下命令替換:

  sudo sed -i 's|raspbian.raspberrypi.org|mirrors.ustc.edu.cn/raspbian|g' /etc/apt/sources.list

當然也可以直接編輯 /etc/apt/sources.list 文件(需要使用 sudo)。刪除原文件所有內容,用以下內容取代(以 Buster 示例):

  deb http://mirrors.ustc.edu.cn/raspbian/raspbian/ buster main contrib non-free rpi
  #deb-src http://mirrors.ustc.edu.cn/raspbian/raspbian/ buster main contrib non-free rpi

編輯源文件方法為:

sudo nano <file position>
或
sudo vi <file position>

編輯源文件后,在命令行運行:

sudo apt-get update
sudo apt-get upgrade

三,Python環(huán)境配置

登錄腳本使用了模擬瀏覽器,需要在python環(huán)境中安裝selenium包,chromium瀏覽器和配合selenium使用的chromium-chromedriver。不過Raspberry Pi OS自帶了cheomium,這里只要安裝selenium和配套的chromium-chromedriver

安裝selenium

pip3 install selenium
selenium.png

安裝chromium-chromedriver

sudo apt-get install chromium-chromedriver

查看安裝路徑

dpkg -L chromium-chromedriver
chromedriver.png

四,自動登錄腳本配置

1,Python腳本:

自動登錄腳本使用了之前配置的Python環(huán)境和系統(很可能)自帶的cron定時任務服務,Python腳本如下:

import time
import logging
import socket
from selenium import webdriver

Chrome_driver_root = "<chrome driver position>"


def init_logger():
    logging.basicConfig(level=logging.INFO,
                     format="%(asctime)s %(levelname)s %(message)s",
                     datefmt="%Y-%m-%d %H:%M:%S",
                     filename="<logdir>")
    logger = logging.getLogger("netlogger")

    return logger


def is_connected(logger):
    '''
    show if the net is connected
    '''
    s = socket.socket()
    status = s.connect_ex(("www.bing.com", 443))
    try:
        if status == 0:
            return True
        else:
            return False
    except Exception:
        logger.critical("an Exception happend, check your system")
        return False


if __name__ == "__main__":
    logger = init_logger()
    if not is_connected(logger):
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        options.add_argument('blink-settings=imagesEnabled=false')
        options.add_argument('--disable-gpu')
        browser = webdriver.Chrome(Chrome_driver_root, options=options)
        try:
            browser.get("http://www.msftconnecttest.com/redrict")
            time.sleep(1)
            browser.find_element_by_id("userphone").send_keys("<學號>")
            time.sleep(1)
            browser.find_element_by_id("password").send_keys("<密碼>")
            time.sleep(1)
            browser.find_element_by_id("mobilelogin_submit").click()
            time.sleep(1)
            if is_connected(logger):
                logger.info("network reconnected")
            else:
                logger.warning(
                    "login filed, waiting for the next login")
            browser.quit()
        except Exception:
            browser.quit()
            logger.critical("An Exception happend, check your system")
    else:
        logger.info("network still connected,waiting for the next ask")

2,cron定時任務

a.安裝cron

一般的Linux發(fā)行版都會帶cron模塊,而且是默認運行的,查詢cron是否在工作可以用

systemctl status cron.service

service cron status

如果看到如下文字即說明cron已安裝且正在運行,第四行為active(running)

pi@aabbcco-s-pi:~ $ systemctl status cron.service
● cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2020-11-24 16:08:49 CST; 19h ago
    Docs: man:cron(8)
Main PID: 331 (cron)
    Tasks: 1 (limit: 1939)
CGroup: /system.slice/cron.service
        └─331 /usr/sbin/cron -f

若cron安裝完成但未運行,應有如下顯示,第四行為inactive(dead)

pi@aabbcco-s-pi:~ $ systemctl status cron.service
● cron.service - Regular background program processing daemon
Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Wed 2020-11-25 12:25:04 CST; 4s ago
    Docs: man:cron(8)
Process: 331 ExecStart=/usr/sbin/cron -f $EXTRA_OPTS (code=killed, signal=TERM)
Main PID: 331 (code=killed, signal=TERM)

此時可以運行

sudo systemctl start cron.service

啟動服務

若cron未安裝,則使用

sudo apt-get install cron

進行安裝

b.配置cron

這里使用crontab命令對其進行配置,命令為

crontab -u <user> -e

第一次使用會彈出編輯器選擇按鈕,建議使用nano,配置文件如下

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

具體用法不再贅述,有疑問的話請看這篇博客

編寫這篇文章時腳本文件為netlogin.py,位于~/scripts文件夾,每天凌晨0點到1點每隔20分鐘運行一次,表達式為

*/20 0 * * * python3 /home/pi/scripts/netlogin.py

至此,所有配置已完成

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容