2019-05-31 linux 使用 ip route 命令快速切换网关
程序员文章站
2022-03-03 21:01:25
...
工作中如果经常需要切换网关,可使用下面的脚本 方便切换
#!/bin/bash
# desc: change gateway in centos
# author: dbquan
ip_conf_file='/etc/sysconfig/network-scripts/ifcfg-eth0'
gw_arr=(1 2 3 205)
tips==$(echo ${gw_arr[@]} | sed "s/ /|/g")
# check gateway
check_gateway()
{
now_gw=`grep "^GATEWAY=" $ip_conf_file`
echo -e "\n===== now $now_gw ======\n"
echo "please input a gatway: $tips"
read in_gw
if [ ! "$in_gw" ] || [[ ${gw_arr[@]/$in_gw/} = ${gw_arr[@]} ]]; then
echo "[error:] please input gateway what you need to change to"
echo "usage: $0 $tips"
exit 1
fi
}
# check gateway by command
check_gateway()
{
now_gw=`ip route`
echo -e "\n===== now $now_gw ======\n"
echo "please input a gatway: $tips"
read in_gw
if [ ! "$in_gw" ] || [[ ${gw_arr[@]/$in_gw/} = ${gw_arr[@]} ]]; then
echo "[error:] please input gateway what you need to change to"
echo "usage: $0 $tips"
exit 1
fi
}
chg_gw_by_ip_route()
{
echo -e "start to change \nfrom: $now_gw\n to: GATEWAY=192.168.0.$in_gw"
#sudo ip r del default && \
# sudo ip route add default via "192.168.0.$in_gw"
# one line
sudo ip r replace default via "192.168.0.$in_gw"
if [ $? -eq 0 ]; then
echo "succ"
else
echo "fail"
fi
}
check_gateway && chg_gw_by_ip_route