public void TestDomain() { using (Domain domain = Domain.GetDomain(ActiveDirectoryContext)) { Assert.Equal(domain.Forest.Name, Forest.GetForest(ActiveDirectoryContext).Name); Assert.NotNull(domain.Children); DomainControllerCollection domainControllers = domain.DomainControllers; Assert.True(domainControllers.Contains(domain.PdcRoleOwner)); Assert.True(domainControllers.IndexOf(domain.RidRoleOwner) >= 0); Assert.True(domainControllers.Contains(domain.InfrastructureRoleOwner)); Assert.True(domain.DomainModeLevel >= 0); Assert.True( domain.DomainMode == DomainMode.Unknown || domain.DomainMode == DomainMode.Windows2000MixedDomain || domain.DomainMode == DomainMode.Windows2000NativeDomain || domain.DomainMode == DomainMode.Windows2003Domain || domain.DomainMode == DomainMode.Windows2003InterimDomain || domain.DomainMode == DomainMode.Windows2008Domain || domain.DomainMode == DomainMode.Windows2008R2Domain || domain.DomainMode == DomainMode.Windows2012R2Domain || domain.DomainMode == DomainMode.Windows8Domain); if (domain.Forest.RootDomain.Name.Equals(domain.Name)) { Assert.Null(domain.Parent); } Assert.Throws <ArgumentNullException>(() => domain.GetSidFilteringStatus(null)); Assert.Throws <ArgumentException>(() => domain.GetSidFilteringStatus("")); } }
public void GetLastLogon() { string username = "******"; //update DirectoryContext context = new DirectoryContext( DirectoryContextType.Domain, "yourdomain.com" //update this ); DateTime latestLogon = DateTime.MinValue; string servername = null; DomainControllerCollection dcc = DomainController.FindAll(context); foreach (DomainController dc in dcc) { DirectorySearcher ds; using (dc) using (ds = dc.GetDirectorySearcher()) { ds.Filter = String.Format( "(sAMAccountName={0})", username ); ds.PropertiesToLoad.Add("lastLogon"); ds.SizeLimit = 1; SearchResult sr = ds.FindOne(); if (sr != null) { DateTime lastLogon = DateTime.MinValue; if (sr.Properties.Contains("lastLogon")) { lastLogon = DateTime.FromFileTime( (long)sr.Properties["lastLogon"][0] ); } if (DateTime.Compare(lastLogon, latestLogon) > 0) { latestLogon = lastLogon; servername = dc.Name; } } } } Console.WriteLine( "Last Logon: {0} at {1}", servername, latestLogon.ToString() ); }
public bool updateDomainControllers(DomainCollection domains) { ConfiguredDomainControllersList.Clear(); UnconfiguredDomainControllersList.Clear(); UnreachableDomainControllersList.Clear(); AllDomainControllers.Clear(); bool retVal = true; try { foreach (Domain domain in domains) { DomainControllerCollection dcCollection = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in dcCollection) { try { AllDomainControllers.Add(dc); if (checkSystemReachable(dc.IPAddress)) { if (checkRegKey(dc.IPAddress)) { ConfiguredDomainControllersList.Add(dc.Name); } else { UnconfiguredDomainControllersList.Add(dc.Name); } } else { UnreachableDomainControllersList.Add(dc.Name); } } catch (Exception e) { UnconfiguredDomainControllersList.Add(e.ToString()); } } } } catch (Exception ex) { UnconfiguredDomainControllersList.Add("Error Retrieving Domain Controllers"); ConfiguredDomainControllersList.Add("Error Retrieving Domain Controllers"); retVal = false; } return(retVal); }
public void TestDomainController() { using (Domain domain = Domain.GetDomain(ActiveDirectoryContext)) { DirectoryContext dc = new DirectoryContext( DirectoryContextType.Domain, domain.Name, LdapConfiguration.Configuration.UserName, LdapConfiguration.Configuration.Password); using (DomainController controller = DomainController.FindOne(dc)) { using (Forest forest = Forest.GetForest(ActiveDirectoryContext)) { Assert.Equal(forest.Name, controller.Forest.Name); } DomainControllerCollection dcc = DomainController.FindAll(dc); Assert.True(dcc.Contains(controller)); Assert.True(dcc.IndexOf(controller) >= 0); Assert.Equal(domain.Name, controller.Domain.Name); Assert.True(controller.CurrentTime > DateTime.Today.AddDays(-2)); Assert.True(controller.HighestCommittedUsn > 0); Assert.NotNull(controller.InboundConnections); Assert.NotNull(controller.OutboundConnections); foreach (ActiveDirectoryRole adr in controller.Roles) { Assert.True( adr == ActiveDirectoryRole.InfrastructureRole || adr == ActiveDirectoryRole.NamingRole || adr == ActiveDirectoryRole.PdcRole || adr == ActiveDirectoryRole.RidRole || adr == ActiveDirectoryRole.SchemaRole); Assert.True(controller.Roles.Contains(adr)); Assert.True(controller.Roles.IndexOf(adr) >= 0); } Assert.NotNull(controller.SiteName); Assert.True(controller.OSVersion.IndexOf("Windows", StringComparison.OrdinalIgnoreCase) >= 0); Assert.True(controller.IPAddress.IndexOf('.') >= 0); } } }
static void ReadEventLogs() { if (AllDCs) { try { DCList = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in DCList) { if (SkipDownDC.Contains(dc.Name)) { OutputToScreen("Skipping DC - " + dc.Name, ConsoleColor.Red); } else { DoReadEventLogs(timeInt, dc.Name.Split('.')[0], dc.SiteName); } } } catch (Exception exp) { OutputToScreen("Error - Cannot find all Domain Controllers - " + exp.Message.ToString(), ConsoleColor.Red); } } else { try { domain = Domain.GetComputerDomain(); DCList = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in DCList) { if (dc.Name.Split('.')[0].ToUpper() == server.ToUpper()) { oneDCName = dc.Name; oneDCSite = dc.SiteName; DoReadEventLogs(timeInt, oneDCName, oneDCSite); break; } } } catch (Exception exp) { OutputToScreen("Error - Cannot find one Domain Controller - " + exp.Message.ToString(), ConsoleColor.Red); } } }
public void updateDomainControllers() { ConfiguredDomainControllersList.Clear(); UnconfiguredDomainControllersList.Clear(); try { Forest forest = Forest.GetCurrentForest(); DomainCollection domCollection = forest.Domains; foreach (Domain domain in domCollection) { DomainControllerCollection dcCollection = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in dcCollection) { try { if (checkSystemReachable(dc.IPAddress)) { AllDomainControllers.Add(dc); if (checkRegKey(dc.IPAddress)) { ConfiguredDomainControllersList.Add(dc.Name); } else { UnconfiguredDomainControllersList.Add(dc.Name); } } } catch (Exception e) { UnconfiguredDomainControllersList.Add(e.ToString()); } } } } catch (Exception ex) { UnconfiguredDomainControllersList.Add("Error Retrieving Domain Controllers"); ConfiguredDomainControllersList.Add("Error Retrieving Domain Controllers"); } }
/// <summary> /// Finds the users last logon time over the whole domain /// </summary> /// <param name="userId">The Guid of the user</param> /// <returns>The time the user last logged on / authenticated with AD</returns> /// <remarks>Taken from http://stackoverflow.com/questions/19454162/getting-last-logon-time-on-computers-in-active-directory </remarks> public DateTime FindLastLogonTime(Guid userId) { DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, ACTIVE_DIRECTORY_DOMAIN); DateTime latestLogon = DateTime.MinValue; DomainControllerCollection dcc = DomainController.FindAll(context); var username = GetUsername(userId); foreach (DomainController dc in dcc.Cast <object>()) { DirectorySearcher ds; using (ds = dc.GetDirectorySearcher()) { try { ds.Filter = String.Format( "(sAMAccountName={0})", username ); ds.PropertiesToLoad.Add("lastLogon"); ds.SizeLimit = 1; SearchResult sr = ds.FindOne(); if (sr != null) { DateTime lastLogon = DateTime.MinValue; if (sr.Properties.Contains("lastLogon")) { lastLogon = DateTime.FromFileTime( (long)sr.Properties["lastLogon"][0] ); } if (DateTime.Compare(lastLogon, latestLogon) > 0) { latestLogon = lastLogon; } } } catch (Exception) { } } } return(latestLogon); }
private void GetDomainControllers() { try { DomainControllerCollection dcCollection = DomainController.FindAll(DirectoryContext); foreach (DomainController dc in dcCollection) { DomainControllers.Add(dc.IPAddress); } } catch (Exception e) { Mq.Error( "Something went wrong trying to find domain controllers. Try defining manually with -c?"); Mq.Degub(e.ToString()); Mq.Terminate(); } }
private GenericPrincipal AuthenticateAndAuthorize(string userName, string password) { GenericPrincipal genericPrincipal = null; DirectoryContext dc = new DirectoryContext(DirectoryContextType.Domain, "WE"); DomainControllerCollection domainControllers = Domain.GetDomain(dc).DomainControllers; foreach (DomainController domainController in domainControllers) { try { //File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", $"{ DateTime.Now } Trying to connecto DC { domainController.Name } { Environment.NewLine }"); genericPrincipal = Authorize(domainController.Name, userName, password); break; } catch (Exception) { //File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logerror.txt", $"{ DateTime.Now } Trying to connecto DC Failed { domainController.Name } { ex.Message } { Environment.NewLine }"); //move next, try new domain controller, else it will return null and 500 come out of the api } } if (genericPrincipal == null) { dc = new DirectoryContext(DirectoryContextType.Domain, "CORP"); domainControllers = Domain.GetDomain(dc).DomainControllers; foreach (DomainController domainController in domainControllers) { try { //File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", $"{ DateTime.Now } Trying to connecto DC { domainController.Name } { Environment.NewLine }"); genericPrincipal = Authorize(domainController.Name, userName, password); break; } catch (Exception) { //File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logerror.txt", $"{ DateTime.Now } Trying to connecto DC Failed { domainController.Name } { ex.Message } { Environment.NewLine }"); //move next, try new domain controller, else it will return null and 500 come out of the api } } } return(genericPrincipal); }
static void ResetFEValue(string s) { if (AllDCs) { DCList = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in DCList) { if (SkipDownDC.Contains(dc.Name)) { OutputToScreen("Skipping DC - " + dc.Name, ConsoleColor.Red); } else { DoTurnFEValueOnOrOff(s, dc.Name.Split('.')[0]); if (veryVerbose) { SetSearchThresholdValues(s, dc.Name.Split('.')[0]); } if (ResetDefaults) { SetSearchThresholdValues(s, dc.Name.Split('.')[0]); } } } } else { DoTurnFEValueOnOrOff(s, server); if (veryVerbose) { SetSearchThresholdValues(s, server); } if (ResetDefaults) { SetSearchThresholdValues(s, server); } } }
private DirectoryEntry GenerateDirectoryEntry() { DirectoryEntry directoryEntry = null; DomainControllerCollection domains = Domain.GetCurrentDomain().DomainControllers; foreach (DomainController controller in domains) { try { directoryEntry = new DirectoryEntry(string.Format("LDAP://{0}", controller.Name)); Logger.Verbose("Connected to " + controller.Name); break; } catch (Exception ex) { Logger.Warning("Failed to connect to " + controller.Name + ". Reason:" + ex.Message); } } if (directoryEntry == null) { throw new Exception("Failed to connect to AD"); } var username = Settings.GetStringValue("ActiveDirectory.Username"); var password = Settings.GetStringValue("ActiveDirectory.Password"); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { directoryEntry.Username = username; directoryEntry.Password = password; } return(directoryEntry); }
static void CreateSkipDownDCList() { DCList = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in DCList) { Console.Write("Connecting ... " + dc.Name); try { using (TcpClient client = new TcpClient()) { client.ReceiveTimeout = 2; client.SendTimeout = 2; IAsyncResult result = client.BeginConnect(dc.Name, 135, null, null); bool isConnected = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2)); if (isConnected) { Console.WriteLine(" ... Success!"); client.Close(); } else { Console.WriteLine(" ... Failure!"); SkipDownDC.Add(dc.Name); } } } catch (Exception exp) { Console.WriteLine(" ... Failure!"); SkipDownDC.Add(dc.Name); ErrWriter.WriteLine("Error creating skip list for " + dc.Name + " - " + exp.Message.ToString()); } } }
static void CalculateStats() { try { string statfile = "LDAPQuertyStats_" + TimeString + ".log"; File.Create(statfile).Close(); statwriter = new StreamWriter(statfile); statwriter.AutoFlush = true; } catch (Exception exp) { OutputToScreen("Error creating stats log - " + exp.Message.ToString(), ConsoleColor.Red); ErrWriter.WriteLine("Error creating stats log - " + exp.Message.ToString()); } try { Console.WriteLine(""); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); statwriter.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("Server Occurrences:"); statwriter.WriteLine("Server Occurrences:"); if (AllDCs) { DCList = domain.FindAllDiscoverableDomainControllers(); foreach (DomainController dc in DCList) { int total = ServerList.FindAll(s => s.Equals(dc.Name.Split('.')[0])).Count; Console.WriteLine(dc.Name.Split('.')[0] + " x " + total.ToString()); statwriter.WriteLine(dc.Name.Split('.')[0] + " x " + total.ToString()); } } else { int total = ServerList.FindAll(s => s.Equals(server)).Count; Console.WriteLine(server + " x " + total.ToString()); statwriter.WriteLine(server + " x " + total.ToString()); } Console.WriteLine(""); statwriter.WriteLine(""); Console.WriteLine("IP Occurrences:"); statwriter.WriteLine("IP Occurrences:"); ArrayList IPArray = new ArrayList(); foreach (string IPItem in IPList) { if (!IPArray.Contains(IPItem)) { IPArray.Add(IPItem); int total = IPList.FindAll(s => s.Equals(IPItem)).Count; Console.WriteLine(IPItem + " x " + total.ToString()); statwriter.WriteLine(IPItem + " x " + total.ToString()); } } Console.WriteLine(""); statwriter.WriteLine(""); Console.WriteLine("Site Occurrences"); statwriter.WriteLine("Site Occurrences"); ArrayList SiteArray = new ArrayList(); foreach (string site in SiteList) { if (!SiteArray.Contains(site)) { SiteArray.Add(site); int total = SiteList.FindAll(s => s.Equals(site)).Count; Console.WriteLine(site + " x " + total.ToString()); statwriter.WriteLine(site + " x " + total.ToString()); } } Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); statwriter.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine(""); statwriter.Flush(); statwriter.Close(); statwriter.Dispose(); } catch (Exception exp) { OutputToScreen("Error calculating stats - " + exp.Message.ToString(), ConsoleColor.Red); ErrWriter.WriteLine("Error calculating stats - " + exp.Message.ToString()); } }
/// <summary> /// Initialize information from PTF config /// </summary> /// <param name="testSite"></param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); Site.Log.Add(LogEntryKind.Debug, "Read common properties from PTF configure file."); AllowBreakEnvironment = GetBoolProperty(propertyGroup + "AllowBreakEnvironment"); DomainFunctionLevel = GetEnumProperty <DomainFunctionLevel>(propertyGroup + "DomainFunctionLevel"); DomainAdminGroup = GetProperty(propertyGroup + "DomainAdminGroup"); DomainAdministratorName = GetProperty(propertyGroup + "DomainAdministratorName", true); DomainUserPassword = GetProperty(propertyGroup + "DomainUserPassword", true); PrimaryDomainDnsName = GetProperty(propertyGroup + "PrimaryDomain.DNSName", true); PrimaryDomainNetBiosName = GetProperty(propertyGroup + "PrimaryDomain.NetBiosName" ?? (PrimaryDomainDnsName.Split('.'))[0].ToString()); PrimaryDomainSrvGUID = GetProperty(propertyGroup + "PrimaryDomain.ServerGUID", true); PrimaryDomainSID = GetProperty(propertyGroup + "PrimaryDomain.SID", true); PDCNetbiosName = GetProperty(propertyGroup + "WritableDC1.NetbiosName", true); PDCPassword = GetProperty(propertyGroup + "WritableDC1.Password", true); PDCIPAddress = GetProperty(propertyGroup + "WritableDC1.IPAddress"); PDCOSVersion = GetEnumProperty <ServerVersion>(propertyGroup + "WritableDC1.OSVersion"); PDCIsWindows = (PDCOSVersion == ServerVersion.NonWin ? false : true); SDCNetbiosName = GetProperty(propertyGroup + "WritableDC2.NetbiosName"); SDCPassword = GetProperty(propertyGroup + "WritableDC2.Password"); SDCIPAddress = GetProperty(propertyGroup + "WritableDC2.IPAddress"); SDCOSVersion = GetEnumProperty <ServerVersion>(propertyGroup + "WritableDC2.OSVersion"); SDCIsWindows = (SDCOSVersion == ServerVersion.NonWin ? false : true); RODCNetbiosName = GetProperty(propertyGroup + "RODC.NetbiosName"); RODCPassword = GetProperty(propertyGroup + "RODC.Password"); RODCIPAddress = GetProperty(propertyGroup + "RODC.IPAddress"); RODCOSVersion = GetEnumProperty <ServerVersion>(propertyGroup + "RODC.OSVersion"); RODCIsWindows = (RODCOSVersion == ServerVersion.NonWin ? false : true); ChildDomainDnsName = GetProperty(propertyGroup + "ChildDomain.DNSName"); ChildDomainNetBiosName = GetProperty(propertyGroup + "ChildDomain.NetBiosName") ?? (ChildDomainDnsName.Split('.'))[0].ToString(); CDCNetbiosName = GetProperty(propertyGroup + "CDC.NetbiosName"); CDCIPAddress = GetProperty(propertyGroup + "CDC.IPAddress"); CDCOSVersion = GetEnumProperty <ServerVersion>(propertyGroup + "CDC.OSVersion"); CDCIsWindows = (CDCOSVersion == ServerVersion.NonWin ? false : true); TrustDomainDnsName = GetProperty(propertyGroup + "TrustDomain.DNSName"); TrustDomainNetBiosName = GetProperty(propertyGroup + "TrustDomain.NetBiosName") ?? (TrustDomainDnsName.Split('.'))[0].ToString(); TDCNetbiosName = GetProperty(propertyGroup + "TDC.NetbiosName"); TDCIPAddress = GetProperty(propertyGroup + "TDC.IPAddress"); TDCOSVersion = GetEnumProperty <ServerVersion>(propertyGroup + "TDC.OSVersion"); TDCIsWindows = (TDCOSVersion == ServerVersion.NonWin ? false : true); DMNetbiosName = GetProperty(propertyGroup + "DM.NetbiosName"); DMPassword = GetProperty(propertyGroup + "DM.Password"); DMOldPassword = GetProperty(propertyGroup + "DM.OldPassword"); DMIPAddress = GetProperty(propertyGroup + "DM.IPAddress"); ENDPOINTNetbiosName = GetProperty(propertyGroup + "ENDPOINT.NetbiosName", true); ENDPOINTPassword = GetProperty(propertyGroup + "ENDPOINT.Password", true); ENDPOINTOldPassword = GetProperty(propertyGroup + "ENDPOINT.OldPassword"); ENDPOINTIPAddress = GetProperty(propertyGroup + "ENDPOINT.IPAddress"); ADLDSInstanceName = GetProperty(propertyGroup + "ADLDSInstanceName"); ADDSPortNum = GetProperty(propertyGroup + "ADDSPortNum"); ADLDSPortNum = GetProperty(propertyGroup + "ADLDSPortNum"); ADLDSSSLPortNum = GetProperty(propertyGroup + "ADLDSSSLPortNum"); LDSApplicationNC = GetProperty(propertyGroup + "LDSApplicationNC"); ClientUserName = GetProperty(propertyGroup + "ClientUserName"); ClientUserPassword = GetProperty(propertyGroup + "ClientUserPassword"); Site.Log.Add(LogEntryKind.Debug, "Read common properties from PTF configure file completed."); Site.Log.Add(LogEntryKind.Debug, "Construct common classes for domain, domain controller and endpoint."); domains = new DomainCollection(); domainControllers = new DomainControllerCollection(); Domain primaryDomain = new Domain(PrimaryDomainDnsName, PrimaryDomainNetBiosName); domains.Add(primaryDomain); DomainController pdc = new DomainController(primaryDomain, PDCNetbiosName, PDCIPAddress, (ServerVersion)PDCOSVersion); DomainController sdc = new DomainController(primaryDomain, SDCNetbiosName, SDCIPAddress, (ServerVersion)SDCOSVersion); DomainController rodc = new DomainController(primaryDomain, RODCNetbiosName, RODCIPAddress, (ServerVersion)RODCOSVersion); domainControllers.Add(pdc); domainControllers.Add(sdc); domainControllers.Add(rodc); if (string.IsNullOrEmpty(ChildDomainDnsName)) { Site.Log.Add(LogEntryKind.Warning, "ChildDomainDnsName is not configured in PTF, indicating the environment has no child domain."); } else { Domain childDomain = new Domain(ChildDomainDnsName); DomainController cdc = new DomainController(childDomain, CDCNetbiosName, CDCIPAddress, (ServerVersion)CDCOSVersion); domains.Add(childDomain); domainControllers.Add(cdc); } if (string.IsNullOrEmpty(TrustDomainDnsName)) { Site.Log.Add(LogEntryKind.Warning, "TrustDomainDnsName is not configured in PTF, indicating the environment has no trusted domain."); } else { Domain trustDomain = new Domain(TrustDomainDnsName); DomainController tdc = new DomainController(trustDomain, TDCNetbiosName, TDCIPAddress, (ServerVersion)TDCOSVersion); domains.Add(trustDomain); domainControllers.Add(tdc); } Computer endpoint = new Computer(primaryDomain, ENDPOINTNetbiosName, ENDPOINTIPAddress); domainMembers = new ComputerCollection(); domainMembers.Add(endpoint); Site.Log.Add(LogEntryKind.Debug, "Construct common classes for domain, domain controller and endpoint completed."); }
public void DiscoverDomain() { if (domain != null) { Console.WriteLine("Domain Name: {0}", domain.Name); Console.WriteLine("Domain Forest: {0}", domain.Forest.Name); Console.WriteLine("Domain Mode: {0}", domain.DomainMode); // 4.8 // Console.WriteLine("Domain Mode Level: {0}", domain.DomainModeLevel); if (domain.Parent != null) { Console.WriteLine("Domain Parent: {0}", domain.Parent); } else { Console.WriteLine("Domain Parent: {0}", "None"); } Console.WriteLine("Domain PDC: {0}", domain.PdcRoleOwner.ToString()); Console.WriteLine("Domain RID Master: {0}", domain.RidRoleOwner.ToString()); DomainControllerCollection dcDis = domain.FindAllDiscoverableDomainControllers(); DomainControllerCollection dcAll = domain.FindAllDomainControllers(); Console.WriteLine("All DCs: "); foreach (DomainController dc in dcAll) { try { Console.WriteLine("\tDomainController : {0}, {1}, {2}, {3}", dc.Name, dc.OSVersion, dc.SiteName, dc.IPAddress); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } } Console.WriteLine("All Discoverable DCs: "); foreach (DomainController dc in dcDis) { try { Console.WriteLine("\tDomainController :\n" + $"\t\tName: {dc.Name}\n" + $"\t\tDomain: {dc.Domain}\n" + $"\t\tForest: {dc.Forest}\n" + $"\t\tTime: {dc.CurrentTime}\n" + $"\t\tIP Address: {dc.IPAddress}\n" + $"\t\tOS Version: {dc.OSVersion}\n" + $"\t\tSite Name: {dc.SiteName}\n" + $"\t\tIs GC?: {dc.IsGlobalCatalog()}" ); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } foreach (ReplicationConnection ircc in dc.InboundConnections) { try { Console.WriteLine("Inbound Replication: {0} {1} {2} {3} {4} {5}", ircc.GetDirectoryEntry().Name, ircc.SourceServer, ircc.TransportType, ircc.ReplicationSpan, ircc.ReciprocalReplicationEnabled, ircc.DestinationServer ); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } } foreach (ReplicationConnection orcc in dc.OutboundConnections) { try { Console.WriteLine("Outbound Replication: {0} {1} from: {2} {3} reciprocal: {4} to: {5}", orcc.GetDirectoryEntry().Name, orcc.SourceServer, orcc.TransportType, orcc.ReplicationSpan, orcc.ReciprocalReplicationEnabled, orcc.DestinationServer ); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); } } } if (domain.Children.Count != 0) { Console.WriteLine("Domain Children: "); foreach (Domain d in domain.Children) { Console.WriteLine("{0}", d.Name); } } else { Console.WriteLine("Domain Children: {0}", "None"); } if (domain.GetAllTrustRelationships().Count != 0) { Console.WriteLine("Domain Trusts: "); foreach (TrustRelationshipInformation tri in domain.GetAllTrustRelationships()) { Console.WriteLine("\t\tSource: {0}, Target: {1}, Direction: {2}, Trust Type: {3}", tri.SourceName, tri.TargetName, tri.TrustDirection, tri.TrustType); } } else { Console.WriteLine("Domain Trusts: {0}", "None"); } } else { Console.WriteLine("Domain object not set"); } }
static void Main() { try { string targetName = "fabrikam.com"; string subnetName1 = "154.55.0.0/16"; string subnetName2 = "154.56.0.0/16"; string siteName = "myNewSite"; string siteLinkName = "DEFAULTIPSITELINK"; string defaultSiteName = "Default-First-Site-Name"; DirectoryContext domainContext = new DirectoryContext( DirectoryContextType.Domain, targetName); DirectoryContext forestContext = new DirectoryContext( DirectoryContextType.Forest, targetName); Forest forest = Forest.GetForest(forestContext); // create new site ActiveDirectorySite site = new ActiveDirectorySite(forestContext, siteName); site.Options = ActiveDirectorySiteOptions.GroupMembershipCachingEnabled; site.Save(); Console.WriteLine("\nSite \"{0}\" is created successfully", site); // create new subnets ActiveDirectorySubnet subnet1 = new ActiveDirectorySubnet(forestContext, subnetName1); subnet1.Location = "Bellevue"; subnet1.Site = site; subnet1.Save(); Console.WriteLine("\nSubnet \"{0}\" is created successfully", subnet1); ActiveDirectorySubnet subnet2 = new ActiveDirectorySubnet(forestContext, subnetName2, siteName); subnet2.Location = "Redmond"; subnet2.Save(); Console.WriteLine("\nSubnet \"{0}\" is created successfully", subnet2); Console.WriteLine("\nSite \"{0}\" contains subnet:", site.Name); foreach (ActiveDirectorySubnet subnet in site.Subnets) { Console.WriteLine("\tSubnet \"{0}\", location is {1}", subnet.Name, subnet.Location); } // add new site to an existing site link ActiveDirectorySiteLink link = ActiveDirectorySiteLink.FindByName( forestContext, siteLinkName); Console.WriteLine("\nAdd site \"{0}\" to site link \"{1}\"", site.Name, link.Name); link.Sites.Add(site); link.Save(); Console.WriteLine("\nSiteLink \"{0}\" has site: ", link); foreach (ActiveDirectorySite s in link.Sites) { Console.WriteLine("\tSite \"{0}\"", s); } // delete site and subnets site.Delete(); subnet1.Delete(); subnet2.Delete(); Console.WriteLine("\nSite and subnets are deleted successfully\n"); // existing site management // preferred RPC bridgehead server ActiveDirectorySite defaultSite = ActiveDirectorySite.FindByName( forestContext, defaultSiteName); Console.WriteLine("\nExisting PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } Console.WriteLine("\nAdd PreferredRpcBridgeheadServers"); DomainControllerCollection col = Domain.GetDomain(domainContext). FindAllDomainControllers(defaultSiteName); foreach (DirectoryServer s in col) { defaultSite.PreferredRpcBridgeheadServers.Add(s); } defaultSite.Save(); Console.WriteLine("\nAfter updating, PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } defaultSite.PreferredRpcBridgeheadServers.Clear(); defaultSite.Save(); Console.WriteLine("\nAfter Clear call, PreferredRpcBridgeheadServers is:"); foreach (DirectoryServer s in defaultSite.PreferredRpcBridgeheadServers) { Console.WriteLine("\tServer {0}", s.Name); } } catch (Exception e) { Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType().Name + ":" + e.Message); } }