昨天在管理远程服务器的时候,为了安全起见,改了远程桌面端口号,在注册表中改了之后,没加思索,重启了系统.重启之后,发现用指定的端口连远程桌面,怎么也连不上,难道我改错了?仔细一回想,应该是没改错.突然想起来,防火墙还没开这个端口.
没办法,只好想个办法把端口号改回去,那就只有操作注册表了,C#好像可以直接操作注册表,马上写个Demo试试,Demo.aspx.cs里代码如下:

Code
1 RegistryKey HKML = Registry.LocalMachine;
2
3 RegistryKey WdsKey = HKML.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp", true);
4 WdsKey.SetValue("PortNumber", 3389, RegistryValueKind.DWord);
5
6 RegistryKey RdpKey = HKML.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", true);
7 RdpKey.SetValue("PortNumber", 3389, RegistryValueKind.DWord);
运行看看,很遗憾,web程序的权限不够,程序报错,不允许访问注册表.那看来要用winapp的方式运行才行.于是新建一个winapp项目,在formload里写下如下代码:

Code
1
RegistryKey HKML = Registry.LocalMachine;
2
3
RegistryKey WdsKey = HKML.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\Wds\rdpwd\Tds\tcp", true);
4
WdsKey.SetValue("PortNumber", 3389, RegistryValueKind.DWord);
5
6
RegistryKey RdpKey = HKML.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp", true);
7
RdpKey.SetValue("PortNumber", 3389, RegistryValueKind.DWord);
8
9
Process Shutdown = new Process();
10
Shutdown.StartInfo.FileName = @"c:\windows\system32\shutdown.exe";
11
Shutdown.StartInfo.Arguments = "-r -t 0";
12
Shutdown.Start();
为了保险起见,在修改端口号后重启系统,使新的端口生效.
现在问题又来了,这程序我能放到服务器上,但我要怎样才能启动它呢?想起以前看过一些资料说有些人在SQL Server里取得权限之后想干啥就干啥,好像有个叫xp_cmdshell的东东,那我好像有sa的权限,应该可以用用吧,但SQL Server出于安全考虑,关闭了远程连接,不过这也没什么大碍,在web里执行也是一样的.找资料,得到如下方法:

Code
1
K2046.DatabaseOperator.SqlOperator dbo = new K2046.DatabaseOperator.SqlOperator("server=.;uid=sa;pwd=xxxxxx;database=xxxxxx;");//SqlOperator是自己写的一个Helper.
2
dbo.ExecuteNonQuery("EXEC sp_configure 'show advanced options', 1");//开启高级选项
3
dbo.ExecuteNonQuery("RECONFIGURE");
4
dbo.ExecuteNonQuery("EXEC sp_configure 'xp_cmdshell', 1");//启用xp_cmdshell.
5
dbo.ExecuteNonQuery("RECONFIGURE");
6
dbo.ExecuteNonQuery("xp_cmdshell '" + Server.MapPath("\\") + "ConfigTools.exe'");//执行指定位置的程序.
7
8
dbo.ExecuteNonQuery("EXEC sp_configure 'xp_cmdshell', 0");//关闭xp_cmdshell.
9
dbo.ExecuteNonQuery("RECONFIGURE");
10
dbo.ExecuteNonQuery("EXEC sp_configure 'show advanced options', 0");//关闭高级选项
11
dbo.ExecuteNonQuery("RECONFIGURE");
把web程序和win程序一起用FTP传到服务器上,打开Demo.aspx页面,稍等一下,FTP便与服务器失去连接,哈哈,显然,服务器是关机了.打开cmd,ping http://www.xxx.com/ -t
大约一分钟,服务器连接上了.再打开远程桌面,哈哈,可以连上了.
由于这些东西都是没了解过的,也没接触过的,所以花了不少时间才写下上面这几行代码,问题解决了就好.做个笔记,给自己提个醒,别再犯这种粗心大意的错误了.唉.