简体   繁体   English

如何使用C#远程登录到远程计算机?

[英]How can you remotely login to a remote computer using C#?

I'm trying to write a small command line application with C# that will prompt for a username and a password that will be used to login to several remote computers that are sitting on the same network/domain and start a local session. 我正在尝试使用C#编写一个小的命令行应用程序,该应用程序将提示输入用户名和密码,这些用户名和密码将用于登录到位于同一网络/域上的多台远程计算机并启动本地会话。

I've tried connecting to a remote computer and to query the remote PC's operating system info with the following code: 我尝试连接到远程计算机,并使用以下代码查询远程PC的操作系统信息:

ConnectionOptions options = new ConnectionOptions();

ManagementScope scope = new ManagementScope(@"\\REMOTE_COMPUTER_NAME");
scope.Connect();

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

ManagementObjectCollection queryCollection = searcher.Get();

foreach (ManagementObject m in queryCollection)
{
    // Display the remote computer information
    Console.WriteLine("Computer Name : {0}", m["csname"]);
    Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]);
    Console.WriteLine("Operating System: {0}", m["Caption"]);
    Console.WriteLine("Version: {0}", m["Version"]);
    Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
}

However, this only returns information on the local PC that I'm working on and not on the remote PC. 但是,这只会返回我正在使用的本地PC上的信息,而不会返回远程PC上的信息。

Am I overlooking something with this code? 我是否可以用此代码忽略某些内容? And is there an appropriate approach to accomplish what I am trying to do? 是否有合适的方法来完成我要完成的工作?

I don't have remote machine right now to give you the working example, but you can try this. 我现在没有远程计算机可以为您提供工作示例,但是您可以尝试一下。 advapi32.logonuser advapi32.logonuser

Example: 例:

[DllImport("advapi32.dll")]
public static extern bool LogonUser(string name, string domain, string pass, 
int logType, int logpv, out IntPtr pht);

IntPtr ptr;
// LogonUser("username", "remotemachine", "password", 2, 0, out ptr);
LogonUser("username", "remotemachine", "password", 9, 0, out ptr);
WindowsIdentity windowsIdentity = new WindowsIdentity(ptr);
var impersonationContext = windowsIdentity.Impersonate();

// your code goes here...

impersonationContext.Undo();

This logon type allows the caller to clone its current token and specify new credentials for outbound connections. 此登录类型允许调用方克隆其当前令牌,并为出站连接指定新的凭据。 The new logon session has the same local identifier but uses different credentials for other network connections. 新的登录会话具有相同的本地标识符,但对其他网络连接使用不同的凭据。 NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. 注意:仅LOGON32_PROVIDER_WINNT50登录提供程序支持此登录类型。 NOTE: Windows NT: This value is not supported. 注意:Windows NT:不支持此值。

http://www.pinvoke.net/default.aspx/advapi32.logonuser http://www.pinvoke.net/default.aspx/advapi32.logonuser

Edit 编辑

Give it a try cassia 尝试决明子

ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetRemoteServer("servername"))
{
    server.Open();
    foreach (ITerminalServicesSession session in server.GetSessions())
    { 
        Console.WriteLine("Hi there, " + session.UserAccount + " on session " + session.SessionId);
        Console.WriteLine("It looks like you logged on at " + session.LoginTime +
                            " and are now " + session.ConnectionState);
    }
}

You have to use ConnectionOptions and pass it to the ManagementScope 您必须使用ConnectionOptions并将其传递给ManagementScope

    public void GetSystemInformation(string _yourDomain, string _hostName, string _userName, SecureString _password)
    {
        ManagementScope Scope = null;
        string computerName = _hostName;
        string userName = _userName;
        SecureString password = _password;
        ManagementObjectCollection collection = null;

        try
        {
            SelectQuery query = new SelectQuery("SELECT * FROM Win32_OperatingSystem");
            //string query = "SELECT * FROM Win32_NetworkAdapterConfiguration" + " WHERE IPEnabled = 'TRUE'";

            var options = new ConnectionOptions
            {
                  EnablePrivileges = false,
                  Impersonation = ImpersonationLevel.Impersonate,
                  Username = _userName,
                  SecurePassword = _password,
                  Authority = "ntlmdomain:" + _yourDomain
            };
            Scope.Options = options;
            Scope.Connect();

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query);
            collection = searcher.Get();

           //Do something with the collection
        }
        catch (ManagementException ex)
        {
            Console.WriteLine(ex.Message);
        }
        catch (UnauthorizedAccessException ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }

    private static SecureString CreateSecuredString(string pw)
    {
        var secureString = new SecureString();

        foreach (var c in pw)
        {
            secureString.AppendChar(c);
        }

        return secureString;
    }

You might have to try some different stats with the variables EnablePrivileges and Impersonation 您可能需要使用变量EnablePrivilegesImpersonation尝试一些不同的统计信息

edit: 编辑:

If you want to get your information from your pc (local) than you dont have to pass the options to the scope. 如果您想从您的PC(本地)获取信息,则不必将选项传递给示波器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM