配置双IP

root@pve:/opt/shell-script# cat /etc/network/interfaces
auto lo
iface lo inet loopback
source /etc/network/interfaces.d/*.cfg

iface enp0s31f6 inet manual

auto vmbr0
iface vmbr0 inet static
        address 192.168.9.231/24
        up ip addr add 192.168.157.231/24 dev vmbr0
        #gateway 192.168.9.1
        bridge-ports enp0s31f6
        bridge-stp off
        bridge-fd 0

auto vmbr1
iface vmbr1 inet static
    address 192.168.122.1
    netmask 255.255.255.0
    bridge_ports none
    bridge_stp off
    bridge_fd 0
    post-up echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up echo 1 > /proc/sys/net/ipv4/conf/vmbr1/proxy_arp
    post-up iptables -t nat -A POSTROUTING -s '192.168.122.0/24' -o vmbr0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s '192.168.122.0/24' -o vmbr0 -j MASQUERADE

移动pc,pve在不同网络环境切换_ip切换

脚本替换网关,然后设置开机执行

root@pve:/opt/shell-script# cat ip_config.sh-back 
#!/bin/bash
set -e
# 家庭网络配置
HOME_GATEWAY="192.168.9.1"

# 公司网络配置
WORK_GATEWAY="192.168.157.1"

# 网络接口名称
IFACE="enp0s31f6"

# 检测网络环境的函数
detect_network() {
    if ping -c 1 -W 1 $HOME_GATEWAY >/dev/null 2>&1; then
        echo "home"
    elif ping -c 1 -W 1 $WORK_GATEWAY >/dev/null 2>&1; then
        echo "work"
    else
        echo "unknown"
    fi
}

# 配置网络的函数
configure_network() {
    local network=$1
    case $network in
        home)
            ip addr flush dev $IFACE
            ip route replace default via $HOME_GATEWAY
            echo "已切换至家庭网络"
            ;;
        work)
            ip addr flush dev $IFACE
            ip route replace default via $WORK_GATEWAY
            echo "已切换至公司网络"
            ;;
        *)
            echo "无法识别的网络环境"
            ;;
    esac
}

while true; do
    CURRENT_NETWORK=$(detect_network)
    
    if [[ $CURRENT_NETWORK == "home" ]] || [[ $CURRENT_NETWORK == "work" ]]; then
        configure_network $CURRENT_NETWORK
        echo "已配置 $CURRENT_NETWORK 网络"
        break
    else
        echo "网络未知,等待5秒后重试"
        sleep 5
    fi
done

开机启动

crontab -e -u root
添加:
@reboot /opt/shell-script/ip_config.sh

在 root 用户的 crontab 中添加@reboot标签,这样在每次开机时都会执行该脚本