需求
在一台Ubuntu主机上,每次开机自动启动Netron服务,使得另一台windows主机(未安装Netron)可以通过局域网连接使用Netron
系统配置
系统:Ubuntu22.04
开启Netron服务的脚本
脚本:Netron8080.sh
Ubuntu主机的局域网IP地址为192.168.0.2,通过--host命令建立网络主机
#!/bin/bash
echo "******************************************************"
/home/username1/.local/bin/netron --host 192.168.0.2 -p 8080 -b &
sleep 2
echo "******************************************************"
注意:这里的要点是必须使用netron的完整路径,否则启动服务时会提示找不到netron
服务配置文件
文件名:StartNetronWhenPowerOn.service
配置文件中引用了上述脚本(Netron8080.sh)
[Unit]
Description=open_netron_when_power_on
After=network.target
[Service]
User=username1 #使用指定用户执行服务
Type=simple
ExecStart=/home/username1/StartNetron/Netron8080.sh #服务的主进程
ExecReload=/home/username1/StartNetron/Netron8080.sh
Restart=always #不管是什么退出原因,总是重启
RestartSec=2 #设置在重启服务前暂停多长时间
StartLimitInterval=2 #启动时间的最大间隔
StartLimitBurst=10 #启动的最大次数限制,超过后停止继续重启
[Install]
WantedBy=multi-user.target
执行脚本
该脚本只需要运行一次,用来配置
脚本名称:run.sh
#! /bin/bash
# 将service文件拷贝到指定目录
sudo cp -r StartNetronWhenPowerOn.service /lib/systemd/system/
# 将service文件建立软链接
sudo ln -s /lib/systemd/system/StartNetronWhenPowerOn.service /etc/systemd/system/StartNetronWhenPowerOn.service
# 重载所有修改过的配置文件
sudo systemctl daemon-reload
# 重启服务
sudo systemctl restart StartNetronWhenPowerOn.service
# 列出配置文件状态
sudo systemctl list-unit-files | grep StartNetronWhenPowerOn.service
# 启动
sudo systemctl start StartNetronWhenPowerOn.service
# 将服务添加到系统自启动项中
sudo systemctl enable StartNetronWhenPowerOn.service
# 使用systemctl命令来查看服务的状态
sudo systemctl status StartNetronWhenPowerOn.service
# 查看服务日志
sudo journalctl -f -u StartNetronWhenPowerOn.service
执行脚本的返回" Serving at http://192.168.0.2:8080"即表示成功。
# 列出配置文件状态
# sudo systemctl list-unit-files | grep StartNetronWhenPowerOn.service
StartNetronWhenPowerOn.service enabled enabled
# 使用systemctl命令来查看服务的状态
# sudo systemctl status StartNetronWhenPowerOn.service
● StartNetronWhenPowerOn.service - open_netron_when_power_on
Loaded: loaded (/lib/systemd/system/StartNetronWhenPowerOn.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2023-12-13 00:58:09 CST; 779ms ago
Main PID: 3721 (Netron8080.sh)
Tasks: 4 (limit: 13905)
Memory: 9.2M
CPU: 32ms
CGroup: /system.slice/StartNetronWhenPowerOn.service
├─3721 /bin/bash /home/username1/StartNetron/Netron8080.sh
├─3725 /usr/bin/python3 /home/username1/.local/bin/netron --host 192.168.0.2 -p 8080 -b
└─3726 sleep 2
12月 13 00:58:09 xxxx systemd[1]: Started open_netron_when_power_on.
12月 13 00:58:09 xxxx Netron8080.sh[3721]:
12月 13 00:58:09 xxxx Netron8080.sh[3721]: open netron
12月 13 00:58:09 xxxx Netron8080.sh[3722]: 20**年 **月 **日 星期三 00:58:09 CST
12月 13 00:58:09 xxxx Netron8080.sh[3721]: netron --host 192.168.0.2 -p 8080 -b &
12月 13 00:58:09 xxxx Netron8080.sh[3725]: Serving at http://192.168.0.2:8080