linux - 如果 dhcp 失败,设置保存的静态 IP 地址

标签 linux bash networking ip dhcp

我正在尝试使用 bash 脚本在 Raspberry Pi 上实现以下场景。我这样做是因为我希望设备在 DHCP 在线时始终获得新 IP,同时我希望它在 DHCP 离线时保留上次使用的 IP。最重要的是,IP 地址可能会改变,而且我有很多设备,所以简单地设置静态 IP 不是我的选择:

  • Boot (not in the script ;) )
  • Switch on DHCP and try to get IP address
  • Check if I got one

   a) Got IP (DHCP successful)

       -> Save IP infos to file

   b) Didn't get IP (DHCP failed)

       -> Do nothing here

  • Set fixed IP address based on the information in the file

现在的重点是,如果我手动运行脚本,这会非常棒,但如果我让它在启动后自动运行,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

现在的问题是:

  • 我可以停用 DHCP 客户端服务(我认为它是带有 dhclient 的 ifplugd)给我那个假 IP 地址吗?
  • 或者我是否可以通过其他方式检测到 DHCP 请求未成功(并放弃虚假地址)?

脚本:

#!/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 中运行,但在系统启动后自动启动后却没有运行!

最佳答案

好的伙计,

您的问题是您的脚本认为如果未找到 DHCP,ifconfig 将无法获得 IP 地址。

如果 dhclient 无法发现 DHCP 服务器,eth0 将获得 169.254.*.* 地址(自行分配)

在运行 dhclient 之前,您需要保存您得到的内容。

例如。 OLDIP=ifconfig eth0 | sed ... Inet ... #come with your SED statement

然后你继续:

dhclient eth0
If [$? !=0];then
    Ifconfig eth0 $OLDIP $OLDMASK

我是用手机写的,所以显然语法不正确。

希望对你有帮助

关于linux - 如果 dhcp 失败,设置保存的静态 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397143/

相关文章:

linux - Bash脚本函数返回值问题

c++ - 如何从我的 Windows 笔记本电脑轻松设计基于 Linux 的终端应用程序?

python - 如何在 Xvfb 中运行 Selenium?

bash - 如何在不进入容器的情况下运行docker容器

linux - mkdir 中的详细选项是什么?

c++ - 如何在不先启动 IE 的情况下使网络在我的 WinCE 应用程序中工作?

php - 为什么使用 PHP 上传文件时 Linux 会创建没有扩展名的临时文件,而 Windows 会创建带有扩展名的临时文件?

javascript - execFile Node.js - 找不到 Shell 脚本

sockets - 接收缓冲区的限制

c++ - 修改 const char* 数组的快速方法