static void Main() { try { String strPath = "IIS://localhost/W3SVC/1/Root"; String strName = ""; // Create a new 'DirectoryEntry' with the given path. DirectoryEntry myDE = new DirectoryEntry(strPath); DirectoryEntries myEntries = myDE.Children; // Create a new entry 'Sample' in the container. DirectoryEntry myDirectoryEntry = myEntries.Add("Sample", myDE.SchemaClassName); // Save changes of entry in the 'Active Directory'. myDirectoryEntry.CommitChanges(); Console.WriteLine(myDirectoryEntry.Name + " entry is created in container."); // Find 'Sample' entry in container. myDirectoryEntry = myEntries.Find("Sample", myDE.SchemaClassName); Console.WriteLine(myDirectoryEntry.Name + " found in container."); // Remove 'Sample' entry from container. strName = myDirectoryEntry.Name; myEntries.Remove(myDirectoryEntry); Console.WriteLine(strName + " entry is removed from container."); } catch (Exception e) { Console.WriteLine("The following exception was raised : {0}", e.Message); } }
private bool DeleteVirtualDirectory() { bool bSuccess = false; try { Log.LogMessage(MessageImportance.Normal, "Deleting virtual directory '{0}' on '{1}:{2}'.", VirtualDirectoryName, ServerName, ServerPort); VerifyIISRoot(); DirectoryEntry iisRoot = new DirectoryEntry(IISServerPath); DirectoryEntries childEntries = iisRoot.Children; iisRoot.RefreshCache(); DirectoryEntry childVDir = iisRoot.Children.Find(VirtualDirectoryName, iisRoot.SchemaClassName); childEntries.Remove(childVDir); childVDir.Close(); iisRoot.Close(); bSuccess = true; Log.LogMessage(MessageImportance.Normal, "Done."); } catch (Exception ex) { Log.LogErrorFromException(ex); } return(bSuccess); }
// Ref http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentries.remove(v=vs.110).aspx private static bool RemoveAutoUserFromCM(string usernametoremove, string machineName) { // Split out the userName var userName = usernametoremove.Split('_')[1]; DirectoryEntry AD = new DirectoryEntry("WinNT://" + machineName + ",computer"); DirectoryEntries daChildren = AD.Children; var userToRemove = daChildren.Find(userName, "User"); try { daChildren.Remove(userToRemove); //Do Something with --> ex.Message.ToString(); Log.Success(string.Format("User {0} removed successfully.", userName)); return(true); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //Do Something with --> ex.Message.ToString(); Log.Error(string.Format("Unable to remove \"{0}\" from CM, Error:{1}", userName, ex.Message)); return(false); } finally { if (null != AD) { AD.Dispose(); } } }
public static void DeleteUser(string passedName) { DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(passedName); users.Remove(user); }
static void Main(string[] args) { int delcount = 0; Boolean ignore = false; Boolean sys = false; string name = null; string[] ignoreList = { "guest", "wdagutilityaccount" }; string sPath = "WinNT://" + Environment.MachineName + ",computer"; DirectoryEntry localDirectory = new DirectoryEntry(sPath); using (var computerEntry = localDirectory) foreach (DirectoryEntry childEntry in computerEntry.Children) { if (childEntry.SchemaClassName == "User") { name = childEntry.Name; ignore = false; sys = false; for (int i = 0; i < ignoreList.Length; i++) { if (name.ToLower().Equals(ignoreList[i])) { ignore = true; i = ignoreList.Length + 5; } } if (!ignore) { object obGroups = childEntry.Invoke("Groups"); foreach (object ob in (System.Collections.IEnumerable)obGroups) { DirectoryEntry obGpEntry = new DirectoryEntry(ob); if (obGpEntry.Name.ToLower().Equals("administrators") || obGpEntry.Name.ToLower().Equals("system managed accounts group")) { sys = true; } obGpEntry.Close(); } if (!sys) { try { DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(name); users.Remove(user); delcount++; } catch (Exception err) { Console.WriteLine(err.ToString()); } } } } } Console.WriteLine("\t " + delcount + "Users Deleted"); }
private static void RemoveLocalUser(string username) { string dir = $"C:\\Users\\{username}"; DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString()); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find($"{username}"); users.Remove(user); //remove the user account from the pc DelDir(dir); }
/// <summary> /// Deletes the group. /// </summary> /// <param name="groupName">Name of the group.</param> public static void DeleteGroup(string groupName) { using (DirectoryEntry localEntry = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries localChildren = localEntry.Children; using (DirectoryEntry groupEntry = localChildren.Find(groupName, "Group")) { localChildren.Remove(groupEntry); } } }
/// <summary> /// Deletes a windows user based on an Id. /// </summary> /// <param name="id">The id that was used to create the user.</param> public static void DeleteUser(string id) { string decoratedUsername = DecorateUser(id); using (DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString())) { DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(decoratedUsername); users.Remove(user); } }
/// <summary> /// Deletes the user. /// </summary> /// <param name="userName">Name of the user.</param> public static void DeleteUser(string userName) { using (DirectoryEntry localEntry = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries localChildren = localEntry.Children; using (DirectoryEntry userEntry = localChildren.Find(userName, "User")) { localChildren.Remove(userEntry); } } }
public void DeleteUser(string userName) { using (var localDirectory = new DirectoryEntry(directoryPath)) { DirectoryEntries users = localDirectory.Children; using (DirectoryEntry user = users.Find(userName)) { users.Remove(user); } } }
public void DeleteLocalGroup(string groupName) { using (var localDirectory = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries children = localDirectory.Children; using (DirectoryEntry group = children.Find(groupName, "group")) { children.Remove(group); } } }
public void Execute(IActivityRequest request, IActivityResponse response) { String userName = String.Empty; String computerName = String.Empty; userName = request.Inputs["User Name"].AsString(); computerName = request.Inputs["Computer Name"].AsString(); String aUserName = String.Empty; String aUserDomain = String.Empty; String aUserPassword = String.Empty; if (request.Inputs.Contains("Alternate Connection Username")) { aUserName = request.Inputs["Alternate Connection Username"].AsString(); } if (request.Inputs.Contains("Alternate Connection User Domain")) { aUserDomain = request.Inputs["Alternate Connection User Domain"].AsString(); } if (request.Inputs.Contains("Alternate Connection Password")) { aUserPassword = request.Inputs["Alternate Connection Password"].AsString(); } DirectoryEntry machine; if (aUserName.Equals(String.Empty) || aUserDomain.Equals(String.Empty) || aUserPassword.Equals(String.Empty)) { machine = new DirectoryEntry("WinNT://" + computerName); } else { machine = new DirectoryEntry("WinNT://" + computerName, string.Format("{0}@{1}", aUserName, aUserDomain), aUserPassword); } DirectoryEntries entries = machine.Children; DirectoryEntry user = entries.Find(userName); entries.Remove(user); machine.Close(); response.Publish("User Name", userName); }
public void DeleteVirtualDirectory() { try { DirectoryEntry folderRoot = new DirectoryEntry(iispath); DirectoryEntries rootEntries = folderRoot.Children; folderRoot.RefreshCache(); DirectoryEntry childVirDir = folderRoot.Children.Find(_vdirname, folderRoot.SchemaClassName); rootEntries.Remove(childVirDir); childVirDir.Close(); folderRoot.Close(); } catch (Exception e) { System.Diagnostics.Trace.Write(e.ToString()); } }
private static string DeleteUser(string userName) { DirectoryEntry user; DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries users = localMachine.Children; try { user = users.Find(userName); } catch (Exception erMess) { return("User not found!"); } users.Remove(user); return("User Delete!"); }
public void removeLocalUser(string name) { try { string user_name = name; DirectoryEntry local_computer_path = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries users = local_computer_path.Children; DirectoryEntry existing_user = users.Find(user_name); users.Remove(existing_user); Console.WriteLine("\nUSER REMOVED SUCCESSFULLY"); } catch (Exception exception_log) { Console.Clear(); Console.Write("=======================================================================================================================\n"); Console.WriteLine(exception_log.ToString() + "\n"); Console.Write("=======================================================================================================================\n"); Console.WriteLine("USER DOES NOT EXIST - OPERATION FAILED"); Thread.Sleep(5000); } }
private void button3_Click(object sender, EventArgs e) { try { if (lstUsers.SelectedItem == null) { return; } string username = lstUsers.SelectedItem.ToString(); DirectoryEntry host = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries entries = host.Children; DirectoryEntry user = entries.Find(username); entries.Remove(user); MessageBox.Show("User deleted"); button1.PerformClick(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
static void Main(string[] args) { Console.WriteLine("----------FIREWALL-----------"); #region firewall SetFirewallRule("Remote Assistance (DCOM-In)", false); SetFirewallRule("Remote Assistance (PNRP-In)", false); SetFirewallRule("Remote Assistance (RA Server TCP-In)", false); SetFirewallRule("Remote Assistance (SSDP TCP-In)", false); SetFirewallRule("Remote Assistance (SSDP UDP-In)", false); SetFirewallRule("Remote Assistance (TCP-In)", false); SetFirewallRule("Telnet Server", false); SetFirewallRule("netcat", false); #endregion Console.WriteLine("----------REGISTRIES-----------"); #region reg { string[] lines = File.ReadAllLines(@"regkeys.txt"); foreach (var line in lines) { string[] words = Regex.Split(line, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); SetRegistry(words[0].Replace("\"", ""), words[1], words[2], words[3]); } } #endregion #region features { string[] lines = File.ReadAllLines(@"features.txt"); foreach (var line in lines) { Console.WriteLine("Disabling " + line); //ExecuteCommand("dism /online /disable-feature /featurename:" + line); } } #endregion Console.WriteLine("flushing dns"); ExecuteCommand("ipconfig /flushdns"); Console.WriteLine("setting password age"); ExecuteCommand("net accounts /minpwlen:10"); ExecuteCommand("net accounts /minpwage:5"); ExecuteCommand("net accounts /maxpwage:30"); Console.WriteLine(@"Deleting media files in C:\Users"); Console.WriteLine("OWNING COMPUTER"); ExecuteCommand("icacls " + @"C:\Users" + " /setowner \"Administrators\" /T /C"); #region users { string[] admins = File.ReadAllLines(@"admins.txt"); string[] standards = File.ReadAllLines(@"standards.txt"); string[] combined = admins.Concat(standards).ToArray(); DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString()); DirectoryEntries users = localDirectory.Children; List <string> unauthorizedUsers = GetComputerUsers(); foreach (var userName in combined) { Console.WriteLine($"Found authorized user {userName}"); unauthorizedUsers.Remove(userName); } foreach (var unauthorizedUser in unauthorizedUsers) { try { Console.WriteLine($"Press enter to remove unauthorized user {unauthorizedUser}"); Console.ReadKey(); DirectoryEntry user = users.Find(unauthorizedUser); users.Remove(user); Console.WriteLine($"Removed unauthorized user {unauthorizedUser}"); } catch (Exception e) { Console.WriteLine($"failed to remove unauthorized user {unauthorizedUser}"); Console.WriteLine(e.ToString()); } } foreach (var userName in admins) { try { DirectoryEntry user = users.Find(userName); Console.WriteLine($"Found admin {userName}"); } catch { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add(userName, "user"); NewUser.Invoke("SetPassword", new object[] { "Exploratory123$" }); NewUser.Invoke("Put", new object[] { "Description", "admin user added by script" }); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Administrators", "group"); if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } Console.WriteLine($"Admin account {userName} Created Successfully"); Console.WriteLine($"Password: Exploratory123$"); } } foreach (var userName in standards) { try { DirectoryEntry user = users.Find(userName); Console.WriteLine($"Found standard user {userName}"); } catch { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add(userName, "user"); NewUser.Invoke("SetPassword", new object[] { "Exploratory123$" }); NewUser.Invoke("Put", new object[] { "Description", "standard user added by script" }); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Users", "group"); if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } Console.WriteLine($"Standard account {userName} Created Successfully"); Console.WriteLine($"Password: Exploratory123$"); } } } #endregion Console.ReadKey(); }
private void Grabar() { bool bErrorControlado = false; ArrayList aListCorreo = new ArrayList(); string sAsunto = ""; string sTexto = ""; string sTO = ""; string strFecIniOld = ""; string strFecFinOld = ""; string strInteresadoOld = ""; string strEmpresaOld = ""; string sUsuario = "", sPassword = ""; if (this.hdnIDReserva.Text != "") { //Si se trata de una reserva existente, se obtienen sus datos //para luego comunicar las modificaciones realizadas. WIFI oWifi = WIFI.Obtener(null, int.Parse(this.hdnIDReserva.Text)); strFecIniOld = oWifi.t085_fechoraini.ToString(); strFecFinOld = oWifi.t085_fechorafin.ToString(); strInteresadoOld = oWifi.t085_interesado; strEmpresaOld = oWifi.t085_empresa; if (strFecIniOld.Length == 19) { strFecIniOld = strFecIniOld.Substring(0, 16); } else { strFecIniOld = strFecIniOld.Substring(0, 15); } if (strFecFinOld.Length == 19) { strFecFinOld = strFecFinOld.Substring(0, 16); } else { strFecFinOld = strFecFinOld.Substring(0, 15); } } SqlConnection oConn = Conexion.Abrir(); SqlTransaction tr = Conexion.AbrirTransaccion(oConn); DateTime dInicio = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue); DateTime dFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue); DateTime dNow = DateTime.Now; try { if (this.hdnIDReserva.Text == "") //insert { #region Código Insert sEsInsert = "true"; string sTicks = DateTime.Now.Ticks.ToString(); //string sTicksReducida = sTicks.Substring(10, 8); //sUsuario = "IB" + EncodeTo64(sTicksReducida).Substring(0, 6).ToUpper(); //sPassword = EncodeTo64((int.Parse(sTicksReducida) + ((int)Session["CR2I_IDFICEPI"] * int.Parse(sTicksReducida))).ToString()); //sPassword = sPassword.Substring(sPassword.Length - 10, 8); sPassword = sTicks.Substring(sTicks.Length - 4, 4); //sUsuario = "ib" + sTicksReducida; //sPassword = (int.Parse(sTicks.Substring(0, 8)) * (int)Session["CR2I_IDFICEPI"]).ToString().Substring(0, 8); //sPassword = (long.Parse(sTicks.Substring(sTicks.Length - 8, 8)) * long.Parse(Session["CR2I_IDFICEPI"].ToString())).ToString(); //sPassword = sPassword.Substring(sPassword.Length-8, 8); //Datos de la reserva byte nEstado = 1; if (dInicio < dNow && dFin > dNow) { nEstado = 2; } int nResul = WIFI.Insert(tr, (int)Session["CR2I_IDFICEPI"], txtInteresado.Text, txtEmpresa.Text, dInicio, dFin, txtObservaciones.Text, nEstado, sPassword); sUsuario = "ib" + nResul.ToString().Substring(nResul.ToString().Length - 4, 4); txtUsuario.Text = sUsuario; txtPwd.Text = sPassword; try { if (dInicio < dNow && dFin > dNow) {//hay que crear la reserva directamente en el LDAP DirectoryEntry de = new DirectoryEntry("LDAP://172.20.254.150:389/ou=people,dc=visitas,dc=ib", "cn=vadmin,dc=visitas,dc=ib", "PruebaLDAP", AuthenticationTypes.FastBind); DirectoryEntries entries = de.Children; DirectoryEntry oUser = entries.Add("cn=" + sUsuario, "inetOrgPerson"); //oUser.Properties["dn"].Add("cn=" + sUsuario + ",ou=people,dc=visitas,dc=ib"); oUser.Properties["objectClass"].Add("inetOrgPerson"); oUser.Properties["cn"].Add(sUsuario); oUser.Properties["sn"].Add(sUsuario); oUser.Properties["uid"].Add(sUsuario); oUser.Properties["userpassword"].Add(sPassword); oUser.Properties["ou"].Add("Visitas"); oUser.CommitChanges(); //DirectoryEntry oUserDelete = entries.Find("cn=" + sUsuario, "inetOrgPerson"); //entries.Remove(oUserDelete); //generar error //DirectoryEntry oUserDeletex = entries.Find("cn=x" + sUsuario, "inetOrgPerson"); } } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } catch (Exception ex) { sErrores = "Error : " + ex.Message; } hdnIDReserva.Text = nResul.ToString(); sTO = Session["CR2I_IDRED"].ToString(); sAsunto = "Reserva WIFI"; string sFecIni = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue).ToString(); if (sFecIni.Length == 19) { sFecIni = sFecIni.Substring(0, 16); } else { sFecIni = sFecIni.Substring(0, 15); } string sFecFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue).ToString(); if (sFecFin.Length == 19) { sFecFin = sFecFin.Substring(0, 16); } else { sFecFin = sFecFin.Substring(0, 15); } sTexto = "<p style='font-size:12px'>" + this.txtSolicitante.Text + @" ha solicitado una reserva WIFI para <b>" + this.txtInteresado.Text + @"</b><br /><br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + sFecIni + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + sFecFin + @"<br /><br /> <span style='width:150px'><b>Usuario:</b></span> " + txtUsuario.Text + @"<br /> <span style='width:150px'><b>Contraseña:</b></span> " + txtPwd.Text + @"<br /><br /> <span style='width:150px'><b>Observaciones:</b></span> " + txtObservaciones.Text.Replace(((char)10).ToString(), "<br />") + @"<br /><br /><br /><br /></p>"; string[] aMail = { sAsunto, sTexto, sTO, "", "I", "" }; aListCorreo.Add(aMail); #endregion } else //update { #region Código Update //Datos de la reserva WIFI oWifi = WIFI.Obtener(tr, int.Parse(hdnIDReserva.Text)); byte nEstado = oWifi.t085_estado; if (dInicio < dNow && dFin > dNow) { nEstado = 2; } WIFI.Actualizar(tr, int.Parse(hdnIDReserva.Text), (int)Session["CR2I_IDFICEPI"], txtInteresado.Text, txtEmpresa.Text, dInicio, dFin, txtObservaciones.Text, nEstado, txtPwd.Text); try { if (dInicio < dNow && dFin > dNow) { DirectoryEntry de = new DirectoryEntry("LDAP://172.20.254.150:389/ou=people,dc=visitas,dc=ib", "cn=vadmin,dc=visitas,dc=ib", "PruebaLDAP", AuthenticationTypes.FastBind); DirectoryEntries entries = de.Children; //1º Borrar la reserva WIFI que pudiera existir. try { DirectoryEntry oUserDelete = entries.Find("cn=" + txtUsuario.Text, "inetOrgPerson"); entries.Remove(oUserDelete); } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } //2º Hay que crear la reserva directamente en el LDAP DirectoryEntry oUser = entries.Add("cn=" + txtUsuario.Text, "inetOrgPerson"); //oUser.Properties["dn"].Add("cn=" + sUsuario + ",ou=people,dc=visitas,dc=ib"); oUser.Properties["objectClass"].Add("inetOrgPerson"); oUser.Properties["cn"].Add(txtUsuario.Text); oUser.Properties["sn"].Add(txtUsuario.Text); oUser.Properties["uid"].Add(txtUsuario.Text); oUser.Properties["userpassword"].Add(txtPwd.Text); oUser.Properties["ou"].Add("Visitas"); oUser.CommitChanges(); } } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } catch (Exception ex) { sErrores = "Error : " + ex.Message; } sTO = Session["CR2I_IDRED"].ToString(); sAsunto = "Modificación reserva WIFI."; string sFecIni = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue).ToString(); if (sFecIni.Length == 19) { sFecIni = sFecIni.Substring(0, 16); } else { sFecIni = sFecIni.Substring(0, 15); } string sFecFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue).ToString(); if (sFecFin.Length == 19) { sFecFin = sFecFin.Substring(0, 16); } else { sFecFin = sFecFin.Substring(0, 15); } sTexto = @"<p style='font-size:12px'>La reserva WIFI <br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + strFecIniOld + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + strFecFinOld + @"<br /><br /> <span style='width:150px'><b>Interesado:</b></span> " + strInteresadoOld + @"<br /> <br />Ha sido modificada por " + Session["CR2I_APELLIDO1"].ToString() + @" " + Session["CR2I_APELLIDO2"].ToString() + @", " + Session["CR2I_NOMBRE"].ToString() + @" y se reservará <br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + sFecIni + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + sFecFin + @"<br /><br /> <span style='width:150px'><b>Interesado:</b></span> " + txtInteresado.Text + @"<br /><br /> <span style='width:150px'><b>Usuario:</b></span> " + txtUsuario.Text + @"<br /> <span style='width:150px'><b>Contraseña:</b></span> " + txtPwd.Text + @"<br /><br /><br /><br /></p>"; string[] aMail = { sAsunto, sTexto, sTO, "", "I", "" }; aListCorreo.Add(aMail); #endregion } Conexion.CommitTransaccion(tr); sResultadoGrabacion = "OK"; } catch (Exception ex) { if (!bErrorControlado) { sErrores += Errores.mostrarError("Error al realizar la reserva:", ex); } else { sErrores = ex.Message; } Conexion.CerrarTransaccion(tr); } finally { Conexion.Cerrar(oConn); } try { Correo.EnviarCorreos(aListCorreo); } catch (Exception ex) { sErrores += Errores.mostrarError("Error al enviar los mails de convocatoria:", ex); } }