问题:树莓派通过网线直连台式机上网,但是台式机没有dhcp功能,怎样避免每次要进去手动修改树莓派的网关?
方案一
可以在每次开启关闭网络的时候执行shell脚本 scritps.sh
/etc/network/interfaces 文件为网络配置文件
```
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
dns-nameservers 223.5.5.5 223.6.6.6
dns-nameservers 116.116.116.116
auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.111.1
dns-nameservers 114.114.114.114 116.116.116.116
pre-up iptables-restore < /etc/iptables
up bash -e /home/pi/set_ip_and_gw.sh
down bash -e /home/pi/test_down.sh
post-down bash -e /home/pi/test_post_down.sh
```
* 这里的 pre-up ,up,down,post-down为网卡启动的钩子
* pre-up 对应的为 网络启动之前执行脚本
* up 对应网络启动之后执行脚本
* down 网络关闭之间
* post-down 网络关闭之后
在这4个位置可以添加脚本程序可以正常执行,但是在/etc/network目录下面对应的
if-up.d if-down.d if-pre-up.d if-post-down.d 4个目录中添加脚本却无法执行
方案二
可以通过systemd来设置开机启动服务,来对每次开机时再网络开启之后执行一次脚本命令
debian 和ubuntu 以及centos7 都默认安装了systemd 来管理服务
在 /usr/lib/systemd/system 设置需要开机启动的服务
vim /usr/lib/systemd/system/do_something.service
[Unit]
Description=test networking
#Before=network.target
After=networking.service # 网络启动之后
[Service]
Type=oneshot # 执行一次
ExecStart=/bin/bash -e /home/pi/set_ip_and_gw.sh
KillSignal=SIGINT
[Install]
WantedBy=multi-user.target #多用户模式
systemctl enable do_something
这样每次开机都会在网络连接之后执行指定的脚本