Windows服务器配置教程

结论: Windows Server 配置的标准流程是六步——初始化(改密码、设主机名、时区、网络)、配置远程桌面(RDP)并加固端口、安装 IIS 与运行环境、配置 Windows 防火墙入站规则、掌握常用 PowerShell 运维命令、开启系统更新与定时备份。全程可以在 PowerShell 里完成,比图形界面更快也更容易复用。

很多习惯了 Linux 的运维第一次拿到 Windows Server 会觉得无从下手:没有 SSH、没有 apt、配置全在层层菜单里。实际上 Windows Server 从 2012 版本开始,PowerShell 已经覆盖了绝大部分运维操作,配合服务器管理器(Server Manager)和 sconfig 命令行工具,配置效率并不比 Linux 低。本文以 Windows Server 2022 与 2025 为例(两者操作基本一致),从开机第一次登录讲到站点上线和备份策略,命令均可直接复制执行。

一、初始化:改密码、设主机名、配网络与时区

先给结论:新机器第一件事是改管理员密码、设置静态 IP(或确认 DHCP 获取正常)、配置主机名与时区,然后激活系统。这一步用 sconfig 菜单最快。

用 sconfig 快速完成基础配置

登录服务器后会自动打开服务器管理器,在 PowerShell 或命令提示符里输入:

powershell
sconfig

sconfig 是 Windows Server 自带的文本配置菜单,常用选项对应关系是:

选项作用建议值
1) Domain/Workgroup加入域或工作组单机选工作组 WORKGROUP
2) Computer Name计算机名如 WEB-PROD-01,改完需重启
3) Add Local Admin添加本地管理员建议新建个人管理员账号
4) Configure Remote Management远程管理启用
5) Windows Update Settings更新设置建议设为手动或仅下载
6) Download and Install Updates下载安装更新初次配置完执行一次
7) Remote Desktop远程桌面启用(选 "e",再选 2 允许任意版本客户端)
8) Network Settings网络设置配置静态 IP 与 DNS
9) Date and Time日期时间设为北京时间
12) Restart Server重启配置完重启生效

用 PowerShell 完成同样操作(可脚本化)

powershell
# 查看系统版本与已安装内存
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer, CsTotalPhysicalMemory

# 重命名计算机(重启后生效)
Rename-Computer -NewName "WEB-PROD-01" -Force -Restart

# 设置时区为中国标准时间
Set-TimeZone -Id "China Standard Time"
Get-TimeZone

# 查看网卡名称
Get-NetAdapter | Select-Object Name, Status, LinkSpeed

# 配置静态 IP(把 "Ethernet" 换成实际网卡名)
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.10 `
  -PrefixLength 24 -DefaultGateway 192.168.1.1

# 配置 DNS
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("223.5.5.5","114.114.114.114")

# 验证网络
Test-NetConnection 223.5.5.5 -Port 53
ipconfig /all

修改管理员密码与创建运维账号

powershell
# 修改当前用户密码
net user Administrator 新密码

# 创建新管理员账号(避免直接使用 Administrator)
net user opsadmin "P@ssw0rd!Complex" /add
net localgroup administrators opsadmin /add

# 禁用内置的 Administrator 账号(降低被爆破风险)
net user Administrator /active:no

# 查看本地用户与组
Get-LocalUser | Select-Object Name, Enabled, LastLogon
Get-LocalGroupMember -Group "Administrators"

云服务器特别提示:Windows 云服务器的 Administrator 初始密码在控制台获取,首次登录后务必立即修改,并在云控制台的安全组中限制 3389 端口的来源 IP。

二、远程桌面(RDP)配置:端口、安全与连接

先给结论:启用 RDP 后,默认端口 3389 是全网扫描的重点目标,必须做三件事——限制来源 IP、修改端口(可选)、启用网络级别身份验证(NLA)。

远程桌面(Remote Desktop Protocol,RDP)是 Windows 服务器最核心的远程管理方式。

启用远程桌面

powershell
# 方式一:注册表方式启用(去掉 fDenyTSConnections 的拒绝标志)
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" `
  -Name "fDenyTSConnections" -Value 0

