問題:樹莓派通過網線直連臺式機上網,但是臺式機沒有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
這樣每次開機都會在網絡連接之後執行指定的腳本