我正在尝试使用bash脚本中的wheezy在Raspberry Pi上实现以下场景。我这样做是因为我希望设备在DHCP处于联机状态时始终获得新的IP,同时我希望在DHCP脱机的情况下保留最后使用的IP。最重要的是,IP地址可能会改变,我有很多设备,所以简单地设置静态IP不是我的选择:
- 引导(不在脚本中;))
- 启用DHCP并尝试获取IP地址
- 检查我是否有一个
a)获得IP(DHCP成功)
- >将IP信息保存到文件
b)没有获得IP(DHCP失败)
- >这里什么都不做
- 根据文件
中的信息设置固定IP地址
现在重点是,如果我手动运行脚本,这非常棒,但是如果我让它在启动后自动运行,那么DHCP将失败但仍然会给我一个IP地址。当然我的脚本认为DHCP有一个ip地址,但它不是正确的!
sys.log告诉我:
dhclient: No DHCPOFFERS received.
dhclient: Trying recorded lease 192.xxx.xx.xx
ifplugd(eth0)[1602]: client: Trying recorded lease 192.xxx.xx.xx
现在的问题是:
脚本:
#!/bin/bash
echo Switch off Ethernet >> log.log
ifconfig eth0 down
echo Set DHCP mode for Ethernet >> log.log
ifconfig eth0 up
dhclient -r eth0
dhclient eth0
echo Now check if we got ip address >> log.log
countLines=$(ifconfig eth0 | grep "inet addr" | wc -l)
if [ $countLines -ne 0 ]; then
echo Found ip address via DHCP - Save it to ip.txt >> log.log
ifconfig eth0 | grep "inet addr" > ip.txt
echo Also save the resolv.conf - DNS settings >> log.log
cp /etc/resolv.conf dns.txt
#grep domain-name-servers /var/lib/dhcp/dhclient.eth0.leases | tail -1 > dns.txt
else
echo No new ip address - no DHCP online! Use the old settings instead... >> log.log
fi
echo Switch off DHCP - and release the current lease >> log.log
dhclient -r eth0
ipaddress=$(<ip.txt)
ipaddress=${ipaddress#*addr:}
ipaddress=${ipaddress% Bcast*}
broadcast=$(<ip.txt)
broadcast=${broadcast#*Bcast:}
broadcast=${broadcast% Mask*}
netmask=$(<ip.txt)
netmask=${netmask#*Mask:}
dnsserver=$(<dns.txt)
dnsserver=${dnsserver#*servers }
dnsserver=${dnsserver%;*}
echo Set static ip address now ip: $ipaddress, broadcast: $broadcast, netmask: $netmask... >> log.log
ifconfig eth0 $ipaddress broadcast $broadcast netmask $netmask
echo Set the nameserver >> log.log
cp dns.txt /etc/resolv.conf
真的很让我感到困惑的是,脚本在bash中运行,但在系统启动后自动启动!
答案 0 :(得分:2)
Ok Mate,
您的问题是您的脚本认为如果找不到DHCP,ifconfig将不会获得IP地址。
如果dhclient无法发现DHCP服务器,eth0
将获得169.254.*.*
地址(自我分配)
在运行dhclient之前,你需要保存你所拥有的东西。
EG。 OLDIP=ifconfig eth0 | sed ... Inet ... #come with your SED statement
然后继续:
dhclient eth0
If [$? !=0];then
Ifconfig eth0 $OLDIP $OLDMASK
我在手机上写字显然语法不正确。
希望有所帮助