# 启用网络级别身份验证 NLA(要求连接前先认证,安全性更高)
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" `
  -Name "UserAuthentication" -Value 1

# 方式二:用 PowerShell 模块(Windows Server 2022+ 推荐)
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

修改 RDP 默认端口

powershell
# 把 RDP 端口改为 3390
$port = 3390
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" `
  -Name "PortNumber" -Value $port -Type DWord

# 为旧版连接也改端口(部分环境需要)
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp" `
  -Name "PortNumber" -Value $port -Type DWord

# 同步修改防火墙规则(否则端口改了连不上)
New-NetFirewallRule -DisplayName "RDP-Custom-$port" -Direction Inbound `
  -Protocol TCP -LocalPort $port -Action Allow -Profile Any

# 确认端口已监听
netstat -ano | findstr ":$port"
Get-NetTCPConnection -LocalPort $port -State Listen

# 重启后生效
Restart-Computer -Force

连接时在客户端写成 IP:3390 的格式,例如 192.168.1.10:3390。

RDP 安全加固清单

  • 限制来源 IP:在"高级安全 Windows Defender 防火墙"里编辑远程桌面入站规则,"作用域"中只填自己的办公网 IP 段。
  • 启用账户锁定策略:连续 5 次失败锁定 30 分钟,用 secpol.msc → 账户策略 → 账户锁定策略配置。
  • 开启 NLA:上面的 UserAuthentication = 1 即是。
  • 配合 VPN 或堡垒机:生产环境建议只允许通过 VPN 访问 3389,不直接暴露到公网。
  • 定期审计登录日志:事件查看器 → Windows 日志 → 安全,筛选事件 ID 4624(登录成功)与 4625(登录失败)。
powershell
# 查询最近 24 小时内 RDP 登录失败记录(事件 ID 4625)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddHours(-24)} |
  Select-Object TimeCreated, @{n='IP';e={$_.Properties[19].Value}} -First 20

# 查询 RDP 登录成功记录(事件 ID 4624,LogonType 10 表示远程交互登录)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624; StartTime=(Get-Date).AddDays(-1)} |
  Where-Object { $_.Properties[8].Value -eq 10 } |
  Select-Object TimeCreated, @{n='User';e={$_.Properties[5].Value}}, @{n='IP';e={$_.Properties[18].Value}}

三、安装 IIS 与发布站点

先给结论:IIS(Internet Information Services,互联网信息服务)是 Windows 自带的 Web 服务器,用 PowerShell 一条命令即可安装;发布站点时关键是应用程序池(Application Pool)的 .NET 版本与身份设置。

安装 IIS 与常用组件

powershell
# 安装 IIS 及管理控制台(含 ASP.NET 4.x)
Install-WindowsFeature -Name Web-Server, Web-Mgmt-Console, Web-Asp-Net45, `
  Web-Default-Doc, Web-Dir-Browsing, Web-Http-Errors, Web-Static-Content, `
  Web-Http-Redirect, Web-Http-Logging, Web-Request-Monitor, Web-Url-Auth `
  -IncludeManagementTools

# 查看已安装的角色与功能
Get-WindowsFeature | Where-Object { $_.Installed -eq $true } | Select-Object Name, DisplayName

# 确认服务已启动
Get-Service W3SVC, WAS | Select-Object Name, Status
iisreset /status

若需要运行 ASP.NET Core,还需单独安装 .NET Hosting Bundle(包含 ASP.NET Core 模块),安装后执行 iisreset 重启 IIS。

用 PowerShell 创建站点与应用程序池

powershell
# 导入 IIS 管理模块
Import-Module WebAdministration

