【脚本】 【Linux】启动所有网卡

该bash脚本用于遍历并启动所有网卡接口,通过ifconfig命令获取接口名并执行ifconfig[接口名]up。将脚本置于/lib/ifupdown/目录下,赋予可执行权限,并创建systemd服务文件。服务文件定义在/lib/systemd/system/ifup_ethernets.service中,设置为在network.target之后启动。最后,通过systemctl启用服务并使其在开机时自动运行。

ifup_ethernets.sh
方法一

#!/bin/bash
 
# 过滤网卡名称
ethList=(`ifconfig -a | grep ^[a-z] | awk -F: '{print $1}'`)
for ((i=0; i<${#ethList[@]}; i++))
do
    echo 启动网卡 ${ethList[$i]} ...
    ifconfig ${ethList[$i]} up
done

方法二

#!/bin/bash

# 等待udev完成设备初始化
udevadm settle --timeout=5
# 获取所有物理网卡
interfaces=()
while IFS= read -r line; do
    interfaces+=("$line")
done < <(find /sys/class/net -type l -name 'e*' -printf '%f\n')
# 遍历启动所有网卡
for iface in "${interfaces[@]}"; do
    # 跳过虚拟网卡
    [[ -e "/sys/devices/virtual/net/$iface" ]] && continue
    # 启动物理网卡
    echo "Activating interface: $iface"
    ip link set "$iface" up
    # 等待网卡实际激活
    timeout=5
    while [[ $timeout -gt 0 ]]; do
        state=$(cat "/sys/class/net/$iface/operstate")
        [[ "$state" == "up" || "$state" == "unknown" ]] && break
        sleep 1
        ((timeout--))
    done
done

用法: ./ifup_ethernets.sh
设置系统开机自启:

  • 把文件ifup_ethernets.sh放在目录/lib/ifupdown/下,chmod +x ifup_ethernets.sh赋予可执行权限。
  • 创建服务文件/lib/systemd/system/ifup_ethernets.service

方法一

[Unit]
Description=ifup all ethernets
DefaultDependencies=no
After=network.target
 
[Service]
Type=simple
KillMode=none
ExecStart=/lib/ifupdown/ifup_ethernets.sh
 
[Install]
WantedBy=network.target

方法二

[Unit]
Description=Bring up all ethernet interfaces
After=systemd-udevd.service
Before=network.target
Wants=systemd-udevd.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/lib/ifupdown/ifup_ethernets.sh
TimeoutStartSec=30
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
  • 启动服务
systemctl enable ifup_ethernets
systemctl daemon-reload
systemctl start ifup_ethernets
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值