在部署 Windows Server 时,默认的远程桌面端口为 3389。为了提升安全性,我们通常会更换该端口,避免被扫描攻击。本文将介绍如何修改远程桌面端口为 33899,并设置防火墙规则仅允许特定 IP 段访问。
一、修改 RDP 默认端口(3389 → 33899)
Windows 的远程桌面服务监听端口保存在注册表中。可通过如下注册表路径修改:
1 2 3
| HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp
|
键值名称为 PortNumber,类型为 REG_DWORD。
可使用管理员脚本自动完成这一操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @echo off SETLOCAL
:: Set new port number set NEW_PORT=33899
:: Modify registry to change RDP port REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber /t REG_DWORD /d %NEW_PORT% /f
:: Add firewall rule for new RDP port netsh advfirewall firewall add rule name="RDP Custom Port %NEW_PORT%" protocol=TCP dir=in localport=%NEW_PORT% action=allow
:: Restart Remote Desktop Services net stop TermService /y net start TermService
:: Notify user echo Remote Desktop port changed to %NEW_PORT%. echo Firewall rule added. echo Remote Desktop Service restarted. pause
ENDLOCAL
|
如果你还想限制IP段访问,继续往下看!
二、添加防火墙规则,仅允许指定 IP 段访问
Windows 防火墙支持添加入站规则,并指定远程 IP 范围。
本文示例中,我们仅允许 192.168.1.0/24 这个 IP 段访问端口 33899,其余全部阻止。
三、完整自动化脚本(以管理员身份运行)
将以下内容保存为 change_rdp_port.bat,右键以管理员身份运行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @echo off SETLOCAL
:: === 设置变量 === set NEW_PORT=33899 set IP_RANGE=192.168.1.0/24
:: === 修改注册表远程桌面端口 === REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" ^ /v PortNumber /t REG_DWORD /d %NEW_PORT% /f
:: === 添加防火墙规则:允许指定 IP 访问 === netsh advfirewall firewall add rule name="RDP %NEW_PORT% Allow %IP_RANGE%" ^ protocol=TCP dir=in localport=%NEW_PORT% action=allow remoteip=%IP_RANGE% enable=yes
:: === 添加防火墙规则:阻止其他 IP === netsh advfirewall firewall add rule name="RDP %NEW_PORT% Block Others" ^ protocol=TCP dir=in localport=%NEW_PORT% action=block remoteip=any enable=yes
:: === 重启远程桌面服务 === net stop TermService /y net start TermService
:: === 提示 === echo Remote Desktop port changed to %NEW_PORT%. echo Firewall rules applied. Only %IP_RANGE% is allowed. pause
ENDLOCAL
|
四、验证端口是否生效
使用以下命令查看端口监听状态:
1
| netstat -aon | findstr "33899"
|
输出示例:
1 2
| TCP 0.0.0.0:33899 0.0.0.0:0 LISTENING 1234 TCP [::]:33899 [::]:0 LISTENING 1234
|
表示远程桌面服务已在 33899 端口监听,PID 为 1234。
你也可以通过以下命令查找对应进程:
1
| tasklist | findstr "1234"
|
五、远程连接方式变更
更改端口后,远程连接时需使用如下格式:
上述脚本支持一键自动完成配置,适合初学者和系统管理员快速部署。