# 创建应用程序池,.NET CLR 版本为空表示无托管代码(ASP.NET Core 用)
New-WebAppPool -Name "MySitePool"
Set-ItemProperty "IIS:\AppPools\MySitePool" -Name managedRuntimeVersion -Value ""
Set-ItemProperty "IIS:\AppPools\MySitePool" -Name startMode -Value "AlwaysRunning"
Set-ItemProperty "IIS:\AppPools\MySitePool" -Name processModel.idleTimeout -Value "00:00:00"

# 创建站点目录并放一个测试页
New-Item -ItemType Directory -Path "C:\inetpub\wwwroot\mysite" -Force
Set-Content -Path "C:\inetpub\wwwroot\mysite\index.html" -Value "

Hello Windows Server

" -Encoding UTF8 # 创建站点,绑定主机名 example.com 与端口 80 New-Website -Name "MySite" -PhysicalPath "C:\inetpub\wwwroot\mysite" ` -ApplicationPool "MySitePool" -Port 80 -HostHeader "example.com" # 查看所有站点状态 Get-Website | Select-Object Name, State, PhysicalPath, Bindings Get-WebBinding -Name "MySite" # 启动 / 停止 / 重启站点 Start-Website -Name "MySite" Stop-Website -Name "MySite"

配置 HTTPS 绑定与 HTTP 跳转

Windows 上申请 Let's Encrypt 证书常用 win-acme(原 letsencrypt-win-simple)工具,也可先在 Linux 或控制台申请 PFX 后导入:

powershell
# 导入已有 PFX 证书到本机证书存储
$pwd = ConvertTo-SecureString -String "Pfx密码" -Force -AsPlainText
Import-PfxCertificate -FilePath "C:\certs\example.com.pfx" `
  -CertStoreLocation "Cert:\LocalMachine\My" -Password $pwd

# 查看导入的证书指纹
Get-ChildItem Cert:\LocalMachine\My | Select-Object Subject, Thumbprint, NotAfter

# 绑定 443 端口(certstore 为 My,需指定指纹)
$thumb = "这里换成实际指纹"
New-WebBinding -Name "MySite" -Protocol "https" -Port 443 -HostHeader "example.com" -SslFlags 1
$binding = Get-WebBinding -Name "MySite" -Protocol "https"
$binding.AddSslCertificate($thumb, "My")

# 安装 URL Rewrite 模块后,可用 web.config 做 HTTP→HTTPS 跳转
xml


  
    
      
        
          
          
            
          
          
        
      
    
  

站点目录权限

powershell
# 给应用程序池身份授予目录读写权限(IIS AppPool\池名 是虚拟账户)
$acl = Get-Acl "C:\inetpub\wwwroot\mysite"
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
  "IIS AppPool\MySitePool", "Modify", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.SetAccessRule($rule)
Set-Acl "C:\inetpub\wwwroot\mysite" $acl

# 查看日志目录
Get-ChildItem C:\inetpub\logs\LogFiles\W3SVC* -Recurse -Filter "*.log" |
  Sort-Object LastWriteTime -Descending | Select-Object -First 5 FullName, Length

四、防火墙入站规则:放行端口的正确姿势

先给结论:Windows 防火墙默认阻止所有入站连接,放行端口要用 New-NetFirewallRule 显式添加规则,并且规则要限定协议、端口和作用域(来源 IP)。

powershell
# 放行 HTTP / HTTPS
New-NetFirewallRule -DisplayName "Allow HTTP 80"  -Direction Inbound -Protocol TCP -LocalPort 80  -Action Allow -Profile Any
New-NetFirewallRule -DisplayName "Allow HTTPS 443" -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow -Profile Any

# 放行指定来源 IP 的自定义端口(如只允许办公网访问 8080)
New-NetFirewallRule -DisplayName "Allow 8080 from Office" -Direction Inbound `
  -Protocol TCP -LocalPort 8080 -RemoteAddress "203.0.113.0/24" -Action Allow

