|
|
硬件:树莓派 3B+
系统:fedora server 30 (Fedora-Server-armhfp-30-1.2-sda.raw)
需求原因:
考虑到带树莓派往返公司和家,网络ip段布局不同,故设置树莓派开机后通过 wlan0 使用DHCP 动态获取IP。
但这样可能无法知道当前的ip地址,无法远程连接。
故采取开机后自动执行脚本,发送当前ip到其他服务器,或发送邮件方式。
树莓派启动慢,急性的人,可以在未接显示器的情况下获取ip地址。
一.发送邮件方式:
这个比较方便,不用依赖其他服务器。
1.系统默认无法使用mail命令,需要安装sendmail 和 mailx,并开启服务
- dnf install sendmail mailx
- chkconfig sendmail on
- service sendmail restart
复制代码
2.使用脚本
[root@raspberry ~]# cat ip.sh
- mail1="test@qq.com"
- #ip=$(ifconfig wlan0 | grep -B 2 'b8:27:eb:e4:0e:8c' | head -1 |cut -d ' ' -f10)
- ip=$(ifconfig wlan0 |grep 'inet [0-9]\{1,3\}\.'|cut -d ' ' -f10)
- if [ "$ip" = '' ];then
- ip='Not find wlan0 , check raspberry pi'
- fi
- echo $ip | mail -s "raspberry ip:$ip" $mail1
复制代码
3.加入到开机启动 /etc/rc.d/rc.local中。
- /etc/rc.d/
- touch rc.local
- echo "#!/bin/bash" > rc.local
- echo "sh /root/ip.sh" >> rc.local
- chmod a+x rc.local
复制代码
修改/usr/lib/systemd/system/rc-local.service, 添加依赖服务(syslog/network-online):
- [Unit]
- Description=/etc/rc.d/rc.local Compatibility
- Documentation=man:systemd-rc-local-generator(8)
- ConditionFileIsExecutable=/etc/rc.d/rc.local
- After=syslog.target network.target network-online.target
- [Service]
- Type=forking
- ExecStart=/etc/rc.d/rc.local start
- TimeoutSec=0
- RemainAfterExit=yes
- GuessMainPID=no
复制代码
这样系统开机成功后或重启成功后时会自动发送ip邮件。
二、发送文件方式:
通过scp传送含有ip地址的文件到其他web服务器,这种办法需要有自己的服务器,还得打开相应的网址(自动刷新),用起来不是很方便。
三、事先知道树莓派的 mac 地址如 "f8:38:80:8f:d8:f7",通过ping 扫描指定网段,如 192.168.0.100 -192.168.0.120,
- for i in {100..120};do ping -c 2 -t 1 192.168.0.$i;done
- arp -a | grep "b8:27:eb:e4:e:8c" | cut -d '(' -f2 | cut -d ')' -f1
复制代码
四、客户端通过脚本访问正在开机中的树莓派
$cat pi.sh
- #!/bin/bash
- ip=''
- mac="b8:27:eb:e4:e:8c"
- while ((1))
- do
- ip=$(arp -a | grep "$mac" | cut -d '(' -f2 | cut -d ')' -f1)
- echo -n '.'
- if [ "$ip" = "" ];then
- for i in {100..120};do ping -c 2 -t 1 192.168.0.$i;done
- else
- result=$(ping -c 2 -t 1 $ip | grep 'ttl')
- if [ "$result" != "" ];then
- echo
- echo "$ip success"
- break
- fi
- fi
- done
- ssh -lroot $ip
复制代码 |
|