加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:12:28 所属栏目:百科 来源:网络整理
导读:我正在尝试使用C#编写一个小命令行应用程序,它将提示用户名和密码,该用户名和密码将用于登录位于同一网络/域并启动本地会话的多个远程计算机. 我尝试连接到远程计算机并使用以下代码查询远程PC的操作系统信息: ConnectionOptions options = new ConnectionO
我正在尝试使用C#编写一个小命令行应用程序,它将提示用户名和密码,该用户名和密码将用于登录位于同一网络/域并启动本地会话的多个远程计算机.

我尝试连接到远程计算机并使用以下代码查询远程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"]);
}

但是,这仅返回我正在处理的本地PC上的信息,而不是远程PC上的信息.

我是否忽略了这段代码?是否有适当的方法来完成我想要做的事情?

解决方法

我现在没有远程机器为您提供工作示例,但您可以试试这个. advapi32.logonuser

例:

[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,out ptr);
LogonUser("username",9,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. NOTE: Windows NT:
This value is not supported.

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

编辑

试一试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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读