说明
改 BAT 脚本会自动启动 RDP 服务,自动允许"远程连接此电脑",自动将远程端口设置为输入的端口。
该脚本需管理员权限运行。运行后,需重启电脑,使更改生效。
目前:错误时,窗口会停留。正常时,窗口会一闪而过。
代码
@echo off
echo.
echo RDP's Port Number change tool.
echo.
echo This tool needs to be run as an administrator.
echo The tool will automatically start and enable RDP, then change the Port Number.
echo When the script is successfully executed, Please reboot your computer.
echo.
echo Author: Shanks
echo Blog: www.yudelei.com
echo Email: Shankschn.Lee@gmail.com
echo.
goto check_Permissions
:check_Permissions
echo Administrative permissions required. Detecting permissions...
net session >nul 2>&1
if %errorLevel% == 0 (
echo Success: Administrative permissions confirmed.
goto input_port_number
) else (
echo failure: Current permissions inadequate.
echo You need to run this tool as an administrator.
goto 0
)
:input_port_number
set /p port_number=Please input the Port Number that you want to use:
if %port_number%=="" (
echo Port Number is Error.
goto input_port_number
) else (
goto check_RDP_running_status
)
:firewall_allow_port
netsh advfirewall firewall add rule name="Custom RDP PortNumber" dir=in action=allow protocol=TCP localport=%port_number%
if %errorlevel%==0(
goto 1
) else (
goto 0
)
:check_RDP_running_status
echo Check RDP running status...
sc query termservice |findstr "STATE" |findstr "RUNNING"
if %errorlevel%==0 (
echo RDP is running.
goto check_RDP_enable_status
) else (
echo RDP is stoped.
goto start_RDP_service
)
:check_RDP_enable_status
echo Check RDP enable status...
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections |findstr 0x0
if %errorlevel%==1 (
echo RDP is disabled.
goto enable_RDP
) else (
echo RDP is enabled.
goto change_port
)
:enable_RDP
echo Enable RDP...
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
echo enable_RDP:%errorlevel%
goto check_RDP_enable_status
:change_port
echo Change Port Number...
echo %port_number%
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp" /v PortNumber /t REG_DWORD /d %port_number% /f
if %errorlevel%==1 (
goto 0
)
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber /t REG_DWORD /d %port_number% /f
if %errorlevel%==1 (
goto 0
)
goto firewall_allow_port
:start_RDP_service
echo RDP is starting...
net start termservice 2>&1 |findstr "2182"
if %errorlevel%==0 (
echo Start RDP: Successful.
goto check_RDP_running_status
) else (
goto 0
)
:0
call echo failure. Sorry. Change Port Faild. An error has occurred.
pause > nul && pause > nul
:1
call echo Successful. Please reboot your computer.
pause > nul && pause > nul