# 放行 MSSQL(1433)仅限内网段
New-NetFirewallRule -DisplayName "MSSQL 1433 Internal" -Direction Inbound `
  -Protocol TCP -LocalPort 1433 -RemoteAddress "10.0.0.0/8" -Action Allow

# 查看所有启用的入站规则
Get-NetFirewallRule -Direction Inbound -Enabled True |
  Select-Object DisplayName, Direction, Action, Profile |
  Sort-Object DisplayName | Format-Table -AutoSize

# 查看规则对应的端口过滤条件
Get-NetFirewallRule -DisplayName "Allow HTTP 80" | Get-NetFirewallPortFilter

# 禁用 / 删除规则
Disable-NetFirewallRule -DisplayName "Allow HTTP 80"
Remove-NetFirewallRule  -DisplayName "Allow HTTP 80"

# 查看当前配置文件状态(域/专用/公用)
Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction

云服务器还要记得放行安全组。 Windows 防火墙是系统内的第二道门,云控制台的安全组是第一道,两边都通了端口才可达。排查"端口不通"时,先 Test-NetConnection IP -Port 端口 从外部测试,再逐层检查。

powershell
# 从本机测试目标端口是否可达(相当于 telnet)
Test-NetConnection 192.168.1.10 -Port 443

# 查看本机所有监听端口与对应进程
Get-NetTCPConnection -State Listen |
  Select-Object LocalAddress, LocalPort,
    @{n='Process';e={(Get-Process -Id $_.OwningProcess).ProcessName}} |
  Sort-Object LocalPort | Format-Table -AutoSize

netstat -ano | findstr LISTENING

五、PowerShell 运维命令速查

先给结论:下面这些命令覆盖日常 80% 的 Windows 服务器运维场景,建议收藏成一份脚本片段。

powershell
# ---------- 进程与服务 ----------
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name, CPU, WorkingSet64
Stop-Process -Name "notepad" -Force
Get-Service | Where-Object { $_.Status -eq "Running" } | Select-Object Name, DisplayName
Restart-Service -Name "W3SVC" -Force
Set-Service -Name "Spooler" -StartupType Disabled

# ---------- 磁盘与文件 ----------
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{n='UsedGB';e={[math]::Round($_.Used/1GB,1)}}, @{n='FreeGB';e={[math]::Round($_.Free/1GB,1)}}
Get-ChildItem C:\inetpub -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, @{n='MB';e={[math]::Round($_.Length/1MB,1)}}
# 清理 Windows 更新缓存(磁盘紧张时常用)
Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore
Dism.exe /Online /Cleanup-Image /StartComponentCleanup

# ---------- 网络 ----------
Get-NetIPConfiguration | Select-Object InterfaceAlias, IPv4Address, IPv4DefaultGateway
Resolve-DnsName example.com
Clear-DnsClientCache
Get-NetTCPConnection | Group-Object State | Select-Object Name, Count

# ---------- 日志与事件 ----------
Get-WinEvent -ListLog * | Where-Object { $_.RecordCount -gt 0 } | Select-Object LogName, RecordCount
Get-EventLog -LogName System -EntryType Error -Newest 20 | Select-Object TimeGenerated, Source, Message

# ---------- 用户与权限 ----------
Get-LocalUser | Select-Object Name, Enabled, PasswordLastSet
Get-LocalGroupMember -Group "Remote Desktop Users"
Add-LocalGroupMember -Group "Remote Desktop Users" -Member "opsadmin"

# ---------- 系统信息 ----------
systeminfo | findstr /C:"OS Name" /C:"Total Physical Memory" /C:"System Boot Time"
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors
Get-CimInstance Win32_PhysicalMemory | Select-Object Manufacturer, Capacity, Speed
Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, @{n='SizeGB';e={[math]::Round($_.Size/1GB,1)}}, @{n='FreeGB';e={[math]::Round($_.FreeSpace/1GB,1)}}

六、系统更新与数据备份

先给结论:生产环境的 Windows Server 建议开启自动更新但安排在维护窗口重启,备份至少包含系统状态(System State)和 IIS 站点目录两层。

配置 Windows 更新

powershell
# 安装 PSWindowsUpdate 模块(社区常用)
Install-Module -Name PSWindowsUpdate -Force -Scope AllUsers
Import-Module PSWindowsUpdate

# 查看可用更新
Get-WindowsUpdate

# 安装所有更新但不自动重启
Install-WindowsUpdate -AcceptAll -IgnoreReboot

# 查看更新历史
Get-WUHistory | Select-Object Date, Title, Result -First 20

# 用 sconfig 图形菜单切换更新策略:sconfig → 选项 5

服务器管理器里也可以通过"本地服务器 → Windows 更新"设置活跃时段(Active Hours),避免业务高峰自动重启。

安装 Windows Server Backup 并配置定时备份

powershell
# 安装备份功能(含命令行工具 wbadmin)
Install-WindowsFeature -Name Windows-Server-Backup -IncludeManagementTools

# 一次性完整备份系统状态到 D 盘
wbadmin start systemstatebackup -backupTarget:D: -quiet

# 备份整个 C 盘到网络共享(需要目标目录有写权限)
wbadmin start backup -backupTarget:\\10.0.0.5\backup$ -include:C: -allCritical -quiet

# 查看已配置的计划任务与备份历史
wbadmin get versions
wbadmin get schedules

# 创建每日 2:00 的定时备份计划
wbadmin enable backup -addtarget:D: -schedule:02:00 -include:C: -allCritical -quiet

用任务计划程序做站点文件备份

powershell
$action  = New-ScheduledTaskAction -Execute "powershell.exe" `
  -Argument "-NoProfile -Command `"Compress-Archive -Path C:\inetpub\wwwroot\mysite -DestinationPath D:\backup\site-$(Get-Date -f yyyyMMdd).zip -Force`""
$trigger = New-ScheduledTaskTrigger -Daily -At 03:00
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "DailySiteBackup" -Action $action -Trigger $trigger `
  -Settings $settings -User "SYSTEM" -RunLevel Highest

