Run mstsc.exe with specified username and password

前端 未结 7 1828
悲&欢浪女
悲&欢浪女 2020-12-04 16:06

I realize that in Windows 7, it is not possible to save different credentials for the same host, but I need some workaround.

Can I provide the username and password

7条回答
  •  悲哀的现实
    2020-12-04 16:21

    The accepted answer solves the problem, but has the side effect of leaving the credentials in the users credential store. I wound up creating an IDisposable so I can use the credentials in a using statement.

    using (new RDPCredentials(Host, UserPrincipalName, Password))
    {
        /*Do the RDP work here*/
    }
    

    internal class RDPCredentials : IDisposable
    {
        private string Host { get; }
    
        public RDPCredentials(string Host, string UserName, string Password)
        {
            var cmdkey = new Process
            {
                StartInfo =
                {
                    FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe"),
                    Arguments = $@"/list",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                }
            };
            cmdkey.Start();
            cmdkey.WaitForExit();
            if (!cmdkey.StandardOutput.ReadToEnd().Contains($@"TERMSRV/{Host}"))
            {
                this.Host = Host;
                cmdkey = new Process
                {
                    StartInfo =
                {
                    FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe"),
                    Arguments = $@"/generic:TERMSRV/{Host} /user:{UserName} /pass:{Password}",
                    WindowStyle = ProcessWindowStyle.Hidden
                }
                };
                cmdkey.Start();
            }
        }
    
        public void Dispose()
        {
            if (Host != null)
            {
                var cmdkey = new Process
                {
                    StartInfo =
                {
                    FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe"),
                    Arguments = $@"/delete:TERMSRV/{Host}",
                    WindowStyle = ProcessWindowStyle.Hidden
                }
                };
                cmdkey.Start();
            }
        }
    }
    

提交回复
热议问题