我如何将其扩展到远程计算机(获取 Windows 服务)?

发布于 2024-10-01 09:45:45 字数 799 浏览 4 评论 0原文

我有以下代码来获取某台计算机上运行的所有 Windows 服务。如果这台机器是我正在运行的机器,它工作正常,但如果它是远程机器,我会收到“访问被拒绝”异常,因为我没有传递用户名/密码。

我的问题是,如何/在哪里传递用户名/密码?

static void Main(string[] args)
        {
            bool filter;
            string machineName = "mymachine";
            string objPath = String.Format("\\\\{0}\\root\\cimv2:Win32_Service",machineName);

            ManagementClass servicesMC = new ManagementClass(new ManagementPath(objPath));
            Dictionary<string, string> ServicesDict = new Dictionary<string, string>();
            List<string> Aggregate = new List<string>();

            foreach (ManagementObject service in servicesMC.GetInstances())
            {
                //Console.WriteLine(service.GetPropertyValue("Name"));
            }

I have the following code that fetches all the Windows Services running on a certain machine. If the machine is the one I am running, it works fine, but if its a remote machine, I get a 'Access Denied' exception because I am not passing in the username/password.

My question is, how/where can I pass in the username/password?

static void Main(string[] args)
        {
            bool filter;
            string machineName = "mymachine";
            string objPath = String.Format("\\\\{0}\\root\\cimv2:Win32_Service",machineName);

            ManagementClass servicesMC = new ManagementClass(new ManagementPath(objPath));
            Dictionary<string, string> ServicesDict = new Dictionary<string, string>();
            List<string> Aggregate = new List<string>();

            foreach (ManagementObject service in servicesMC.GetInstances())
            {
                //Console.WriteLine(service.GetPropertyValue("Name"));
            }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不服输 2024-10-08 09:45:45

我还没有运行这个,因为我现在不在网络上,但这应该可以工作:

ConnectionOptions theConnection = new ConnectionOptions();

theConnection.Username = "username";
theConnection.Password = "password";

ManagementScope scope = new ManagementScope(objPath, theConnection);
ManagementClass servicesMC = new ManagementClass(scope, new ManagementPath("Win32_Service"), new ObjectGetOptions());

I haven't run this because I am not on a network right now but this should work:

ConnectionOptions theConnection = new ConnectionOptions();

theConnection.Username = "username";
theConnection.Password = "password";

ManagementScope scope = new ManagementScope(objPath, theConnection);
ManagementClass servicesMC = new ManagementClass(scope, new ManagementPath("Win32_Service"), new ObjectGetOptions());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文