本文目录导读:

我来为您介绍几种不同操作系统下的IP配置切换脚本。
Windows 系统 - PowerShell 脚本
基础版 - 切换静态IP和DHCP
# Switch-NetworkConfig.ps1
param(
[Parameter(Mandatory=$true)]
[ValidateSet("Static", "DHCP")]
[string]$Mode,
[string]$IPAddress = "192.168.1.100",
[string]$SubnetMask = "255.255.255.0",
[string]$DefaultGateway = "192.168.1.1",
[string]$DNSServer = "8.8.8.8"
)
$AdapterName = (Get-NetAdapter | Where-Object {$_.Status -eq "Up"})[0].Name
if ($Mode -eq "Static") {
# 设置为静态IP
Write-Host "正在设置静态IP..." -ForegroundColor Yellow
# 移除原有配置
Remove-NetIPAddress -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
# 设置新IP
New-NetIPAddress -InterfaceAlias $AdapterName `
-IPAddress $IPAddress `
-PrefixLength 24 `
-DefaultGateway $DefaultGateway
# 设置DNS
Set-DnsClientServerAddress -InterfaceAlias $AdapterName `
-ServerAddresses ($DNSServer, "8.8.4.4")
Write-Host "静态IP设置完成!" -ForegroundColor Green
Write-Host "IP: $IPAddress" -ForegroundColor Cyan
Write-Host "子网掩码: 255.255.255.0" -ForegroundColor Cyan
Write-Host "网关: $DefaultGateway" -ForegroundColor Cyan
} elseif ($Mode -eq "DHCP") {
# 设置为DHCP
Write-Host "正在切换到DHCP..." -ForegroundColor Yellow
Set-NetIPInterface -InterfaceAlias $AdapterName -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceAlias $AdapterName -ResetServerAddresses
# 更新IP
ipconfig /renew
Write-Host "DHCP模式设置完成!" -ForegroundColor Green
# 显示当前IP
$ipInfo = Get-NetIPAddress -InterfaceAlias $AdapterName -AddressFamily IPv4
Write-Host "当前IP地址: $($ipInfo.IPAddress)" -ForegroundColor Cyan
}
配置文件版本
配置文件 config.json:
{
"profiles": {
"office": {
"ip": "192.168.1.100",
"subnet": "24",
"gateway": "192.168.1.1",
"dns": ["8.8.8.8", "8.8.4.4"]
},
"home": {
"dhcp": true
},
"dmz": {
"ip": "10.0.0.50",
"subnet": "16",
"gateway": "10.0.0.1",
"dns": ["10.0.0.1"]
}
}
}
高级脚本:
# Advanced-IP-Switcher.ps1
param(
[Parameter(Mandatory=$true)]
[string]$Profile
)
$ConfigFile = "config.json"
$ConfigPath = Join-Path $PSScriptRoot $ConfigFile
# 检查配置文件
if (-not (Test-Path $ConfigPath)) {
Write-Error "配置文件不存在:$ConfigPath"
exit 1
}
# 读取配置
$Config = Get-Content $ConfigPath | ConvertFrom-Json
# 检查子网格式转换
function Convert-SubnetToPrefix {
param([string]$Subnet)
$subnets = @{
"255.255.255.0" = "24"
"255.255.255.128" = "25"
"255.255.255.192" = "26"
"255.255.255.224" = "27"
"255.255.255.240" = "28"
"255.255.255.248" = "29"
"255.255.255.252" = "30"
"255.255.0.0" = "16"
"255.0.0.0" = "8"
}
if ($Subnet -match "^\d+$") {
return $Subnet
}
return $subnets[$Subnet]
}
# 获取当前网卡
$Adapter = Get-NetAdapter | Where-Object {$_.Status -eq "Up"} | Select-Object -First 1
if (-not $Adapter) {
Write-Error "未找到活动的网络适配器"
exit 1
}
$AdapterName = $Adapter.Name
Write-Host "使用网卡: $AdapterName" -ForegroundColor Yellow
# 显示可用配置
Write-Host "`n可用配置方案:" -ForegroundColor Cyan
foreach ($key in $Config.profiles.PSObject.Properties.Name) {
Write-Host "- $key" -ForegroundColor White
}
# 检查配置是否存在
if (-not ($Config.profiles.$Profile)) {
Write-Error "配置 '$Profile' 不存在"
exit 1
}
$ProfileConfig = $Config.profiles.$Profile
# 备份当前配置
Write-Host "正在备份当前配置..." -ForegroundColor Yellow
$backupIP = Get-NetIPAddress -InterfaceAlias $AdapterName -AddressFamily IPv4 -ErrorAction SilentlyContinue
$backupDNS = Get-DnsClientServerAddress -InterfaceAlias $AdapterName -ErrorAction SilentlyContinue
# 执行切换
try {
if ($ProfileConfig.dhcp -eq $true) {
# DHCP模式
Write-Host "切换到 DHCP 模式..." -ForegroundColor Yellow
Remove-NetIPAddress -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
Set-NetIPInterface -InterfaceAlias $AdapterName -Dhcp Enabled
Set-DnsClientServerAddress -InterfaceAlias $AdapterName -ResetServerAddresses
ipconfig /renew
Write-Host "成功切换到 DHCP 模式" -ForegroundColor Green
# 显示当前IP
$currentIP = Get-NetIPAddress -InterfaceAlias $AdapterName -AddressFamily IPv4 -ErrorAction SilentlyContinue
Write-Host "当前IP: $($currentIP.IPAddress)" -ForegroundColor Cyan
} else {
# 静态IP模式
Write-Host "切换到静态IP模式..." -ForegroundColor Yellow
# 移除现有配置
Remove-NetIPAddress -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetRoute -InterfaceAlias $AdapterName -Confirm:$false -ErrorAction SilentlyContinue
# 转换子网掩码
$PrefixLength = Convert-SubnetToPrefix $ProfileConfig.subnet
# 设置静态IP
New-NetIPAddress -InterfaceAlias $AdapterName `
-IPAddress $ProfileConfig.ip `
-PrefixLength $PrefixLength `
-DefaultGateway $ProfileConfig.gateway `
-ErrorAction Stop
# 设置DNS
if ($ProfileConfig.dns) {
Set-DnsClientServerAddress -InterfaceAlias $AdapterName `
-ServerAddresses $ProfileConfig.dns
}
Write-Host "成功配置网络" -ForegroundColor Green
Write-Host "IP: $($ProfileConfig.ip)" -ForegroundColor Cyan
Write-Host "子网前缀: /$PrefixLength" -ForegroundColor Cyan
Write-Host "网关: $($ProfileConfig.gateway)" -ForegroundColor Cyan
Write-Host "DNS: $($ProfileConfig.dns -join ', ')" -ForegroundColor Cyan
}
} catch {
Write-Error "配置失败: $($_.Exception.Message)"
# 恢复备份
Write-Host "正在恢复原始配置..." -ForegroundColor Yellow
if ($backupIP) {
New-NetIPAddress -InterfaceAlias $AdapterName `
-IPAddress $backupIP.IPAddress `
-PrefixLength $backupIP.PrefixLength `
-DefaultGateway $backupIP | Out-Null
}
if ($backupDNS) {
Set-DnsClientServerAddress -InterfaceAlias $AdapterName `
-ServerAddresses $backupDNS.ServerAddresses
}
}
使用示例
# 设置为静态IP .\Switch-NetworkConfig.ps1 -Mode Static -IPAddress 192.168.1.100 # 设置为DHCP .\Switch-NetworkConfig.ps1 -Mode DHCP # 使用配置文件 .\Advanced-IP-Switcher.ps1 -Profile office # 查看所有配置 $config = Get-Content config.json -Raw | ConvertFrom-Json $config.profiles.PSObject.Properties | Select-Object Name
Linux 系统 - Bash 脚本
#!/bin/bash
# ip-switcher.sh
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# 配置文件路径
CONFIG_FILE="$HOME/.network_configs"
# 检测系统类型
detect_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
else
OS=$(uname -s)
fi
# 检测网络管理器
if command -v nmcli &> /dev/null; then
NETWORK_MANAGER="nmcli"
elif command -v systemctl &> /dev/null && systemctl is-active networking &> /dev/null; then
NETWORK_MANAGER="networking"
else
NETWORK_MANAGER="manual"
fi
echo "检测到系统: $OS"
echo "网络管理器: $NETWORK_MANAGER"
}
# 获取接口信息
get_interfaces() {
if [ "$NETWORK_MANAGER" == "nmcli" ]; then
nmcli -t -f DEVICE,TYPE,STATE device status | grep -E ":ethernet:|:wifi:" | grep ":connected"
else
ip -o link show | grep -v "lo:" | awk -F': ' '{print $2}'
fi
}
# 配置静态IP (使用nmcli)
configure_static_nmcli() {
local interface=$1
local ip=$2
local gateway=$3
local dns1=$4
local dns2=$5
echo -e "${YELLOW}配置静态IP - 接口: $interface${NC}"
# 创建或修改连接
nmcli con mod "$interface" ipv4.addresses "$ip/24"
nmcli con mod "$interface" ipv4.gateway "$gateway"
nmcli con mod "$interface" ipv4.method manual
nmcli con mod "$interface" ipv4.dns "$dns1 $dns2"
# 重启连接
nmcli con down "$interface" 2>/dev/null || true
nmcli con up "$interface"
echo -e "${GREEN}静态IP配置完成${NC}"
echo "IP: $ip"
echo "网关: $gateway"
echo "DNS: $dns1, $dns2"
}
# 配置DHCP (使用nmcli)
configure_dhcp_nmcli() {
local interface=$1
echo -e "${YELLOW}配置DHCP - 接口: $interface${NC}"
nmcli con mod "$interface" ipv4.method auto
nmcli con mod "$interface" ipv4.dns ""
# 重启连接
nmcli con down "$interface" 2>/dev/null || true
nmcli con up "$interface"
# 获取新IP
sleep 2
local new_ip=$(ip -4 addr show "$interface" | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
echo -e "${GREEN}DHCP配置完成${NC}"
echo "IP: $new_ip"
}
# 保存配置文件
save_config() {
local name=$1
local ip=$2
local gateway=$3
local dns1=$4
local dns2=$5
local type=${6:-"static"}
# 创建配置目录
mkdir -p "$(dirname "$CONFIG_FILE")"
# 保存配置
echo "name=$name" >> "$CONFIG_FILE.tmp"
echo "type=$type" >> "$CONFIG_FILE.tmp"
echo "ip=$ip" >> "$CONFIG_FILE.tmp"
echo "gateway=$gateway" >> "$CONFIG_FILE.tmp"
echo "dns1=$dns1" >> "$CONFIG_FILE.tmp"
echo "dns2=$dns2" >> "$CONFIG_FILE.tmp"
echo "---" >> "$CONFIG_FILE.tmp"
mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
}
# 加载配置文件
load_config() {
if [ ! -f "$CONFIG_FILE" ]; then
echo -e "${RED}配置文件不存在${NC}"
return 1
fi
echo -e "${CYAN}可用配置:${NC}"
local current=""
local count=0
while IFS= read -r line; do
if [ "$line" == "---" ]; then
count=$((count + 1))
echo -e "${GREEN}[$count]${NC} $current"
current=""
elif [[ "$line" == name=* ]]; then
current="配置: ${line#name=}"
fi
done < "$CONFIG_FILE"
}
# 主菜单
show_menu() {
echo -e "\n${CYAN}====== IP配置切换工具 ======${NC}"
echo "1. 配置静态IP"
echo "2. 配置DHCP"
echo "3. 使用已保存配置"
echo "4. 保存当前配置"
echo "5. 显示当前网络状态"
echo "6. 退出"
echo -e "${CYAN}==========================${NC}"
echo -n "请选择: "
}
# 主函数
main() {
# 检测系统
detect_os
# 显示接口
echo -e "\n${CYAN}可用网络接口:${NC}"
if [ "$NETWORK_MANAGER" == "nmcli" ]; then
interfaces=$(nmcli -t -f DEVICE,TYPE device | grep -E ":ethernet:|:wifi:")
echo "$interfaces" | head -5
else
ip link show | grep -v "lo:" | awk -F': ' '{print $2}'
fi
while true; do
show_menu
read choice
case $choice in
1)
echo -n "接口名称: "; read interface
echo -n "IP地址: "; read ip
echo -n "网关: "; read gateway
echo -n "DNS服务器1: "; read dns1
echo -n "DNS服务器2: "; read dns2
if [ "$NETWORK_MANAGER" == "nmcli" ]; then
configure_static_nmcli "$interface" "$ip" "$gateway" "$dns1" "$dns2"
fi
;;
2)
echo -n "接口名称: "; read interface
if [ "$NETWORK_MANAGER" == "nmcli" ]; then
configure_dhcp_nmcli "$interface"
fi
;;
3)
load_config
echo -n "选择配置编号: "; read config_num
# 实现配置加载逻辑
;;
4)
echo -n "配置名称: "; read name
echo -n "IP地址: "; read ip
echo -n "网关: "; read gateway
echo -n "DNS服务器1: "; read dns1
echo -n "DNS服务器2: "; read dns2
save_config "$name" "$ip" "$gateway" "$dns1" "$dns2"
echo -e "${GREEN}配置已保存${NC}"
;;
5)
echo -e "\n${CYAN}当前网络状态:${NC}"
if command -v nmcli &> /dev/null; then
nmcli device status | head -5
fi
ip addr show | grep -E "^[0-9]|inet "
;;
6)
echo "退出"
exit 0
;;
*)
echo -e "${RED}无效选择${NC}"
;;
esac
done
}
# 运行主函数
main
使用说明
Windows脚本使用:
- 以管理员身份运行PowerShell
- 允许脚本执行:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
- 运行脚本
Linux脚本使用:
-
赋予执行权限:
chmod +x ip-switcher.sh
-
以root权限运行:
sudo ./ip-switcher.sh
注意事项:
- 管理员权限:大部分IP配置操作需要管理员/root权限
- 备份配置:切换前最好备份当前配置
- 网络连接:切换过程中可能会短暂断开网络
- 防火墙规则:如果使用防火墙,切换IP后可能需要更新规则
这些脚本覆盖了基本的IP配置切换需求,可以根据您的具体环境进行修改和扩展。