Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

RedHat 下交換兩張網卡邏輯名稱的 shell 腳本

實驗環境常需要把 eth0 與 eth1 對調,手動改檔容易出錯,寫成腳本會省事很多。

#!/bin/bash

# this script will change your network card logic name!
# copy this script to /bin, named changnet.sh
# chmod +x /bin/changnet.sh
# usage: changnet.sh firstcardnumber secondcardnumber
# create date: 2010/8/18

# stop nic
ifdown eth$1
ifdown eth$2

# rename network card configure file
cd /etc/sysconfig/network-scripts
sed -i -e "s/eth$1/eth$2/" ifcfg-eth$1
sed -i -e "s/eth$2/eth$1/" ifcfg-eth$2

mv ifcfg-eth$1 ifcfg-eth$2.tmp
mv ifcfg-eth$2 ifcfg-eth$1
mv ifcfg-eth$2.tmp ifcfg-eth$2

# switch alias in modprobe.conf
DRIVER1=`grep eth$1 /etc/modprobe.conf | awk '{print $3}'`
DRIVER2=`grep eth$2 /etc/modprobe.conf | awk '{print $3}'`

if [ $DRIVER1 != $DRIVER2 ]
then
sed -e "/alias eth$1/d" -e "/alias eth$2/d" /etc/modprobe.conf > /etc/modprobe.conf.tmp.1
echo "alias eth$1 $DRIVER2" >> /etc/modprobe.conf.tmp.1
echo "alias eth$2 $DRIVER1" >> /etc/modprobe.conf.tmp.1
rm /etc/modprobe.conf
mv /etc/modprobe.conf.tmp.1 /etc/modprobe.conf
else
:
fi

把上述內容存成 changnet.sh 並加上執行權限,用法為 changnet.sh 0 1,即可把 eth0 與 eth1 對調。

腳本邏輯包含三件事:先關閉兩張網卡、交換 ifcfg 檔內容與檔名、最後在 modprobe.conf 中對調 alias 與驅動對應(僅在兩張卡驅動不同時才需要處理)。執行完重啟網路服務即可生效。提醒:執行前請先備份 /etc/sysconfig/network-scripts 與 /etc/modprobe.conf,並確認你是透過其他連線(例如 console 或第三方 session)操作,否則網路中斷後可能再也連不回去。

Copyright © Linux教程網 All Rights Reserved