自动配置网络参数的脚本怎么写

wen 实用脚本 1

本文目录导读:

自动配置网络参数的脚本怎么写

  1. Windows 版本 (Batch/PowerShell)
  2. Linux 版本 (Bash)
  3. 使用说明
  4. 安全注意事项

我来帮你写一个自动配置网络参数的脚本,由于不同操作系统(Windows/Linux/Mac)的命令差异很大,我分别提供几个版本:

Windows 版本 (Batch/PowerShell)

Batch 脚本 (net_config.bat)

@echo off
chcp 65001 >nul网络参数自动配置工具
echo ========================================
echo      网络参数自动配置脚本
echo ========================================
:menu
echo.
echo 请选择操作:
echo 1. 配置静态IP
echo 2. 配置DHCP自动获取
echo 3. 查看当前网络配置
echo 4. 设置DNS
echo 5. 退出
echo.
set /p choice="请输入选项 (1-5): "
if "%choice%"=="1" goto static_ip
if "%choice%"=="2" goto dhcp
if "%choice%"=="3" goto view
if "%choice%"=="4" goto dns
if "%choice%"=="5" exit
goto menu
:static_ip
echo.
echo 当前可用的网络适配器:
netsh interface ip show interfaces
echo.
set /p nic="请输入网络适配器名称 (如: 以太网): "
set /p ip="请输入IP地址 (如: 192.168.1.100): "
set /p mask="请输入子网掩码 (如: 255.255.255.0): "
set /p gateway="请输入默认网关 (如: 192.168.1.1): "
echo.
echo 正在配置静态IP...
echo 适配器: %nic%
echo IP: %ip%
echo 掩码: %mask%
echo 网关: %gateway%
netsh interface ip set address "%nic%" static %ip% %mask% %gateway% 1
if %errorlevel% equ 0 (
    echo ✓ 配置成功!
) else (
    echo ✗ 配置失败!请检查参数
)
pause
goto menu
:dhcp
echo.
set /p nic="请输入网络适配器名称 (如: 以太网): "
echo 正在配置DHCP自动获取...
netsh interface ip set address "%nic%" dhcp
netsh interface ip set dns "%nic%" dhcp
if %errorlevel% equ 0 (
    echo ✓ DHCP配置成功!
) else (
    echo ✗ 配置失败!
)
pause
goto menu
:view
echo.
echo 当前网络配置:
ipconfig /all
pause
goto menu
:dns
echo.
set /p nic="请输入网络适配器名称 (如: 以太网): "
echo 常用DNS服务器:
echo 1. 阿里巴巴: 223.5.5.5
echo 2. 114DNS: 114.114.114.114
echo 3. 谷歌: 8.8.8.8
echo 4. 自定义
echo.
set /p dns_choice="请选择DNS (1-4): "
if "%dns_choice%"=="1" set dns=223.5.5.5
if "%dns_choice%"=="2" set dns=114.114.114.114
if "%dns_choice%"=="3" set dns=8.8.8.8
if "%dns_choice%"=="4" (
    set /p dns="请输入DNS地址: "
)
netsh interface ip set dns "%nic%" static %dns%
if %errorlevel% equ 0 (
    echo ✓ DNS配置成功!当前DNS: %dns%
) else (
    echo ✗ 配置失败!
)
pause
goto menu

PowerShell 脚本 (net_config.ps1)

