Exemple #1
0
        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();
        }
Exemple #2
0
        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();
            }
        }
 public string GetComputerProperty(ComputerPrincipal computerPrincipal, string propertyName)
 {
     if (!(computerPrincipal.GetUnderlyingObject() is DirectoryEntry de))
     {
         return(string.Empty);
     }
     return(de.Properties.Contains(propertyName) ? de.Properties[propertyName].Value.ToString() : string.Empty);
 }
Exemple #4
0
        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);
        }
Exemple #5
0
        private void buttonRename_Click(object sender, EventArgs e)
        {
            m_form.Focus();
            m_form.OutputBox.AppendText("\r\nRenaming computer, please wait...");
            this.Hide();
            if ((checkIfOnDomain(computername) == true) && (checkDomainCreds(textBoxDomainUserName.Text, textBoxDomainPassword.Text) == true) && (checkLocalCreds(textBoxLocalUserName.Text, textBoxLocalPassword.Text) == true))
            {
                try
                {
                    System.Security.SecureString sec   = convertToSecureString(textBoxLocalPassword.Text);
                    NetworkCredential            local = new NetworkCredential(computername + "\\" + textBoxLocalUserName.Text, sec);

                    ConnectionOptions conn = new ConnectionOptions
                    {
                        Authentication = AuthenticationLevel.PacketPrivacy,
                        //the rest of wmi objects will use the local admin so when joining to domain
                        //you must use your domain account
                        Impersonation    = ImpersonationLevel.Impersonate,
                        EnablePrivileges = true,
                        //needs to be local admin account that connects to machine
                        //local admin account
                        Username = local.UserName,
                        //local admin account password
                        SecurePassword = sec,
                    };
                    ManagementScope scope = new ManagementScope("\\\\" + computername + "\\root\\cimv2", conn);
                    scope.Connect();
                    WqlObjectQuery wqlQuery =
                        new WqlObjectQuery("SELECT * FROM Win32_ComputerSystem");
                    ManagementObjectSearcher searcher =
                        new ManagementObjectSearcher(scope, wqlQuery);

                    object[] methodArgs = { textBoxNewName.Text, textBoxDomainPassword.Text, textBoxDomainUserName.Text };

                    foreach (ManagementObject n in searcher.Get())
                    {
                        n.InvokeMethod("Rename", methodArgs);
                        methodArgs = null;
                    }


                    DialogResult result = System.Windows.Forms.MessageBox.Show("Do you want to restart this computer?", "Restart remote computer", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                                                               MessageBoxDefaultButton.Button1,
                                                                               MessageBoxOptions.DefaultDesktopOnly);
                    if (result == DialogResult.Yes)
                    {
                        Process          process = new Process();
                        ProcessStartInfo psi     = new ProcessStartInfo();
                        psi.FileName        = @"C:\Windows\System32\shutdown.exe";
                        psi.UseShellExecute = false;
                        psi.CreateNoWindow  = true;
                        string path = "\\\\" + computername;
                        string hh   = string.Format("\"{0}\"", path);
                        psi.Arguments     = @"/m " + path + " /r /t 0";
                        process.StartInfo = psi;
                        process.Start();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("The computer will not show it is renamed until it is restarted", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Question,
                                                             MessageBoxDefaultButton.Button1,
                                                             MessageBoxOptions.DefaultDesktopOnly);
                        this.Close();
                    }

                    DialogResult moveOu = System.Windows.Forms.MessageBox.Show("Do you want to move this computer to another OU?", "Move remote computer", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                                                               MessageBoxDefaultButton.Button1,
                                                                               MessageBoxOptions.DefaultDesktopOnly);
                    if (moveOu == DialogResult.Yes)
                    {
                        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain))
                        {
                            ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, computername);

                            DirectoryEntry de = (DirectoryEntry)computer.GetUnderlyingObject();
                            de.MoveTo(new DirectoryEntry("LDAP://" + comboBoxOUs.Text));
                            de.CommitChanges();
                        }
                    }
                }
                catch (SystemException err)
                {
                    System.Windows.Forms.MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                         MessageBoxDefaultButton.Button1,
                                                         MessageBoxOptions.DefaultDesktopOnly);
                    this.Close();
                }
            }
            if ((checkIfOnDomain(computername) == false) && (checkLocalCreds(textBoxLocalUserName.Text, textBoxLocalPassword.Text) == true))
            {
                System.Security.SecureString sec   = convertToSecureString(textBoxLocalPassword.Text);
                NetworkCredential            local = new NetworkCredential(computername + "\\" + textBoxLocalUserName.Text, sec);
                try
                {
                    ConnectionOptions conn = new ConnectionOptions
                    {
                        Authentication = AuthenticationLevel.PacketPrivacy,
                        //the rest of wmi objects will use the local admin so when joining to domain
                        //you must use your domain account
                        Impersonation    = ImpersonationLevel.Impersonate,
                        EnablePrivileges = true,
                        //needs to be local admin account that connects to machine
                        //local admin account
                        Username = local.UserName,
                        //local admin account password
                        SecurePassword = sec,
                    };
                    ManagementScope scope = new ManagementScope("\\\\" + computername + "\\root\\cimv2", conn);
                    scope.Connect();
                    WqlObjectQuery wqlQuery =
                        new WqlObjectQuery("SELECT * FROM Win32_ComputerSystem");
                    ManagementObjectSearcher searcher =
                        new ManagementObjectSearcher(scope, wqlQuery);


                    object[] methodArgs = { textBoxNewName.Text };

                    foreach (ManagementObject n in searcher.Get())
                    {
                        n.InvokeMethod("Rename", methodArgs);
                        methodArgs = null;
                    }
                    DialogResult result = System.Windows.Forms.MessageBox.Show("Do you want to restart this computer?", "Restart remote computer", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                                                               MessageBoxDefaultButton.Button1,
                                                                               MessageBoxOptions.DefaultDesktopOnly);
                    if (result == DialogResult.Yes)
                    {
                        WqlObjectQuery wqlQuery0 =
                            new WqlObjectQuery("SELECT * FROM Win32_OperatingSystem");
                        ManagementObjectSearcher searcher0 =
                            new ManagementObjectSearcher(scope, wqlQuery0);
                        object[] methodArgs0 = { };

                        foreach (ManagementObject n in searcher0.Get())
                        {
                            n.InvokeMethod("Reboot", methodArgs0);
                            methodArgs0 = null;
                        }
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("The computer will not be show it is renamed until it is restarted", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Question,
                                                             MessageBoxDefaultButton.Button1,
                                                             MessageBoxOptions.DefaultDesktopOnly);
                        this.Close();
                    }
                }
                catch (SystemException err)
                {
                    System.Windows.Forms.MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                         MessageBoxDefaultButton.Button1,
                                                         MessageBoxOptions.DefaultDesktopOnly);
                    this.Close();
                }
            }
        }
