Network-Interface

自動檢測網路介面卡,network init.d

  • May 22, 2022

我已經根據本書建構了我的 LFS linux ,它工作正常,網路介面卡也在工作。即使它使用dhcpcd服務自動配置IP。

根據那本書的第9章,有一個文件叫做

/etc/sysconfig/ifconfig.eth0 問題是,如果我正在使用wlan0,我是否需要手動修改配置文件或將 eth0 重命名為 wlan0 每次更改網路介面卡,我希望它會自動檢測到

這裡是由 LFS 書籍生成的初始化網路腳本,/etc/init.d/network/etc/sysconfig/ifconfig.*

### BEGIN INIT INFO
# Provides:            $network
# Required-Start:      $local_fs localnet swap
# Should-Start:        $syslog firewalld iptables nftables
# Required-Stop:       $local_fs localnet swap
# Should-Stop:         $syslog firewalld iptables nftables
# Default-Start:       3 4 5
# Default-Stop:        0 1 2 6
# Short-Description:   Starts and configures network interfaces.
# Description:         Starts and configures network interfaces.
# X-LFS-Provided-By:   LFS
### END INIT INFO

case "${1}" in
  start)
     # Start all network interfaces
     for file in /etc/sysconfig/ifconfig.*
     do
        interface=${file##*/ifconfig.}

        # Skip if $file is * (because nothing was found)
        if [ "${interface}" = "*" ]; then continue; fi

        /sbin/ifup ${interface}
     done
     ;;

  stop)
     # Unmount any network mounted file systems
      umount --all --force --types nfs,cifs,nfs4

     # Reverse list
     net_files=""
     for file in  /etc/sysconfig/ifconfig.*
     do
        net_files="${file} ${net_files}"
     done

     # Stop all network interfaces
     for file in ${net_files}
     do
        interface=${file##*/ifconfig.}

        # Skip if $file is * (because nothing was found)
        if [ "${interface}" = "*" ]; then continue; fi

        # See if interface exists
        if [ ! -e /sys/class/net/$interface ]; then continue; fi

        # Is interface UP?
        ip link show $interface 2>/dev/null | grep -q "state UP"
        if [ $? -ne 0 ];  then continue; fi

        /sbin/ifdown ${interface}
     done
     ;;

  restart)
     ${0} stop
     sleep 1
     ${0} start
     ;;

  *)
     echo "Usage: ${0} {start|stop|restart}"
     exit 1
     ;;
esac

exit 0

# End network

通過閱讀腳本,很明顯它會處理所有/etc/sysconfig/ifconfig.*文件:

  start)
     # Start all network interfaces
     for file in /etc/sysconfig/ifconfig.*
     do
        interface=${file##*/ifconfig.}

該腳本將從文件名中選擇要配置的介面名稱,因此您只需分別編寫您想要的eth0設置和您想要/etc/sysconfig/ifconfig.eth0的設置。wlan0``/etc/sysconfig/ifconfig.wlan0

另外,請注意,對於無線網路介面(如wlan0),您很可能還需要安裝和配置wpa_supplicant, 以處理現代形式的無線網路安全。

能夠閱讀其他人編寫的 shell 腳本對於 Linux 系統管理員來說是一項寶貴的技能。有時你可能需要閱讀一個腳本來驗證它是否真的做了它聲稱做的事情;有時您可能需要弄清楚腳本實際上做了什麼才能解決某些問題,或者因為可用的文件不夠詳細。

引用自:https://unix.stackexchange.com/questions/703442