# 查看与手动触发
Get-ScheduledTask -TaskName "DailySiteBackup"
Start-ScheduledTask -TaskName "DailySiteBackup"

数据库备份(如 SQL Server)应使用 sqlcmd 或维护计划导出 .bak,不要直接复制数据文件:

powershell
sqlcmd -S localhost -Q "BACKUP DATABASE [MyDB] TO DISK = 'D:\backup\MyDB.bak' WITH COMPRESSION, INIT"

常见误区 / 排错提示

  • 改了 RDP 端口却没加防火墙规则。 修改注册表端口后必须同步创建入站规则,否则重启后就再也连不上了。云服务器此时可用控制台的 VNC 救援。
  • IIS 装好了但外网访问不了。 三层检查:云安全组是否放行 80/443 → Windows 防火墙入站规则是否添加 → 站点绑定里的主机名是否与访问的域名一致。用 Test-NetConnection 从外部逐项验证。
  • 应用程序池 .NET 版本选错。 ASP.NET Core 站点必须把 managedRuntimeVersion 设为空字符串(无托管代码),若设为 v4.0 会报 500 错误。
  • 用 Administrator 跑生产服务。 建议新建运维账号并禁用内置 Administrator,同时配置账户锁定策略防止暴力破解。
  • 自动更新在业务高峰重启。 生产环境务必设置活跃时段或改为手动更新,配合维护窗口执行。
  • 只备份站点不备份系统状态。 系统崩溃重装后,IIS 配置、证书、注册表项都会丢失。完整备份应包含 -allCritical 或单独做系统状态备份。