ubuntu 双网卡建网桥脚本实现

#!/bin/bash

interface1=`ls /sys/class/net|grep en|awk 'NR==1{print}'`
interface2=`ls /sys/class/net|grep en|awk 'NR==2{print}'`

interfaces_file="/etc/network/interfaces"


while getopts "i:g:b:" opt; do
    case $opt in
        i)
            ip=$OPTARG
            ;;
        g)
            gateway=$OPTARG
            ;;
        b) 
            broadcast=$OPTARG
            ;;
        \?)
            ;;
    esac
done

echo $ip
echo $gateway
echo $broadcast

function set_bridge(){
     #写网卡配置文件
     cat > "$interfaces_file" <<EOF
auto lo br0
iface lo inet loopback
auto $interface1
iface $interface1 inet manual
auto $interface2
iface $interface2 inet manual
iface br0 inet static
bridge_ports $interface1 $interface2
address $ip
broadcast $broadcast
netmask 255.255.255.0
gateway $gateway
EOF


sudo /etc/init.d/networking restart

 #检查ip地址是否设置成功
    res=`ip addr show br0 |grep -c "$ip"`
    if [ "$res" -eq 0 ];then
        echo "ip地址设置失败" >&2
        return 254
    fi
    
#检查默认路由是不是gateway
    res=`ip route |grep -c "default\s*via\s*$gateway\s*dev\s*br0"`
    if [ "$res" -eq 0 ];then
        echo "网关设置失败" >&2
        return 253
    fi
    return 0
}

    set_bridge

执行格式:

./set_bridge.sh -i 192.168.4.147 -g 192.168.4.1 -b 192.168.4.255

结果:

 

weifeng@weifeng-ThinkPad-E470:~$ ifconfig
br0 Link encap:以太网 硬件地址 00:0e:c6:d2:24:89
inet 地址:192.168.4.147 广播:192.168.4.255 掩码:255.255.255.0
inet6 地址: fe80::20e:c6ff:fed2:2489/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 跃点数:1
接收数据包:455 错误:0 丢弃:0 过载:0 帧数:0
发送数据包:93 错误:0 丢弃:0 过载:0 载波:0
碰撞:0 发送队列长度:1000
接收字节:46287 (46.2 KB) 发送字节:12383 (12.3 KB)

enp4s0 Link encap:以太网 硬件地址 c8:5b:76:96:54:8d
UP BROADCAST MULTICAST MTU:1500 跃点数:1
接收数据包:2991 错误:0 丢弃:1 过载:0 帧数:0
发送数据包:106 错误:0 丢弃:47 过载:0 载波:0
碰撞:0 发送队列长度:1000
接收字节:361624 (361.6 KB) 发送字节:14387 (14.3 KB)

enx000ec6d22489 Link encap:以太网 硬件地址 00:0e:c6:d2:24:89
UP BROADCAST RUNNING MULTICAST MTU:1500 跃点数:1
接收数据包:186715 错误:0 丢弃:41 过载:0 帧数:0
发送数据包:5115 错误:0 丢弃:0 过载:0 载波:0
碰撞:0 发送队列长度:1000
接收字节:20149201 (20.1 MB) 发送字节:533581 (533.5 KB)

 

posted @ 2017-10-10 15:25  Oops!#  阅读(619)  评论(0编辑  收藏  举报