在 Windows Server 2022 的 Server Core 或 Nano Server 等无图形界面(GUI)版本中,网络与防火墙配置完全依赖命令行工具。以下是基于 PowerShell 和传统 CMD 的高效操作指南,符合生产环境最佳实践。
一、网络配置核心方法
1. 查看当前网络状态
# 查看所有网络接口信息(推荐首选)
Get-NetAdapter | Format-Table Name, Status, LinkSpeed, IPAddress -AutoSize
# 查看详细 IP 配置
Get-NetIPConfiguration
2. 配置静态 IP 地址(PowerShell 方式)
# 示例:为 "Ethernet" 接口配置静态 IP
Set-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress "192.168.1.100" -PrefixLength 24 -DefaultGateway "192.168.1.1"
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("8.8.8.8", "114.114.114.114")
注意:
-PrefixLength对应子网掩码位数(如 24 表示 255.255.255.0),-DefaultGateway必须与 IP 同网段。
3. 传统 CMD 备用方案(netsh)
# 设置静态 IP
netsh interface ip set address "Ethernet" static 192.168.1.100 255.255.255.0 192.168.1.1
# 设置 DNS
netsh interface ip set dns "Ethernet" static 8.8.8.8 primary
netsh interface ip add dns "Ethernet" 114.114.114.114 index=2
二、防火墙配置关键操作
1. 查看防火墙规则
# 列出所有入站/出站规则
Get-NetFirewallRule | Format-Table DisplayName, Direction, Action, Enabled -AutoSize
# 按服务名称筛选规则
Get-NetFirewallRule -DisplayName "*HTTP*" | Format-List
2. 启用/禁用特定规则
# 启用 HTTP 服务规则
Enable-NetFirewallRule -DisplayName "HTTP" -Direction Inbound
# 禁用远程桌面规则(谨慎操作)
Disable-NetFirewallRule -DisplayName "Remote Desktop - User Mode (TCP-In)"
3. 创建自定义规则(开放端口)
# 允许 TCP 8080 端口入站流量
New-NetFirewallRule -Name "Custom-Port-8080" `
-DisplayName "Allow Custom Port 8080" `
-Direction Inbound `
-Protocol TCP `
-LocalPort 8080 `
-Action Allow `
-Profile Any `
-Description "Allow application traffic on port 8080"
4. 批量管理建议
# 导出当前防火墙配置备份
Get-NetFirewallRule | Export-Csv "C:FirewallRules.csv" -NoTypeInformation
# 导入配置(需先准备 CSV 文件)
Import-Csv "C:FirewallRules.csv" | ForEach-Object {
New-NetFirewallRule -Name $_.Name -DisplayName $_.DisplayName ... # 需根据字段映射重建
}
三、生产环境注意事项
- 权限要求:所有命令需在 Administrator 权限 PowerShell 中执行
- 配置文件验证:修改后务必通过
Test-NetConnection验证连通性Test-NetConnection 192.168.1.1 -Port 80 - 云厂商适配:若部署在阿里云/AWS/腾讯云等平台,需同步检查:
- 云平台安全组规则(控制台层面)
- 操作系统防火墙规则(本系统层面)
- 两者需协同配置,避免策略冲突
- 审计日志:开启防火墙事件日志便于排查
Set-NetFirewallRule -Name "*" -LogAllowed $true -LogDenied $true
重要提示:在生产环境中修改网络或防火墙前,建议先通过远程终端会话(如 SSH 或 RDP over TCP)保持至少一个管理通道,避免因配置错误导致失联。对于核心业务系统,建议采用配置管理工具(如 Ansible)进行标准化部署。
CLOUD云枢