How to login into machine using c# and System.Management library

Have to do periodic checks if it is still possible to login into every Virtual Server using domain account. So I had to put some code togather:

using System;
using System.Collections.Generic;
using VMware.Vim;
using System.Collections.Specialized;
using System.Management;

namespace vSphereCommand
{
internal class Program
{
private static void Main(string[] args)
{
var c = new VimClient();
var sc = c.Connect("https:///sdk");
var us = c.Login("", "");

IList vms = c.FindEntityViews(typeof (VirtualMachine), null, null, null);

foreach (var tmp in vms)
{
var vm = (VirtualMachine)tmp;
try
{
if (vm.Guest.GuestState == "running")
{
var serverName = vm.Guest.HostName;
var domainName = "";
var userName = "";
var password = "";

var connectionOptions = new ConnectionOptions();
connectionOptions.Username = userName;
connectionOptions.Password = password;
connectionOptions.Authority = string.Format("ntlmdomain:{0}", domainName);
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;
var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", serverName), connectionOptions);
scope.Connect();
Console.WriteLine(" ***OK*** Name: " + vm.Guest.HostName + " IP:" + vm.Guest.IpAddress + " state:" + vm.Guest.GuestState);
}
else
{
Console.WriteLine(" Not Runing. Name: " + vm.Guest.HostName + " IP:" + vm.Guest.IpAddress + " state:" + vm.Guest.GuestState);
}
}
catch(Exception ex)
{
Console.WriteLine("ERROR. Failed to connect. Name: " + vm.Guest.HostName + " IP:" + vm.Guest.IpAddress + " state:" + vm.Guest.GuestState);
}
}
}
}
}

Leave a Reply