将QQ放入Network Namespace

2024-06-14
#linux #namespace
nsname=qq
outer_interface=qq-veth
inner_interface=qveth1
inner_mac=12:e1:7d:f8:a2:a4

if [[ ! -e /var/run/netns/$nsname ]]; then
    ip netns add $nsname
fi
if ! ip address show $outer_interface > /dev/null 2>&1 || ! ip -n $nsname address show $inner_interface > /dev/null 2>&1; then
    if ip address show $outer_interface > /dev/null 2>&1; then
        ip link del $outer_interface
    fi
    if ip -n $nsname address show $inner_interface > /dev/null 2>&1; then
        ip -n $nsname link del $inner_interface
    fi
    if ip address show $inner_interface > /dev/null 2>&1; then
        ip link del $inner_interface
    fi
    ip link add $outer_interface type veth peer name $inner_interface
    ip link set $inner_interface netns $nsname

    ip addr add 192.168.67.1/24 dev $outer_interface
    ip -n $nsname addr add 192.168.67.2/24 dev $inner_interface
    ip -n $nsname link set dev $inner_interface address $inner_mac
    ip -n $nsname route add default via 192.168.67.1 dev $inner_interface

    ip link set $outer_interface up
    ip -n $nsname link set $inner_interface up
fi

if ! iptables -t nat -C POSTROUTING -s 192.168.67.0/24 -j MASQUERADE > /dev/null 2>&1; then
    iptables -t nat -A POSTROUTING -s 192.168.67.0/24 -j MASQUERADE
fi

ip netns exec qq sudo -u richar bash -c "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS exec qq"