How to programmatically search a printer in Active Directory - c#

Attempting to find printers / shares in Active Directory using C#.
This is my sample code that works for users however I cannot seen to be able to find a printer using the same concept. (I am new to Active Directory).
DirectoryEntry entry = new DirectoryEntry();
entry.Path = "LDAP://xxx.xxx.xx.xx/CN=Printers;DC=domainName, DC=com";
entry.Username = #"domainName.com\Administrator";
entry.Password = "admin";
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
Any assistance would be greatly appreciated.

In contrast to users (CN=Users) there is no CN=Printers container in Active Directory after installation.
Printers are published in Active Directory in the releated computer container. What does
releated computer container mean? Well, open Active Directory Users and Computers MMC snap-in and
follow this procedure:
Select advanced features in the view menu.
Select Users, Contancts, Groups and Computers as containers in the view menu.
Navigate to the computer object (which is now displayed as container)
your printer belongs to.
Click on the plus sign of the computer container. There you will see
the printer object.
So, you see printers are published in Active Directory in the releated computer container (the printer belongs to) and not in one common container such as CN=Printers.
So, to search for a printer object in Active Directory, you have to specify
a different LDAP path. For example you could specify the root of your Active Directory
as the search root:
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Path = "LDAP://xxx.xxx.xxx.xxx/DC=domainName,DC=com";
entry.Username = #"domainName.com\Administrator";
entry.Password = "SecurePassword";
using (DirectorySearcher search = new DirectorySearcher(entry))
{
search.Filter = "(objectCategory=printQueue)";
SearchResult result = search.FindOne();
if (result != null)
{
ResultPropertyCollection fields = result.Properties;
foreach (String ldapField in fields.PropertyNames)
{
foreach (Object myCollection in fields[ldapField])
Console.WriteLine(String.Format("{0,-20} : {1}",
ldapField, myCollection.ToString()));
}
}
}
}
Of course, you could also specify as search root the LDAP path to the computer where your printer
is shared on. For example if your printer is shared on a computer called server10 and this computer is located in the CN=Computers container, then specify this LDAP path:
LDAP://xxx.xxx.xxx.xxx/CN=server10,CN=Computers,DC=domainName,DC=com
If you share a printer on the domain controller then the LDAP path is slightly different (because by default domain controller computer objects are located in the OU=Domain Controllers organizational unit):
LDAP://xxx.xxx.xxx.xxx/CN=DomainControllerName,OU=Domain Controllers,DC=domainName,DC=com

Related

How to Get the list of all User Accounts of Windows in C#? [duplicate]

How can I get a list of users from active directory? Is there a way to pull username, firstname, lastname? I saw a similar post where this was used:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
I have never done anything with active directory so I am completely lost. Any help would be greatly appreciated!
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.
There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.
For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value);
Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.
If you want to filter y active accounts add this to Harvey's code:
UserPrincipal userPrin = new UserPrincipal(context);
userPrin.Enabled = true;
after the first using. Then add
searcher.QueryFilter = userPrin;
before the find all. And that should get you the active ones.
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here:
https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here:
https://learn.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
Certainly the credit goes to #Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
Include the System.DirectoryServices.dll, then use the code below:
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
userNames += child.Name + Environment.NewLine ;
}
}
MessageBox.Show(userNames);

Retrieve security permissions for a Security Group from Active Directory

