Querying access to a UNC path on a remote machine via WMI - c#

I want to find out if the remote host has r/w access to a network share. To start out I wanted to see if I could query the target host's ability to query the UNC path for info, ala
var query = string.Format("select * from CIM_Directory where name = '{0}'", path);
This works fine for local files, e.g.
var path = #"c:\\Windows";
However, I can't figure out an appropriate way of querying a UNC path (e.g. \\foo\bar). The query always returns a blank set. I saw a related question about executing remote files and the solution for that one ended up being PsExec. I was hoping to ideally solve this problem entirely using WMI without having to rely on 3rd party execs, or uploading my own tool to the remote host.
Cheers
Here's a little usage sample of what I am trying to do right now (var values taken out):
using System;
using System.Linq;
using System.Management;
namespace netie
{
class Program
{
static void Main()
{
var connection = new ConnectionOptions
{
Username = "user",
Password = "pass",
Authority = "domain",
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true
};
var scope = new ManagementScope("\\\\remote\\root\\CIMV2", connection);
scope.Connect();
var path = #"\\\\foo\\bar\\";
var queryString = string.Format("select * from CIM_Directory where name = '{0}'", path);
try
{
var query = new ObjectQuery(queryString);
var searcher = new ManagementObjectSearcher(scope, query);
foreach (var queryObj in searcher.Get().Cast<ManagementObject>())
{
Console.WriteLine("Number of properties: {0}", queryObj.Properties.Count);
foreach (var prop in queryObj.Properties)
{
Console.WriteLine("{0}: {1}", prop.Name, prop.Value);
}
Console.WriteLine();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}

So it looks like this is basically impossible as WMI locks you out of network access for security reasons. Looks like your best bet is WinRM or PsExec for one-offs. You can potentially enable WinRM through WMI if that's your only path of access, but I imagine that ability can be blocked by group policies. The third option is to write your own Windows Service that will respond to requests and installing that through WMI if you have the access.
In short: the answer to my question is a No. Use WinRm, PsExec, or a custom win-service solution.

I know this is an old question, but for anyone looking to do this, the following code works. (I know that it's not WMI. Given the OP's answer I didn't even try it with WMI, but I shudder to think that people may write a service for something like this.)
if (System.IO.Directory.Exists(#"[SOME UNC PATH]"))
{
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(#"[SOME UNC PATH]");
var securityInfo = info.GetAccessControl();
var rules = securityInfo.GetAccessRules(
true,
true,
typeof(System.Security.Principal.SecurityIdentifier));
foreach (var rule in rules)
{
var fileSystemRule = rule as System.Security.AccessControl.FileSystemAccessRule;
if (ruleastype != null)
{
string user = fileSystemRule.IdentityReference.Translate(
typeof(System.Security.Principal.NTAccount)).Value;
System.Diagnostics.Debug.Print("{0} User: {1} Permissions: {2}",
fileSystemRule.AccessControlType.ToString(),
user,
fileSystemRule.FileSystemRights.ToString());
}
}
}
When run it produces the following output:
Allow User: Everyone Permissions: ReadAndExecute, Synchronize
Allow User: CREATOR OWNER Permissions: FullControl
Allow User: NT AUTHORITY\SYSTEM Permissions: FullControl
Allow User: BUILTIN\Administrators Permissions: FullControl
Allow User: BUILTIN\Users Permissions: ReadAndExecute, Synchronize

Related

How to obtain IP addresses of everything on network in c#

I have a sonicwall on a network of around 100 machines.
I have tried and tried to find a way of creating 2 combobox's that will contain both the IP addresses linked to the sonicwall, as well as the currently logged in user of the machine as well.
What i am trying to create is a employee monitoring software (like Interguard/ActivTrak/etc), but am unable at present to even get near to finding this information?
I've been researching A LOT of stuff (~25 pages of google, with not a single link not clicked), and have met no conclusion as to get this information.
I'm not exactly a great programmer, but I would LOVE to be able to get this sort of information into two combobox's/arrays/other suitable object/control.
If anyone knows a way of even creating an array of IP addresses, along with corresponding Logins, that would be of great help to this project!
(PLEASE NOTE: I know there is a Networking exchange site, but I have already looked! Also, since i'm designing a piece of software for this, I thought i'd ask it here!)
Thanks for any advice/suggestions much appreciated!
What you looking for is similar to a packet sniffer application like wireshark or ethereal. But if you want to design it yourself, I think your best solution is a collection/list to store the data that is binded to a datagrid.
If you're in an Active Directory domain, you could use the code from my S/O question. Instead of using the CheckConnectionAsync() method to check for connectivity, you could just re-write it to get the IP address using System.Net.Dns.
To retrieve the user, you can use WMI. For this, you need to make a reference to the System.Management namespace.
public Task<string> GetUserName(string ComputerName)
{
return Task.Run(() =>
{
ConnectionOptions conn = ConnectionOptions()
{
EnablePrivileges = true,
Username = // string in format of #"DomainName\UserName",
Password = password,
Authentication = AuthenticationLevel.PacketPrivacy,
Impersonation = ImpersonationLevel.Impersonate
};
ManagementScope scope = new ManagementScope(#"\\" + ComputerName + #"\root\cimv2", conn);
try
{
scope.Connect();
ObjectQuery user = new ObjectQuery("Select UserName From Win32_ComputerSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, user);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject m in collection)
{
string username = m["UserName"].ToString().Trim();
if(!String.IsNullOrEmpty(username))
{
return username;
}
}
return null; // no current logged in user
}
catch (Exception) // error handling...
});
}
Then, just iterate through your collection of computers and retrieve the username like so:
private async Task RetrieveUsers()
{
Parallel.ForEach(Computers, c =>
{
string user = await GetUserName(c.Name); // or c.IP. both work.
});
}

Check service status remotely

I need to grab the service status (running, stopped) remotely using the credentials of the user running my executable(winform).
Would WMI be the best method?
I need this query to work on windows(7,2003,2008,2012).Can someone point me in the right direction.
if (RemoteOSversion.Contains("Windows 7"))
{
var Windows7Query = xdoc.Elements("OS").Elements("Windows7");
foreach (var myServices in Windows7Query)
{
var ServicesQuery = myServices.Elements("Services");
foreach (var ServiceName in ServicesQuery)
{
var ServiceOutput = ServiceName.Value;
}
}
}
ServiceOutput is the service name. I need to check if this service is running/stopped remotely using the same credentials of the user running my exe
It's REALLY straightforward with WMI
var sc = new ServiceController(ServiceName, MachineName);
string result = sc.Status.ToString();
Yes, use WMI.
WMI has a query language called WQL, which is similar to to SQL. You can execute these in C# using the System.Management classes.
To work with WMI you need to add a reference to the System.Management assembly. Then you can set up a connection (i.e. ManagementScope) to the WMI Provider as follows:
ConnectionOptions options = new ConnectionOptions();
// If we are connecting to a remote host and want to
// connect as a different user, we need to set some options
//options.Username =
//options.Password =
//options.Authority =
//options.EnablePrivileges =
// If we are connecting to a remote host, we need to specify the hostname:
//string providerPath = #"\\Hostname\root\CIMv2";
string providerPath = #"root\CIMv2";
ManagementScope scope = new ManagementScope(providerPath, options);
scope.Connect();
You can read more about WMI at Microsoft Docs and work around at working-with-windows-services-using-csharp-and-wmi.

finding the actual executable and path associated to a windows service using c#

I am working on an installation program for one of my company's product. The product can be installed multiple times and each installation represents a separate windows service. When users upgrade or reinstall the program, I would like to look up the services running, find the services that belong to the product, and then find the executable file and its path for that service. Then use that information to find which one of the services the user wishes to upgrade/replace/install/etc. In my code example below, I see the service name, description, etc, but don't see the actual filename or path. Could someone please tell me what I'm missing? Thank you in advance!
The code I have is as follows:
ServiceController[] scServices;
scServices = ServiceController.GetServices();
foreach (ServiceController scTemp in scServices)
{
if (scTemp.ServiceName == "ExampleServiceName")
{
Console.WriteLine();
Console.WriteLine(" Service : {0}", scTemp.ServiceName);
Console.WriteLine(" Display name: {0}", scTemp.DisplayName);
ManagementObject wmiService;
wmiService = new ManagementObject("Win32_Service.Name='" + scTemp.ServiceName + "'");
wmiService.Get();
Console.WriteLine(" Start name: {0}", wmiService["StartName"]);
Console.WriteLine(" Description: {0}", wmiService["Description"]);
}
}
I might be wrong but the ServiceController class doesn't provide that information directly.
So as suggested by Gene - you will have to use the registry or WMI.
For an example of how to use the registry, refer to http://www.codeproject.com/Articles/26533/A-ServiceController-Class-that-Contains-the-Path-t
If you decide to use WMI (which I would prefer),
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
string name = obj["Name"] as string;
string pathName = obj["PathName"] as string;
...
}
You can decide to wrap the properties you need in a class.
the interface has changed since #sidprasher answered, try:
var collection = searcher.Get().Cast<ManagementBaseObject>()
.Where(mbo => mbo.GetPropertyValue("StartMode")!=null)
.Select(mbo => Tuple.Create((string)mbo.GetPropertyValue("Name"), (string)mbo.GetPropertyValue("PathName")));

Getting users of a computer

I am trying to get the list of local users of a computer using the following code.
internal void GetUsers()
{
try
{
List<string> adUsers = new List<string>();
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName.Equals("User", StringComparison.OrdinalIgnoreCase))
{
adUsers.Add(child.Name);
}
}
}
catch (Exception ex)
{
//Exception
}
}
This code works fine in my computer. However, when I tested it on a few other computers, the following system users were included in the list:
ASPNET,
HelpAssistant
Could some one throw some light on how I can get rid of these system users and get only users who actually log in, ie, normal users.
Thanks,
Ram
Not an answer as such, but some suggestions that might help.
I think the problem is that those accounts aren't real system accounts, so might not be so easy to distinguish.
You could look at the WMI classes Win32_UserAccount and Win32_UserProfile and see if there are any properties in there that might indicate which user accounts are normal ones and which ones are the ones you mention. Specifically, maybe the 'SIDType' or 'AccountType' properties of Win32_UserAccount or maybe the Special property of the Win32_UserProfile class.
Might be other WMI classes that might be worth looking at as well.
Or there might be some way that you can query if a user account has the interactive logon right (which I assume those two accounts might not have normally).
Have you tried enumerating the Properties collection on DirectoryEntry?
using (DirectoryEntry dirEntry = new DirectoryEntry(strchild))
{
foreach (string strPropertyName in dirEntry.Properties.PropertyNames)
{
Console.WriteLine(strPropertyName + " " + dirEntry.Properties[strPropertyName].Value.ToString());
}
}
Other than that, you may have to do an LDAP search on Active Directory to match the UserName you have found to an ActiveDirectory user.
Have a look at this article.
http://www.codeproject.com/KB/system/everythingInAD.aspx
Have fun.
The following code will get you the local users that actually have local accessible folders.
var localDrives = Environment.GetLogicalDrives();
var localUsers = new List<string>();
var query = new SelectQuery("Win32_UserAccount") { Condition = "SIDType = 1 AND AccountType = 512" };
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
foreach (string drive in localDrives)
{
var dir = Path.Combine(String.Format("{0}Users", drive), envVar["name"].ToString());
if (Directory.Exists(dir))
{
localUsers.Add(envVar["name"].ToString());
}
}
}

How do I retrieve the username that a Windows service is running under?

Given a service name, I would like to retrieve the username that it runs under (i.e. the username shown in the 'Log On' tab of a service's properties window).
There doesn't appear to be anything in the ServiceController class to retrieve this basic information. Nothing else in System.ServiceProcess looks like it exposes this information either.
Is there a managed solution to this, or am I going to have to drop down into something lower-level?
Using WMI, with the System.Management you can try the following code:
using System;
namespace WindowsServiceTest
{
class Program
{
static void Main(string[] args)
{
System.Management.SelectQuery sQuery = new System.Management.SelectQuery(string.Format("select name, startname from Win32_Service")); // where name = '{0}'", "MCShield.exe"));
using (System.Management.ManagementObjectSearcher mgmtSearcher = new System.Management.ManagementObjectSearcher(sQuery))
{
foreach (System.Management.ManagementObject service in mgmtSearcher.Get())
{
string servicelogondetails =
string.Format("Name: {0} , Logon : {1} ", service["Name"].ToString(), service["startname"]).ToString();
Console.WriteLine(servicelogondetails);
}
}
Console.ReadLine();
}
}
}
You can then later substitute the commented code with your service name, and it should only return the instances of your service process that is running.
WMI is your friend. Look at Win32_Service, specifically the StartName property. You can access WMI from C# via the System.Management.ManagementClass.
If you've not used WMI before, this article seems to be quite a good tutorial.
You can find this using the Windows Registry, reading the following string value, replacing [SERVICE_NAME] with the name of the Windows Service:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[SERVICE_NAME]\ObjectName
Try this:
System.Security.Principal.WindowsIdentity.GetCurrent();
but the most obvious you will get LOCAL SYSTEM or NETWORK. The reason that you cannot show this user - that service can manage multiple users (shared by desktop, attached to current windows session, using shared resource ...)
System starts service, but any user can use it.
This solution works fine for me:
ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + this.ServiceName + "'");
wmiService.Get();
string user = wmiService["startname"].ToString();
public String getUsername() {
string username = null;
try {
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ms.Connect();
ObjectQuery query = new ObjectQuery
("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(ms, query);
foreach (ManagementObject mo in searcher.Get()) {
username = mo["UserName"].ToString();
}
string[] usernameParts = username.Split('\\');
username = usernameParts[usernameParts.Length - 1];
} catch (Exception) {
username = "SYSTEM";
}
return username;
}

Categories