Exemple #6
0
        public Boolean MoveComputerToOU(String MACHINEOBJECTOU, String OSDComputerName)
        {
            Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Starting Web Service");
            Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: MACHINEOBJECTOU received was: " + MACHINEOBJECTOU);
            Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: OSDComputerName received was: " + OSDComputerName);

            String CurrentOU = string.Empty;

            Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Connecting to " + FQDNDomainName + ".");

            try
            {
                // Connect to AD
                PrincipalContext AD = new PrincipalContext(ContextType.Domain, FQDNDomainName);

                string controller = AD.ConnectedServer;
                Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Connected to " + string.Format("Domain Controller: {0}", controller));

                ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(AD, OSDComputerName);

                if (computer != null)
                {
                    Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Machine found in AD, continue.");
                    // Get Parent OU
                    DirectoryEntry deComputer          = computer.GetUnderlyingObject() as DirectoryEntry;
                    DirectoryEntry deComputerContainer = deComputer.Parent;

                    CurrentOU = string.Format("{0}".Trim(), deComputerContainer.Properties["distinguishedName"].Value);

                    Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: CurrentOU is " + CurrentOU);

                    // Verify if the selected OU is the same as the current OU
                    if (String.Equals(MACHINEOBJECTOU, CurrentOU, StringComparison.OrdinalIgnoreCase))
                    {
                        Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Selected OU is the same as current OU, or machine does not exist in AD, do nothing ");
                    }
                    else
                    {
                        Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Selected OU is not the same as currentOU, move computer to selected OU ");

                        // Move the computer object
                        DirectoryEntry NewParent = new DirectoryEntry("LDAP://" + MACHINEOBJECTOU);
                        deComputer.MoveTo(NewParent);
                    }
                }
                else
                {
                    Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Machine not found in AD, assuming new machine, skipping move operation.");
                }
            }


            catch (Exception e)
            {
                Trace.WriteLine(DateTime.Now + ": MoveComputerToOU: Unhandled exception finding provider namespace on server " + e.ToString());
                return(false);
            }


            return(true);
        }