# 网络配置脚本 - PowerShell版本
Write-Host "网络参数自动配置工具" -ForegroundColor Cyan
function Show-Menu {
    Write-Host "`n请选择操作:" -ForegroundColor Yellow
    Write-Host "1. 配置静态IP"
    Write-Host "2. 配置DHCP"
    Write-Host "3. 查看网络配置"
    Write-Host "4. 配置DNS"
    Write-Host "5. 退出"
}
function Get-NetAdapterName {
    Get-NetAdapter | Where-Object {$_.Status -eq "Up"} | Select-Object Name, InterfaceDescription
}
do {
    Show-Menu
    $choice = Read-Host "请输入选项"
    switch ($choice) {
        "1" {
            Write-Host "`n当前可用的网络适配器:" -ForegroundColor Green
            Get-NetAdapterName | Format-Table -AutoSize
            $nic = Read-Host "请输入适配器名称"
            $ip = Read-Host "请输入IP地址"
            $prefix = Read-Host "请输入子网前缀长度 (例如24)"
            $gateway = Read-Host "请输入默认网关"
            try {
                New-NetIPAddress -InterfaceAlias $nic -IPAddress $ip -PrefixLength $prefix -DefaultGateway $gateway
                Write-Host "静态IP配置成功!" -ForegroundColor Green
            } catch {
                Write-Host "配置失败: $_" -ForegroundColor Red
            }
        }
        "2" {
            Write-Host "`n当前可用的网络适配器:" -ForegroundColor Green
            Get-NetAdapterName | Format-Table -AutoSize
            $nic = Read-Host "请输入适配器名称"
            try {
                Set-NetIPInterface -InterfaceAlias $nic -Dhcp Enabled
                Set-DnsClientServerAddress -InterfaceAlias $nic -ResetServerAddresses
                Write-Host "DHCP配置成功!" -ForegroundColor Green
            } catch {
                Write-Host "配置失败: $_" -ForegroundColor Red
            }
        }
        "3" {
            Write-Host "`n当前网络配置:" -ForegroundColor Yellow
            Get-NetIPConfiguration | Format-List
            Read-Host "按回车继续"
        }
        "4" {
            Write-Host "`n当前可用的网络适配器:" -ForegroundColor Green
            Get-NetAdapterName | Format-Table -AutoSize
            $nic = Read-Host "请输入适配器名称"
            Write-Host "`n常用DNS:" -ForegroundColor Yellow
            Write-Host "1. 阿里巴巴: 223.5.5.5, 223.6.6.6"
            Write-Host "2. 114DNS: 114.114.114.114"
            Write-Host "3. 谷歌: 8.8.8.8, 8.8.4.4"
            Write-Host "4. 自定义"
            $dnsChoice = Read-Host "请选择"
            switch ($dnsChoice) {
                "1" { $dnsServers = "223.5.5.5", "223.6.6.6" }
                "2" { $dnsServers = "114.114.114.114" }
                "3" { $dnsServers = "8.8.8.8", "8.8.4.4" }
                "4" { 
                    $dns1 = Read-Host "请输入首选DNS"
                    $dns2 = Read-Host "请输入备用DNS (可选)"
                    $dnsServers = @($dns1)
                    if ($dns2) { $dnsServers += $dns2 }
                }
            }
            try {
                Set-DnsClientServerAddress -InterfaceAlias $nic -ServerAddresses $dnsServers
                Write-Host "DNS配置成功!" -ForegroundColor Green
            } catch {
                Write-Host "配置失败: $_" -ForegroundColor Red
            }
        }
        "5" { break }
    }
} while ($choice -ne "5")

Linux 版本 (Bash)