I am trying to create a function where I input a Security Group name and return a list of the security permissions.
How do I get a list of security permissions like read, write, full control etc. for a Security Group such as Domain Controllers, Domain Guests, etc. from Active Directory using C#?
You need to check the path of the LDAP connection that you are making to communicate with the Active Directory server.
For example:
DirectoryEntry rootDSE = null;
rootDSE = new DirectoryEntry("LDAP://OU=" + department + ",OU=Users,OU=" + ou + ",dc=corp,dc=local", username, password);
Now in that case I need only groups that exist in Department → Users → OU → DC
Same as in your case. You can define on which OU your security group exist.
After that I can fetch a group like this:
DirectorySearcher ouSearch = new DirectorySearcher(rootDSE);
ouSearch.PageSize = 1001;
ouSearch.Filter = "(objectClass=group)";
ouSearch.SearchScope = SearchScope.Subtree;
ouSearch.PropertiesToLoad.Add("name");
SearchResultCollection allOUS = ouSearch.FindAll();
foreach (SearchResult oneResult in allOUS)
{
dt.Rows.Add(oneResult.Properties["name"][0].ToString());
}
rootDSE.Dispose();
Now in case of permissions
Permissions are stored on the individual file system items, e.g. files and/or directories - or other objects (like registry keys, etc.). When you have an AD group or user account, you can read its SID (Security Identifier) property - that SID will show up in ACLs (Access Control Lists) all over Windows - but from the user or group, there's no mechanism to get all permissions it might have anywhere in the machine/server.
Permissions for files and directories can e.g. be retrieved using the .GetAccessControl() method on the FileInfo and DirectoryInfo classes:
FileInfo info = new FileInfo(#"D:\test.txt");
FileSecurity fs = info.GetAccessControl();
DirectoryInfo dir = new DirectoryInfo(#"D:\test\");
DirectorySecurity ds = dir.GetAccessControl();
I hope this is what you are looking for!

How can I get a list of users from active directory?

How can I get a list of users from active directory? Is there a way to pull username, firstname, lastname? I saw a similar post where this was used:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
I have never done anything with active directory so I am completely lost. Any help would be greatly appreciated!
If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.
Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory
The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.
There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.
For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.
using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
Console.WriteLine("SAM account name : " + de.Properties["samAccountName"].Value);
Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
Console.WriteLine();
}
}
}
Console.ReadLine();
Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.
If you want to filter y active accounts add this to Harvey's code:
UserPrincipal userPrin = new UserPrincipal(context);
userPrin.Enabled = true;
after the first using. Then add
searcher.QueryFilter = userPrin;
before the find all. And that should get you the active ones.
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here:
https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here:
https://learn.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
Certainly the credit goes to #Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
Include the System.DirectoryServices.dll, then use the code below:
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
string userNames="Users: ";
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
userNames += child.Name + Environment.NewLine ;
}
}
MessageBox.Show(userNames);

C#.NET: Retrieve list of computers in a FOLDER in a domain

How do I Retrieve a list of computers in a FOLDER in a domain.
lets say i have maydomain.dom as my domain
and I have a folder containing some computers.
Following code to list out computers in your domain and in active directory, this may help you
//ActiveDirectorySearch1
//Displays all computer names in an Active Directory
using System;
using System.DirectoryServices;
namespace ActiveDirectorySearch1
{
class Class1
{
static void Main (string[] args)
{
//Note : microsoft is the name of my domain for testing purposes.
DirectoryEntry entry = new DirectoryEntry(LDAP://microsoft);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
Console.WriteLine("Listing of computers in the Active Directory");
Console.WriteLine("============================================"); foreach(SearchResult resEnt in mySearcher.FindAll())
{
Console.WriteLine(resEnt.GetDirectoryEntry().Name.ToString()); }
Console.WriteLine("=========== End of Listing =============");
}
}
}
http://www.c-sharpcorner.com/UploadFile/jodonnell/ListAllComps07022005005654AM/ListAllComps.aspx
It's not exactly the same but maybe you can use the same principle as in this blog post: Find users in Active Directory folder using GUID

Reading ldap group member from c#

I have this code to connect to Active Directory and get all the groups that exist, it works and returns all the groups in results :
DirectoryEntry dirEnt = new DirectoryEntry();
using (DirectorySearcher srch = new DirectorySearcher(dirEnt, "(objectClass=Group)"))
{
srch.PageSize = 1000;
SearchResultCollection results = srch.FindAll();
}
I now want to return users of a specific group i.e. Administrators, how would I go about this?
I had tried changing (objectClass=Group) to (objectClass=Group)(cn=admin) but then it returns no results.
All the best
Here's a reference about how to in Active Directory:
Howto: (Almost) Everything In Active Directory via C#

Categories

Resources