/// <summary> /// This method receives a string containing the server name, and deletes it's computer account. /// </summary> /// <param name="serverName">a string containing the server name.</param> /// <returns>A ComputerAccountResult containing the action performed, a success/failure message, /// the name of the server which the computer account belongs to and the path of the object in AD.</returns> public static ComputerAccountResult DeleteComputerAccount(string serverName) { // Set up the result object. ComputerAccountResult result = new ComputerAccountResult() { action = "delete", message = string.Empty, serverName = serverName, objectADPath = string.Empty }; // Set up domain context. PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain); // Check if an existing computer account exists in AD. ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, serverName); if (computer != null) { result.objectADPath = computer.DistinguishedName; computer.Delete(); result.message = "Computer Account deleted successfully."; } else { result.message = "No such Computer Account."; } return(result); }
public void TestComputerContext() { using (PrincipalContext context = DomainContext) { using (ComputerPrincipal cp = new ComputerPrincipal(context)) { cp.Name = "*"; PrincipalSearcher ps = new PrincipalSearcher(); ps.QueryFilter = cp; using (ComputerPrincipal r1 = ps.FindOne() as ComputerPrincipal) using (ComputerPrincipal r2 = ComputerPrincipal.FindByIdentity(context, r1.Name)) { Assert.Equal(r2.AccountExpirationDate, r1.AccountExpirationDate); Assert.Equal(r2.Description, r1.Description); Assert.Equal(r2.DisplayName, r1.DisplayName); Assert.Equal(r2.DistinguishedName, r1.DistinguishedName); Assert.Equal(r2.Guid, r1.Guid); Assert.Equal(r2.HomeDirectory, r1.HomeDirectory); Assert.Equal(r2.HomeDrive, r1.HomeDrive); Assert.Equal(r2.SamAccountName, r1.SamAccountName); Assert.Equal(r2.Sid, r1.Sid); Assert.Equal(r2.UserPrincipalName, r1.UserPrincipalName); } } } }
//search Active directory for computers static public string GetComputer(string name) { //domain connection using (var pc = new PrincipalContext(ContextType.Domain, "Domain Name")) { //search through all computer objects in ad for matching name ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, IdentityType.Name, name); if (computer != null) { DataTable tempTable = new DataTable(); //save computer name & last logon for table tempTable.Columns.Add("Name", typeof(string)); tempTable.Columns.Add("LastLogon", typeof(DateTime)); //convert time to est DateTime easternTime = Utils.ConvertUTCToEST(computer.LastLogon.Value); tempTable.Rows.Add(computer.Name, easternTime); //finalize string for webpage return(Utils.ConvertDataTableToHTML(tempTable, "adComputer")); } else { return("<br>Computer not found in AD<br><br>"); } } }
private ComputerPrincipal GetComputerPrincipal(string ComputerName) { PrincipalContext pc = GetPrincipalContext(); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, ComputerName); return(computer); }
/// <summary> /// Public method for verifying if a given principal (user or machine) is a member of a given group. /// </summary> /// <param name="principalName">string</param> /// <param name="type">PrincipalType</param> /// <param name="groupName">string</param> /// <returns>bool</returns> public static bool IsMemberOf(string principalName, PrincipalType type, string groupName) { bool returnValue = false; PrincipalContext context = new PrincipalContext(ContextType.Domain); try { switch (type) { case PrincipalType.Machine: using (var comp = ComputerPrincipal.FindByIdentity(context, principalName)) { returnValue = IsMemberOf(groupName, comp); } break; case PrincipalType.User: using (var user = UserPrincipal.FindByIdentity(context, principalName)) { returnValue = IsMemberOf(groupName, user); } break; } return(returnValue); } catch { throw; } finally { context = null; } }
private void TbSearch_TextChanged(object sender, EventArgs e) { try { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, tbSearch.Text); if (computer != null) { tbSearch.ForeColor = Color.Green; btnDelete.Enabled = true; } else { tbSearch.ForeColor = Color.Red; btnDelete.Enabled = false; } } } catch (Exception) { } }
private void tbpAdvanced_Enter(object sender, EventArgs e) { Thread thloadAdvanced = new Thread(() => { try { Thread.CurrentThread.Name = "thloadAdvanced"; this.Invoke((MethodInvoker) delegate { pBoxProgressAdvanced.Visible = true; }); ADLib LdapHelper = new ADLib(); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), this.machineToQuery); System.DirectoryServices.DirectoryEntry underField = computer.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry; DataTable advancedData = LdapHelper.FillDataTableFromADContainer(underField); this.Invoke((MethodInvoker) delegate { dGridAdvanced.DataSource = advancedData; dGridAdvanced.Columns[1].Width = 300; pBoxProgressAdvanced.Visible = false; }); } catch { Thread.CurrentThread.Abort(); } }); thloadAdvanced.Start(); }
private void buttonMovePC_Click(object sender, EventArgs e) { try { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain)) { // find a computer ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, computername); DirectoryEntry de = (DirectoryEntry)computer.GetUnderlyingObject(); de.MoveTo(new DirectoryEntry("LDAP://" + comboBoxOUList.Text)); de.CommitChanges(); de.Dispose(); computer.Dispose(); } System.Windows.Forms.MessageBox.Show(computername + " has been moved to " + comboBoxOUList.Text, "Moving computer to OU", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (SystemException err) { System.Windows.Forms.MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); this.Close(); } }
private void BtnDelete_Click(object sender, EventArgs e) { DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("Are you sure you want to permanently delete this computer from active directory?", "Warning!", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { DialogResult dialogResult1 = System.Windows.Forms.MessageBox.Show("Are you sure? This action cannot be undone!", "Warning!", MessageBoxButtons.YesNo); if (dialogResult1 == DialogResult.Yes) { try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, tbSearch.Text); if (computer != null) { computer.Delete(); } else { return; } } catch (Exception) { } } } }
/// <summary> /// Retire une machine dans un groupe donné. /// </summary> /// <param name="groupName"></param> /// <param name="computerName"></param> public void RemoveComputerToGroup(string groupName, string computerName) { try { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName)) { if (group != null) { ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(_adConnection, IdentityType.Name, computerName); if (computer != null) { Logger?.Info("Ajout de PC : " + computerName + " dans le groupe " + groupName); group.Members.Remove(computer); group.Save(); } else { Logger?.Warn("Le PC : " + computerName + " n'existe pas !"); } } else { Logger?.Warn("Le groupe : " + groupName + " n'existe pas !"); } } } catch (Exception exception) { Logger?.Error("Error RemoveComputerToGroup - groupName : " + groupName + " - computerName : " + computerName, exception); } }
/// <summary> /// Gets the computers summaries data. /// </summary> /// <returns>IEnumerable<ExpandoObject>.</returns> /// TODO Edit XML Comment Template for GetComputersSummariesData private IEnumerable <ExpandoObject> GetComputersSummariesData() { var data = new List <ExpandoObject>(); foreach (var distinguishedName in DistinguishedNames) { CancellationToken.ThrowIfCancellationRequested(); using (var principalContext = GetPrincipalContext()) using (var computerPrincipal = ComputerPrincipal.FindByIdentity( principalContext, IdentityType.DistinguishedName, distinguishedName)) { if (computerPrincipal == null) { continue; } data.Add( DataPreparer.PrepareData( DefaultComputerProperties, computerPrincipal)); } } return(data); }
public void Check() { try { var builder = new StringBuilder(); var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; if (string.IsNullOrWhiteSpace(domainName)) { Message = "\tNot domain joined"; return; } ComputerPrincipal principal = ComputerPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, domainName), Dns.GetHostName()); foreach (GroupPrincipal group in principal.GetGroups()) { builder.AppendLine(string.Format("\t{0}", group)); } Message = builder.ToString(); } catch { Message = "\tCheck failed [*]"; } }
private static string GetDistinguishedName(string computerName) { PrincipalContext oCtx = new PrincipalContext(ContextType.Domain); ComputerPrincipal oPrincipal = ComputerPrincipal.FindByIdentity(oCtx, computerName); string dn = oPrincipal.DistinguishedName; return(dn); }
/// <summary> /// This method searches for and returns a ComputerPrincipal object that corrosponds to the specified computer name. /// </summary> /// <param name="name">The unique identifier for the computer.</param> /// <returns>A ComputerPrincipal object.</returns> public static ComputerPrincipal GetComputer(string name) { PrincipalContext pc = GetPrincipalContext(); ComputerPrincipal cp = ComputerPrincipal.FindByIdentity(pc, name); return(cp); }
public Boolean AddComputerToGroup(String ADGroupName, String OSDComputerName) { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: Starting Web Service"); Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: ADGroupName received was: " + ADGroupName); Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: OSDComputerName received was: " + OSDComputerName); Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: Connecting to " + FQDNDomainName + "."); try { // Connect to Active Directory PrincipalContext AD = new PrincipalContext(ContextType.Domain, FQDNDomainName); string controller = AD.ConnectedServer; Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: Connected to " + string.Format("Domain Controller: {0}", controller)); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(AD, OSDComputerName); if (computer != null) { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: " + OSDComputerName + " computer found in AD, continue."); GroupPrincipal group = GroupPrincipal.FindByIdentity(AD, ADGroupName); if (group != null) { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: " + ADGroupName + " group found in AD, continue."); group.Members.Add(computer); group.Save(); Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: " + OSDComputerName + " computer added to " + ADGroupName + " group"); return(true); } else { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: " + ADGroupName + " group not found in AD"); return(false); } } else { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: " + OSDComputerName + "Machine not found in AD"); return(false); } } catch (Exception e) { Trace.WriteLine(DateTime.Now + ": AddComputerToGroup: Unhandled exception finding provider namespace on server " + e.ToString()); return(false); } }
//Device's group membership public void DeviceGroupMembership() { string deviceName = DeviceAssetNo.Text; string loginPwd = textBox1.Text; PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, loginUser, loginPwd); ComputerPrincipal device = ComputerPrincipal.FindByIdentity(ctx, deviceName); ComputerGroupListBox.Items.Clear(); foreach (var group in device.GetGroups()) { ComputerGroupListBox.Items.Add(group.Name); } }
///<summary> /// Проверяет, есть ли учетная запись Active Directory для указанного имени компьютера в указанном домене. /// </summary> private bool ExistsInAD(string computerName, string domain) { PrincipalContext context = new PrincipalContext(ContextType.Domain, domain); if (ComputerPrincipal.FindByIdentity(context, computerName) != null) { return(true); } else { return(false); } }
/// <summary> /// Deletes the specified computer account. /// </summary> /// <param name="name">The unique identifier of the computer.</param> /// <returns>True if the computer was deleted, false if not or the computer doesn't exist.</returns> public static Boolean DeleteComputer(string name) { try { ComputerPrincipal c = ComputerPrincipal.FindByIdentity(GetPrincipalContext(), name); c.Delete(); c.Save(); return(true); } catch { return(false); } }
public bool IsAccountGmsa(SecurityIdentifier serviceAccount) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { using (ComputerPrincipal cmp = ComputerPrincipal.FindByIdentity(ctx, IdentityType.Sid, serviceAccount.ToString())) { if (cmp != null) { return(string.Equals(cmp.StructuralObjectClass, "msDS-GroupManagedServiceAccount", StringComparison.OrdinalIgnoreCase)); } } } return(false); }
public static adComputers adComputerDetailsFinder(PrincipalContext context, string computer) { adComputers adComputer = new adComputers(); try { ComputerPrincipal comp = ComputerPrincipal.FindByIdentity(context, computer); if (comp != null) { DirectoryEntry deepDetails = comp.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry; adComputer.Name = comp.Name; adComputer.DN = comp.DistinguishedName; adComputer.Description = comp.Description; if (deepDetails.Properties.Contains("operatingSystem")) { adComputer.OS = deepDetails.Properties["operatingSystem"].Value.ToString(); } if (deepDetails.Properties.Contains("whenCreated")) { adComputer.CreationDate = deepDetails.Properties["whenCreated"].Value.ToString(); } if (deepDetails.Properties.Contains("whenChanged")) { adComputer.ChangedDate = deepDetails.Properties["whenChanged"].Value.ToString(); } if (deepDetails.Properties.Contains("ms-Mcs-AdmPwd")) { adComputer.LapPAS = deepDetails.Properties["ms-Mcs-AdmPwd"].Value.ToString(); } if (deepDetails.Properties.Contains("ms-Mcs-AdmPwdExpirationTime")) { Int64 lastLogonThisServer = new Int64(); try { IADsLargeInteger lgInt = (IADsLargeInteger)deepDetails.Properties["ms-Mcs-AdmPwdExpirationTime"].Value; lastLogonThisServer = ((long)lgInt.HighPart << 32) + lgInt.LowPart; adComputer.LapPASExpirationDate = (DateTime.FromFileTime(lastLogonThisServer)).ToString(); } catch (Exception e) { } } } } catch { Exception e; } return(adComputer); }
public Computer(string ComputerData) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Connections.LDAPConnection)) { using (ComputerPrincipal currentComputer = ComputerPrincipal.FindByIdentity(ctx, ComputerData)) { DistinguishedName = currentComputer.DistinguishedName; Name = currentComputer.Name; Description = currentComputer.Description; Created = Functions.GetProperty(currentComputer, "whenCreated"); Changed = Functions.GetProperty(currentComputer, "whenChanged"); GUID = (Guid)currentComputer.Guid; OperatingSystem = new ComputerOperatingSystem(currentComputer); } } }
/// <summary> /// the computer principle /// </summary> public virtual ComputerPrincipal GetComputerPrinciple() { int tryCount = 0; ComputerPrincipal comp = null;; while (comp == null && tryCount < 10) { comp = ComputerPrincipal.FindByIdentity(_Context, IdentityType.SamAccountName, this.SamAccountName); System.Threading.Thread.Sleep(1000); tryCount++; } if (comp == null) { throw new Exception("Failed to retrieve ComputerPrincipal for " + this.SamAccountName); } return(comp); }
public static void DeleteComputerAccountVoid(string serverName) { // Set up domain context. PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain); // Check if an existing computer account exists in AD. ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, serverName); while (computer == null) { computer = ComputerPrincipal.FindByIdentity(pc, serverName); } if (computer != null) { computer.Delete(); } }
public Utilities.ItemRunResult RunItem(int EmpID, RunPayload RunPayload) { DataLayer.EPSEntities db = new DataLayer.EPSEntities(); Utilities util = new Utilities(); try { String myName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; LibraryItem li = db.LibraryItems.Where(l => l.LibraryPath.EndsWith(myName + ".dll")).FirstOrDefault(); String htmlOptions = li.HtmlOptions; String domain = util.GetParam("ADDomain", "Active Directory domain"); String adminName = util.GetParam("ADUsername", "Active Directory admin user"); String password = util.GetParam("ADPassword", "Active Directory admin user password"); List <RunPayloadItem> thisPL = RunPayload.RunPayloadItems.Where(p => p.ItemID == li.ItemID).ToList(); string compAcct = thisPL.Where(p => p.ElementID == "CompAcct").FirstOrDefault().ElementValue; PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, adminName, password); ComputerPrincipal comp = ComputerPrincipal.FindByIdentity (context, compAcct); if (comp == null) { return(new Utilities.ItemRunResult { ResultID = 4, ResultText = String.Format("{0} could not be found in Active Directory.", compAcct), TimeDone = DateTime.Now }); } comp.Delete(); return(new Utilities.ItemRunResult { ResultID = 2, ResultText = String.Format("Computer name: {0} was removed from Active Directory.", compAcct), TimeDone = DateTime.Now }); } catch (Exception ex) { return(new Utilities.ItemRunResult { ResultID = 4, ResultText = String.Format("Error: {0}", ex.Message), TimeDone = DateTime.Now }); } }
public bool AddComputerToGroup(string computerName, string groupName) { bool done = false; GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName); if (group == null) { group = new GroupPrincipal(context, groupName); } ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(context, computerName); if (computer != null & group != null) { group.Members.Add(computer); group.Save(); done = (computer.IsMemberOf(group)); } return(done); }
public static bool CheckComputerSecurityGroup(string computerName, string groupNames, string domain) { List <string> groupName = groupNames.ToUpper().Split(',').ToList(); List <string> groups = new List <string>(); PrincipalContext domainContext = new PrincipalContext(ContextType.Domain); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(domainContext, computerName); using (var directoryEntry = new DirectoryEntry("LDAP://" + computer.DistinguishedName)) { PropertyValueCollection ValueCollection = directoryEntry.Properties["memberOf"]; IEnumerator en = ValueCollection.GetEnumerator(); while (en.MoveNext()) { if (en.Current != null) { string group = en.Current.ToString().Substring(3, (en.Current.ToString()).IndexOf(',') - 3); if (!groups.Contains(group)) { groups.Add(group); //if (recursive) //AttributeValuesMultiString(attributeName, en.Current.ToString(), valuesCollection, true); } } } } foreach (string name in groupName) { Console.WriteLine("\t{0}", name); } foreach (string g in groups) { string query = groupName.Find(group => group == g.ToUpper()); if (query != null) { return(true); } } return(false); }
public static List <adGroups> adComputerGroups(PrincipalContext ctx, string adComputer) { List <adGroups> lstADGroups = new List <adGroups>(); ComputerPrincipal comp = ComputerPrincipal.FindByIdentity(ctx, adComputer); if (comp != null) { PrincipalSearchResult <Principal> groups = comp.GetGroups(); foreach (Principal p in groups) { adGroups adGroup = new adGroups(); if (p is GroupPrincipal) { adGroup.Name = p.Name; adGroup.DN = p.DistinguishedName; lstADGroups.Add(adGroup); } } } return(lstADGroups); }
protected override byte[] GetIdentifierHash() { _traceManager?.TraceDebug("MachineDomainSIDIdentifier.GetIdentifierHash"); try { System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain(); _traceManager?.TraceDebug("MachineDomainSIDIdentifier.GetIdentifierHash : Le poste appartient à un domaine"); } catch (Exception e) { _traceManager?.TraceDebug(e, "MachineDomainSIDIdentifier.GetIdentifierHash : Le poste n'appartient pas à un domaine"); return(null); } string sid = null; try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, IdentityType.Name, Environment.MachineName); sid = computer.Sid.Value; _traceManager?.TraceDebug("MachineDomainSIDIdentifier.GetIdentifierHash : Le sid de la machine dans le domaine est : {0}", sid ?? String.Empty); } catch (Exception e) { _traceManager?.TraceError(e, "MachineDomainSIDIdentifier.GetIdentifierHash : Le sid de la machine dans le domaine est impossible à déterminer"); } if (sid != null) { return(base.ComputeHash(sid)); } else { return(null); } }
private void RunLocation() // Runs all code related to location & location sources { string location_string = ""; foreach (string locationQuery in this.Queries["Location"]) { if (locationQuery == "OU") { try { int ouLevel; bool ouLevelSuccess = int.TryParse(Settings["OULevel"], out ouLevel); if (!ouLevelSuccess) { ouLevel = 1; } string[] machineOU; using (var context = new PrincipalContext(ContextType.Domain)) using (var comp = ComputerPrincipal.FindByIdentity(context, Environment.MachineName)) machineOU = comp.DistinguishedName.Split(',').SkipWhile(s => !s.StartsWith("OU=")).ToArray(); location_string = machineOU[0].Split('=')[ouLevel]; } catch (Exception e) { Trace.WriteLine("Could not get location from OU"); Trace.WriteLine(e.ToString()); Trace.WriteLine("Getting location from config file instead"); location_string = Settings["Location"]; } } else { location_string = Settings["Location"]; } } this.Values.Add("Location", location_string); }
public bool CanAccountBeDelegated(SecurityIdentifier serviceAccount) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { using (UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.Sid, serviceAccount.ToString())) { if (u != null) { return(u.DelegationPermitted); } } using (ComputerPrincipal cmp = ComputerPrincipal.FindByIdentity(ctx, IdentityType.Sid, serviceAccount.ToString())) { if (cmp != null) { return(cmp.DelegationPermitted); } } } return(false); }