#!/bin/bash
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
show_menu() {
    echo -e "${YELLOW}========================================${NC}"
    echo -e "${BLUE}      网络参数自动配置脚本${NC}"
    echo -e "${YELLOW}========================================${NC}"
    echo "1. 配置静态IP (netplan)"
    echo "2. 配置静态IP (ifconfig)"
    echo "3. 配置DHCP"
    echo "4. 查看当前网络配置"
    echo "5. 配置DNS"
    echo "6. 重启网络"
    echo "7. 退出"
    echo -e "${YELLOW}========================================${NC}"
}
configure_static_netplan() {
    echo "当前网络接口:"
    ip link show | grep -v lo | grep -E "^[0-9]" | awk '{print $2}' | sed 's/://'
    read -p "请输入网卡名称 (如 eth0): " interface
    read -p "请输入IP地址 (如 192.168.1.100): " ip
    read -p "请输入子网掩码 (如 255.255.255.0): " mask
    read -p "请输入网关 (如 192.168.1.1): " gateway
    # 计算CIDR表示法
    cidr_prefix=$(echo $mask | awk -F. '{
        split($0, octets);
        for(i=1; i<=4; i++) {
            octet = octets[i] + 0
            while(octet > 0) {
                prefix += octet % 2
                octet = int(octet / 2)
            }
        }
        print prefix
    }')
    # 创建netplan配置文件
    sudo tee /etc/netplan/01-netcfg.yaml > /dev/null << EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    $interface:
      dhcp4: no
      addresses:
        - $ip/$cidr_prefix
      gateway4: $gateway
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]
EOF
    sudo netplan apply
    echo -e "${GREEN}✓ 网络配置已应用${NC}"
}
configure_static_ifconfig() {
    echo "当前网络接口:"
    ifconfig -a | grep -E "^[a-z]" | awk '{print $1}'
    read -p "请输入网卡名称: " interface
    read -p "请输入IP地址: " ip
    read -p "请输入子网掩码: " mask
    read -p "请输入网关: " gateway
    # 临时配置(重启失效)
    sudo ifconfig $interface $ip netmask $mask up
    sudo route add default gw $gateway $interface
    echo -e "${GREEN}✓ 临时配置已应用(重启后失效)${NC}"
}
configure_dhcp() {
    echo "当前网络接口:"
    ip link show | grep -v lo | grep -E "^[0-9]" | awk '{print $2}' | sed 's/://'
    read -p "请输入网卡名称: " interface
    # DHCP配置
    sudo dhclient $interface
    echo -e "${GREEN}✓ DHCP配置完成${NC}"
}
view_config() {
    echo "IP地址信息:"
    ip addr show | grep -E "inet "
    echo ""
    echo "路由表:"
    ip route show
    echo ""
    echo "DNS配置:"
    cat /etc/resolv.conf 2>/dev/null || echo "无法读取resolv.conf"
}
configure_dns() {
    echo "当前DNS服务器:"
    cat /etc/resolv.conf 2>/dev/null | grep nameserver
    echo -e "${YELLOW}选择DNS服务器:${NC}"
    echo "1. 阿里巴巴: 223.5.5.5"
    echo "2. 114DNS: 114.114.114.114"
    echo "3. 谷歌: 8.8.8.8"
    echo "4. 自定义"
    read -p "请选择: " dns_choice
    case $dns_choice in
        1) dns="223.5.5.5" ;;
        2) dns="114.114.114.114" ;;
        3) dns="8.8.8.8" ;;
        4) read -p "请输入DNS地址: " dns ;;
        *) echo -e "${RED}无效选项${NC}"; return ;;
    esac
    # 临时修改DNS
    echo "nameserver $dns" | sudo tee /etc/resolv.conf
    echo -e "${GREEN}✓ DNS已设为: $dns${NC}"
}
restart_network() {
    echo "重启网络服务..."
    sudo systemctl restart networking 2>/dev/null || sudo service networking restart
    echo -e "${GREEN}✓ 网络服务已重启${NC}"
}
# 主程序循环
while true; do
    show_menu
    read -p "请选择操作: " choice
    case $choice in
        1) configure_static_netplan ;;
        2) configure_static_ifconfig ;;
        3) configure_dhcp ;;
        4) view_config ;;
        5) configure_dns ;;
        6) restart_network ;;
        7) echo -e "${GREEN}再见!${NC}"; exit 0 ;;
        *) echo -e "${RED}无效选项,请重试${NC}" ;;
    esac
    echo ""
    read -p "按回车继续..."
done

使用说明

Windows:

  1. Batch脚本: 以管理员身份运行 net_config.bat
  2. PowerShell脚本:
    # 先执行(一次即可)
    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
    # 然后运行
    .\net_config.ps1

Linux:

# 赋予执行权限
chmod +x net_config.sh
# 运行(可能需要sudo)
sudo ./net_config.sh

安全注意事项

⚠️ 重要提示

  • 这些脚本需要管理员/root权限才能修改网络设置
  • 远程连接时请谨慎使用,错误的配置可能导致断开连接
  • 建议先在测试环境验证
  • 生产环境建议使用配置管理工具(如Ansible)

如果需要更具体的功能(如:批量配置多台设备、从配置文件读取参数等),请告诉我具体需求!

抱歉,评论功能暂时关闭!