在我所处的网络中,受到了管制,我必须登陆才能使用我的网络。但是我的Linux没有桌面系统,甚至没有外接的显示器,这非常麻烦。虽然我设置了每次开机自动连接到我的移动热点。但是这明显不实际。
所以我抓包了一个登陆认证的带参URL,只需要设置定时任务在每天登陆认证重置后一分钟,请求这个URL即可。
但是,可能我的终端机会在某个时间段关机,之后一段时间再开机,而这个时间远远未到定时任务的时间,所以我的主机会离线,直到触发定时任务。或者我不厌其烦找来显示器,又搬来键盘,触发验证。
所以,我必须要设置开机执行一条命令,那条命令就是 curl 登陆认证的带参URL。之后长时间开机就交给定时任务了。
正文
方法 1:使用 /etc/rc.local(传统-不推荐)
/etc/rc.local 是一个传统的方式,用于在系统启动时运行命令。虽然在某些较新的系统中可能需要手动启用该功能,但它仍然是一个简单的方法。
步骤:
- 编辑
/etc/rc.local文件: ```shell vim /etc/rc.local
2. 在 `exit 0` 之前加入你的命令。例如:
```shell
#!/bin/sh -e
sleep 10 # 添加一个延迟,等待网络服务启动
curl https://xxxxxx.com....
exit 0
- 确保
/etc/rc.local文件有可执行权限: ```shell chmod +x /etc/rc.local
**如果 `/etc/rc.local` 不存在或未启用:**
1. 检查服务是否存在:
```shell
systemctl status rc-local
- 如果服务不存在,创建一个服务文件:
vim /etc/systemd/system/rc-local.service
- 内容如下:
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
[Install]
WantedBy=multi-user.target
- 启用并启动服务:
systemctl enable rc-local
systemctl start rc-local
方法 2:使用 crontab 的 @reboot(推荐)
cron 可以使用 @reboot 关键字在系统启动时运行命令。
步骤:
- 编辑当前用户的
crontab: ```shell crontab -e
2. 添加一条 `@reboot` 任务。例如:
```shell
@reboot sleep 10 && curl https://xxxxxxx.com.... # 添加了延迟10s,等待网络加载连接
(已有定时任务的话,在第二行追加即可)
- 保存并退出编辑器,重启系统测试。
注意:如果命令需要以特定用户身份运行,请确保编辑的是对应用户的
crontab。
方法 3:创建 systemd 服务(比较麻烦-推荐)
systemd 是现代 Linux 系统的初始化系统,可以通过创建服务文件来配置开机启动任务。
步骤:
- 创建一个
sh文件 ```shell vim /path/to/your/script.sh # 对应下面的守护进程配置
之后填东西进去:
```shell
#!/bin/sh
sleep 10
curl https://xxxxxxxx.com....
之后记得给一下执行权限
chmod +x /path/to/your/script.sh
- 创建一个自定义服务文件: ```shell vim /etc/systemd/system/my-startup.service
3. 添加以下内容(将 `ExecStart` 替换为你的命令):
```shell
[Unit]
Description=My Startup Script
After=network.target
[Service]
Type=oneshot
ExecStart=/path/to/your/script.sh # 想要执行的bash脚本地址,涉及到curl认证的话,记得sleep一下,参考上面,防止网络未加载
RemainAfterExit=true
[Install]
WantedBy=multi-user.target
- 保存文件后,启用并启动服务: ```shell systemctl enable my-startup.service systemctl start my-startup.service
5. 测试服务是否在开机时运行:
```shell
systemctl status my-startup.service
方法 4:编辑 Shell 启动文件(取决于你启动的是哪一个终端)
如果命令仅需要在某个用户登录后执行,可以将其添加到用户的 Shell 启动文件中,例如 .bashrc 或 .bash_profile。
步骤:
- 编辑
.bashrc文件: ```shell vim ~/.bashrc # (取决于你启动的是哪一个终端)
2. 添加你的命令,例如:
```shell
sleep 10
curl https://xxxxxxx.com....
- 保存文件并退出。注意,这种方式只会在该用户登录时执行。
我的方案 (Crontab + Systemd)
首先,我创建了一个
ba.sh文件,在/root/下面,给予了+x的权限。我写了一个守护进程(Systemd),调用与执行
ba.sh,之后设置开机自启动。使用
crontab -e在每日早上7点,自动触发一次认证,这里直接复用ba.sh即可。
0 7 * * * bash /root/ba.sh
- 通过
/etc/network/interfaces文件配置完 无线网络 的连接配置(到管制网络)。重启网络服务和终端机 (请确保已完成数据持久化(保存文件),因为一会需要手动硬重启) – 因为我使用的是无线网络。有线网络一般接上线即可,而无需配置/etc/network/interfaces,除非你需要静态设置。
systemctl restart networking # 此时 SSH 就已经和终端机断开连接了,手动重启。
- 后台看到终端机上线,完成。
总结
如果需要 系统级别 的开机命令,推荐使用
/etc/rc.local或systemd服务。如果是 用户级别 的命令,可以使用
crontab @reboot或~/.bashrc。系统级别比用户级别要稳定些,也比较麻烦。
