zoukankan      html  css  js  c++  java
  • C#链接Windows远程桌面

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace 链接远程服务器
    {
        public class OpenRemoteDesktop
        {
            /**
             MSTSC [<连接文件>] [/v:<服务器[:端口]>] [/admin] [/f[ullscreen]] [/w:<宽度> /h:<高度>] [/public] | [/span] [/multimon] [/migrate] [/edit “连接文件”] [/restrictedAdmin] [/prompt]
            “连接文件”– 指定用于连接的 .RDP 文件的名称。
            /v:<服务器[:端口]> — 指定要连接到的远程计算机。
            /admin — 将您连接到会话以管理服务器。
            /f — 在全屏模式下启动远程桌面。
            /w:<宽度> — 指定远程桌面窗口的宽度。
            /h:<高度> — 指定远程桌面窗口的高度。
            /public — 以公共模式运行远程桌面。
            /span — 将远程桌面的宽度和高度与本地虚拟桌面相匹配,如有必要,可跨多个监视器进行扩展。若要跨多个监视器进行扩展,必须将监视器排列成一个矩形。
            /multimon — 将远程桌面服务会话监视器布局配置为与当前的客户端配置相同。
            /edit — 打开要进行编辑的指定 .RDP 连接文件。
            /migrate — 将使用客户端连接管理器创建的旧版连接文件迁移到新的 .RDP 连接文件。
            /restrictedAdmin — 在受限管理模式下将您连接到远程计算机或服务器。在此模式下,将不会向远程计算机或服务器发送凭据,这样可在您连接到的计算机已被攻击时为您提供保护。但是,从远程计算机建立的连接可能不会由其他远程电脑和服务器进行身份验证,这可能会影响应用的功能和兼容性。表示 /admin。
            /prompt — 在您连接到远程计算机或服务器时提示您输入凭据。
            */
            
            /// <summary>
            /// 密码因子
            /// </summary>
            static byte[] s_aditionalEntropy = null;
    
            /// <summary>
            /// 打开远程桌面
            /// </summary>
            /// <param name="ip">IP地址</param>
            /// <param name="admin">用户名</param>
            /// <param name="pw">明文密码</param>
            public void Openrdesktop(string ip, string port = "", string admin = null, string pw = null)
            {
                string password = GetRdpPassWord(pw);
    
                int width = Screen.PrimaryScreen.Bounds.Width;
                int height = Screen.PrimaryScreen.Bounds.Height;
    
                #region newrdp
                //创建rdp
                string fcRdp = @"screen mode id:i:1
                               desktopi:" + width + @" 
                               desktopheight:i:" + height + @" 
                               session bpp:i:24
                               winposstr:s:2,3,188,8,1062,721
                               full address:s:MyServer
                               compression:i:1
                               keyboardhook:i:2
                               audiomode:i:0
                               redirectdrives:i:0
                               redirectprinters:i:0
                               redirectcomports:i:0
                               redirectsmartcards:i:0
                               displayconnectionbar:i:1
                               autoreconnection
                               enabled:i:1
                               username:s:" + admin + @"
                               domain:s:QCH
                               alternate shell:s:
                               shell working directory:s:
                               password 51:b:" + password + @"
                               disable wallpaper:i:1
                               disable full window drag:i:1
                               disable menu anims:i:1
                               disable themes:i:0
                               disable cursor setting:i:0
                               bitmapcachepersistenable:i:1";
    
                string rdpname = "rdesktop.rdp";
                CreationBat(rdpname, fcRdp);
                #endregion
    
                //创建bat
                string fcBat = @"mstsc rdesktop.rdp /console /v:" + ip + ":" + port + " /f /edit";
                string batname = "runRdp.bat";
                CreationBat(batname, fcBat);
                //创建vbs
    
                string vbsname = "runBat.vbs";
                string fcVbs = @"set ws=WScript.CreateObject(""WScript.Shell"")" + "
    ws.Run"runRdp.bat",0";
                CreationBat(vbsname, fcVbs);
                ExecuteVbs(vbsname);
            }
    
            /// <summary>
            /// 获取RDP密码
            /// </summary>
            private string GetRdpPassWord(string pw)
            {
                byte[] secret = Encoding.Unicode.GetBytes(pw);
                byte[] encryptedSecret = Protect(secret);
                string res = string.Empty;
                foreach (byte b in encryptedSecret)
                {
                    res += b.ToString("X2"); //转换16进制的一定要用2位
                }
                return res;
            }
    
            /// <summary>
            /// 加密方法
            /// </summary>
            /// <param name="data"></param>
            /// <returns></returns>
            private static byte[] Protect(byte[] data)
            {
                try
                {
                    //调用System.Security.dll
                    return ProtectedData.Protect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine("Data was not encrypted. An error occurred.");
                    Console.WriteLine(e.ToString());
                    return null;
                }
            }
    
            //解密方法
            private static byte[] Unprotect(byte[] data)
            {
                try
                {
                    //Decrypt the data using DataProtectionScope.CurrentUser.
                    return ProtectedData.Unprotect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine("Data was not decrypted. An error occurred.");
                    Console.WriteLine(e.ToString());
                    return null;
                }
            }
    
            /// <summary>
            /// 创建bat脚本
            /// </summary>
            /// <param name="batName">文件名</param>
            /// <param name="fileContent">文件内容</param>
            /// <param name="u"></param>
            private void CreationBat(string batName, string fileContent, string u = null)
            {
                string filepath = System.IO.Directory.GetCurrentDirectory();
                string batpath = filepath + @"" + batName;
                writeBATFile(fileContent, batpath);
            }
    
            /// <summary>
            /// 写入文件
            /// </summary>
            /// <param name="fileContent">文件内容</param>
            /// <param name="filePath">路径</param>
            private void writeBATFile(string fileContent, string filePath)
            {
                if (!File.Exists(filePath))
                {
                    FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//创建写入文件
                    StreamWriter sw = new StreamWriter(fs1);
                    sw.WriteLine(fileContent);//开始写入值
                    sw.Close();
                    fs1.Close();
                }
                else
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write);
                    StreamWriter sr = new StreamWriter(fs);
                    sr.WriteLine(fileContent);//开始写入值
                    sr.Close();
                    fs.Close();
                }
            }
    
            /// <summary>
            /// 调用执行bat文件
            /// </summary>
            /// <param name="batName">文件名</param>
            /// <param name="thisbatpath">路径</param>
            private void ExecuteBat(string batName, string thisbatpath)
            {
                Process proc = null;
                try
                {
                    string targetDir = string.Format(thisbatpath);//this is where testChange.bat lies
                    proc = new Process();
                    proc.StartInfo.WorkingDirectory = targetDir;
                    proc.StartInfo.FileName = batName;
                    proc.StartInfo.Arguments = string.Format("");//this is argument
                    proc.StartInfo.RedirectStandardError = false;
                    proc.StartInfo.CreateNoWindow = true;
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示,经实践可行
                    proc.Start();
                    proc.WaitForExit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                }
            }
    
            /// <summary>
            /// 调用执行vbs文件
            /// </summary>
            /// <param name="vbsName">文件名</param>
            private void ExecuteVbs(string vbsName)
            {
                string path = System.IO.Directory.GetCurrentDirectory() + @"" + vbsName;
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "wscript.exe";
                startInfo.Arguments = path;
                Process.Start(startInfo);
            }
    
        }
    }
    
    

    参照:https://www.shuzhiduo.com/A/6pdDP4XLdw/

  • 相关阅读:
    深入Android 【一】 —— 序及开篇
    Android中ContentProvider和ContentResolver使用入门
    深入Android 【六】 —— 界面构造
    The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the ser
    Dynamic Business代码片段总结
    对文件的BuildAction以content,resource两种方式的读取
    paraview 3.12.0 windows下编译成功 小记
    百度网盘PanDownload使用Aria2满速下载
    netdata的安装与使用
    用PS给证件照排版教程
  • 原文地址:https://www.cnblogs.com/wugang/p/15342188.html
Copyright © 2011-2022 走看看