Ejemplo n.º 1
0
        private void Button_Connect_Click(object sender, EventArgs e)
        {
            bool valid = false;
            Label_ConnectionStatus.Text = "Status: Connecting...";
            Panel_ConnectedState.BackColor = Color.PaleGoldenrod;
            Label_ConnectedState.Text = "Status: Conneting...";
            Application.DoEvents();
            try
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Textbox_Domain.Text))
                {
                    // Validate credentials before proceeding
                    valid = context.ValidateCredentials(Textbox_UserName.Text, Textbox_Password.Text);
                    if (valid)
                    {
                        Label_ConnectionStatus.Text = "Status: Connected to " + Textbox_Domain.Text;
                        //Show detected LDAP root connection path:
                        try
                        {
                            // TODO: Convert password to securepassword
                            // Detect root domain naming context
                            DirectoryEntry RootDSE = new DirectoryEntry(@"LDAP://" + Textbox_Domain.Text + @"/RootDSE");
                            RootDSE.Username = Textbox_UserName.Text;
                            RootDSE.Password = Textbox_Password.Text;
                            Label_Detect.Text = @"LDAP://" + RootDSE.Properties["defaultNamingContext"].Value.ToString();
                            LDAPBaseSearchPathBox.Text = Label_Detect.Text;

                            connection = new RemoteConnect(Textbox_Domain.Text, Textbox_UserName.Text, Textbox_Password.Text);
                            connected = true;

                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            Label_Detect.Text = "Domain Not Detected";
                            LDAPBaseSearchPathBox.Text = Label_Detect.Text;
                            connected = false;
                        }

                    }
                    else
                    {
                        Label_ConnectionStatus.Text = "Status: Incorrect username and/or password";
                        connected = false;
                    }
                }
            }
            catch (System.DirectoryServices.AccountManagement.PrincipalServerDownException err)
            {

                Console.WriteLine("Error: {0}", err);
                Label_ConnectionStatus.Text = "Status: The domain could not be contacted, please check your domain name. (Try using the FQDN, example: contoso.com)";

                //An unhandled exception of type 'System.DirectoryServices.AccountManagement.PrincipalServerDownException' occurred in System.DirectoryServices.AccountManagement.dll  
                //Additional information: The server could not be contacted.
                connected = false;
            }
            catch (System.DirectoryServices.Protocols.LdapException err)
            {
                Console.WriteLine("Error: {0}", err);
                Label_ConnectionStatus.Text = "The connection cannot be established. Note: This can happen if this executable is running from a network drive or blocked by antivirus/firewall.";
                connected = false;
            }

            if (connected)
            {
                Panel_ConnectedState.BackColor = Color.LightGreen;
                Label_ConnectedState.Text = "  Status: Connected";
                //Button_Refresh_Click(sender, e); Do i really wan't to wait for a refresh after connecting? The refresh button is always there.

            }
            else
            {
                Panel_ConnectedState.BackColor = Color.IndianRed;
                Label_ConnectedState.Text = "Status: Disconnected";
            }
                
        }
Ejemplo n.º 2
0
        public void GetZabbixServiceInfo(RemoteConnect connection, bool refreshStatusOfLastAction)
        {
            // Create background worker to send WMI queries to another thread.
            bool finished = false;
            UpdateProgress(finished);
            bw = new BackgroundWorker();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;

            // this allows us to cancel the thread and prevent an exception occuring
            // for events such as in when we need to quit the program
            bw.WorkerSupportsCancellation = true;

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
            {
                try
                {
                    ObjectQuery query;
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher();
                    int numberOfQueries = 3;

                    for (int i = 1; i <= numberOfQueries; i++)
                    {
                        if (bw.CancellationPending)
                        {
                            args.Cancel = true;
                            break;
                        }

                        if (refreshStatusOfLastAction == true)
                        {
                            this.statusOfLastAction = "";
                        }

                        switch (i)
                        {
                            case 1:
                                query = new ObjectQuery("Select * from Win32_OperatingSystem");
                                osArch = "Checking...";
                                bw.ReportProgress(i);
                                break;
                            case 2:
                                query = new ObjectQuery("SELECT * FROM Win32_Service Where Name = 'Zabbix Agent'");
                                zabbixServiceState = "Checking...";
                                bw.ReportProgress(i);
                                break;
                            case 3:
                                query = new ObjectQuery("SELECT * FROM CIM_DataFile WHERE name='" + zabbixAgentPath + "'");
                                zabbixAgentVersion = "Checking...";
                                bw.ReportProgress(i);
                                break;
                            default:
                                query = new ObjectQuery("");
                                break;
                        }

                        //Connect to server WMI scope and authenticate
                        connection.SetWMIScopeCIMv2(this);
                        connection.wmiScope.Connect();

                        switch (i)
                        {
                            case 1:
                                searcher = new ManagementObjectSearcher(connection.wmiScope, query);
                                WMIOperatingSystemSearcher(searcher);
                                if (osArch == "Checking...")
                                    osArch = "Not Detected";
                                break;
                            case 2:
                                searcher = new ManagementObjectSearcher(connection.wmiScope, query);
                                WMIServiceSearcher(searcher);
                                if (zabbixServiceState == "Checking...")
                                    zabbixServiceState = "Not Detected";
                                break;
                            case 3:
                                searcher = new ManagementObjectSearcher(connection.wmiScope, query);
                                WMIDataFileSearcher(searcher, connection);
                                if (zabbixAgentVersion == "Checking...")
                                    zabbixAgentVersion = "Not Detected";
                                break;
                            default:
                                break;
                        }

                        // Update the Form to display current values
                        bw.ReportProgress(i);                    
                        searcher.Dispose();
                    }
                }
                catch (ManagementException err)
                {
                    //MessageBox.Show("An error occured while querying for WMI data: " + err.Message);
                    statusOfLastAction = "An error occured while querying for WMI data: " + err.Message;
                    Console.WriteLine(err.ToString());
                    osArch = "Connection failed";
                }
                catch (System.UnauthorizedAccessException unauthorizedErr)
                {
                    // MessageBox.Show("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
                    statusOfLastAction = "WMI connection error - " + "access denied (incorrect credentials or insufficient privileges), error details: " + unauthorizedErr.Message;
                    Console.WriteLine(unauthorizedErr.ToString());
                    osArch = "Connection failed";
                }
                catch (System.Runtime.InteropServices.COMException COMExcepErr)
                {
                    // MessageBox.Show("Connection error " + "(The RPC server service may not be available), error details:" + COMExcepErr.Message);
                    statusOfLastAction = "WMI connection error " + "(The RPC server service may not be available), error details:" + COMExcepErr.Message;
                    Console.WriteLine(COMExcepErr.ToString());
                    osArch = "Connection failed";
                }


                if (statusOfLastAction == "")
                    statusOfLastAction = "Ok";

            });

            // what to do when worker completes its task (notify the user)
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
            delegate(object o, RunWorkerCompletedEventArgs args)
            {
                finished = true;
                UpdateProgress(finished);
            });

            // what to do when progress changed (update the progress bar for example)
            bw.ProgressChanged += new ProgressChangedEventHandler(
            delegate(object o, ProgressChangedEventArgs args)
            {
                UpdateProgress(finished);
            });
    
            
            bw.RunWorkerAsync();

            while (!(finished) && (!(bw.CancellationPending)))
            {
                // TODO: This is a terrible way to process threads, need to find a proper solution.
                Application.DoEvents();
                // Using thread.sleep here for 50ms will at least prevent the CPU from being wasted by this loop.
                Thread.Sleep(50 /* millisec */);
            }
        }
Ejemplo n.º 3
0
         private void WMIDataFileSearcher(ManagementObjectSearcher searcher, RemoteConnect connection)
        {
            try
            {
                foreach (ManagementObject queryObj in searcher.Get())
                {

                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("CIM_DataFile instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("File Caption: " +
                    Convert.ToString(queryObj["Caption"]));
                    Console.WriteLine("File Version: " +
                    Convert.ToString(queryObj["version"]));
                    Console.WriteLine("Archive: " + Convert.ToString(queryObj["Archive"]));
                    Console.WriteLine("Compressed: " +
                    Convert.ToString(queryObj["Compressed"]));
                    Console.WriteLine("File Name: " +
                    Convert.ToString(queryObj["FileName"]));
                    Console.WriteLine("File Extension: " +
                    Convert.ToString(queryObj["Extension"]));
                    Console.WriteLine("File Size: " +
                    Convert.ToString(queryObj["FileSize"]));
                    Console.WriteLine("File Type: " +
                    Convert.ToString(queryObj["FileType"]));
                    Console.WriteLine("Last Modified: " +
                    Convert.ToString(queryObj["LastModified"]));
                    Console.WriteLine("File Size: " +
                    Convert.ToString(queryObj["FileSize"]));
                    Console.WriteLine("Name: " + Convert.ToString(queryObj["Name"]));
                    Console.WriteLine("Path: " + Convert.ToString(queryObj["Path"]));
                    Console.WriteLine("Name: " + Convert.ToString(queryObj["Name"]));
                    Console.WriteLine("System: " + Convert.ToString(queryObj["System"]));
                    Console.WriteLine("Manufaturer: " +
                    Convert.ToString(queryObj["Manufacturer"]));

                    zabbixAgentVersion = Convert.ToString(queryObj["version"]);

                    // Try getting file version by running --service paramater on agent executable
                    if (zabbixAgentVersion == "")
                    {
                        try
                        {
                            //Assemble command string
                            string uncZabbixAgentPath = zabbixAgentPath.Replace(@":", @"$");
                            uncZabbixAgentPath = @"\\" + this.computerName + @"\\" + uncZabbixAgentPath;
                            string strCmd = "\"" + uncZabbixAgentPath + "\""; 
                            string strArgs =  "--version";
                            Console.WriteLine("Running command to get Zabbix Agent Version: " + strCmd + " " + strArgs);   
                            Log.WriteLog("Running command to get Zabbix Agent Version: " + strCmd + " " + strArgs);   

     
                            //Set and start process object for command
                            //Note: a command window will pop open and close, this is impossible to prevent when using any of the following properties:
                            //StartInfo.UserName != null (has been set in RemoteConnect)
                            //StartInfo.Password != null (has been set in RemoteConnect)
                            //StartInfo.UseShellExecute = true;
                            connection.pProcess.StartInfo.FileName = strCmd;
                            connection.pProcess.StartInfo.Arguments = strArgs;
                            connection.pProcess.StartInfo.UseShellExecute = false;
                            connection.pProcess.StartInfo.RedirectStandardOutput = true;
                            connection.pProcess.StartInfo.RedirectStandardError = true;
                            connection.pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            connection.pProcess.StartInfo.CreateNoWindow = true;
                            connection.pProcess.Start();
                            string strOutput = connection.pProcess.StandardOutput.ReadToEnd();
                            connection.pProcess.WaitForExit();
                            Console.WriteLine("strOutput" + strOutput);

                            //Set zabbixAgentVersion to substring of output
                            string[] substrings = strOutput.Split(')');
                            zabbixAgentVersion = substrings[1].TrimStart() + ')';
                            Console.WriteLine("Setting Zabbix Agent Version To: " + zabbixAgentVersion);

                            if (zabbixAgentVersion != "")
                                Log.WriteLog("INFO: Unable to get zabbix version info from file properties (agent version < v2.0), trying to determine using --version parameter on agent. (Note: You will see a command window quickly pop open and close again)");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            Log.WriteLog("INFO: Could not get zabbix version from service zabbix_agentd.exe --version paramater. Note: zabbix_agentd.exe --version is invoked from local computer, therefore this function will only work if account specified under setup tab also has permission to the local computer." + "\r\nOriginating error message: " + ex.Message);
                        }
                    }
                }

            }
            catch (ManagementException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

        }
Ejemplo n.º 4
0
        public void DeployZabbixService(RemoteConnect connection, String agentFileName)
        {
            try
            {
                bool finished = false;
                UpdateProgress(finished);
                connection.SetWMIScopeCIMv2(this);
                string strCmd;

                bw = new BackgroundWorker();

                // this allows our worker to report progress during work
                bw.WorkerReportsProgress = true;

                // this allows us to cancel the thread and prevent an exception occuring
                // for events such as in when we need to quit the program
                bw.WorkerSupportsCancellation = true;

                // what to do in the background thread
                bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
                {
                    if (bw.CancellationPending)
                    {
                        args.Cancel = true;
                    }

                    //Install Zabbix Service
                    strCmd = "\"" + GlobalVariables.defaultDeployPath + agentFileName + "\" --config \"" +
                        GlobalVariables.defaultDeployPath + GlobalVariables.defaultConfigFileName + "\" --install";
                    runCommand(strCmd.Replace(@"\\", @"\"), connection.wmiScope);

                    //Start Zabbix Service
                    strCmd = "\"" + GlobalVariables.defaultDeployPath + agentFileName + "\" --config \"" +
                        GlobalVariables.defaultDeployPath + GlobalVariables.defaultConfigFileName + "\" --start";
                    runCommand(strCmd.Replace(@"\\", @"\"), connection.wmiScope);
                    
                });


                // what to do when worker completes its task (notify the user)
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                delegate(object o, RunWorkerCompletedEventArgs args)
                {
                    finished = true;
                    //UpdateProgress(finished);
                });

                bw.RunWorkerAsync();


                while (!(finished) && (!(bw.CancellationPending)))
                {
                    // TODO: This is a terrible way to process threads, need to find a proper solution.
                    Application.DoEvents();
                    // Using thread.sleep here for 50ms will at least prevent the CPU from being wasted by this loop.
                    Thread.Sleep(50 /* millisec */);
                }

                //Copy files NOTE: This method does work to copy remote files, but ended up instead preferring the use of NetworkShareAccesserClass. The following method requies the use of xcopy to pull files from client to server, and thus requiring additional credential validation on the client computer.
                /*
                strCmd = "cmd /C net use \"\\\\computername.contoso.com\\c$\" /user:domain\\username password /yes && xcopy /Y \"\\\\computername.contoso.com\\c$\\testfile.txt\" \"" + GlobalVariables.defaultDeployPath + "\" && net use \"\\\\computername.contoso.com\\c$\" /delete /yes";
                inParams["CommandLine"] = strCmd;
                Console.WriteLine("Deploy cmd: {0}", strCmd);
                outParams = wmiProcess.InvokeMethod("Create", inParams, null);
                Console.WriteLine(outParams["returnvalue"]);
                Console.WriteLine(outParams["processid"]);
                 * */


            }
            catch (System.UnauthorizedAccessException unauthErr)
            {
                //DONE: Update the status of last action instead
                //MessageBox.Show("Insufficient permissions for computer: " + this.computerName + " Please try another credential. \n\nOriginating error message: " + unauthErr.Message);
                statusOfLastAction = "Insufficient permissions for computer: " + this.computerName + " Please try another credential. Originating error message: " + unauthErr.Message;
                Console.WriteLine(unauthErr);
            }
        }
Ejemplo n.º 5
0
        public void UninstallZabbixService(RemoteConnect connection)
        {
            try
            {
                bool finished = false;
                UpdateProgress(finished);
                connection.SetWMIScopeCIMv2(this);
                string strCmd;
                

                bw = new BackgroundWorker();

                // this allows our worker to report progress during work
                bw.WorkerReportsProgress = true;

                // this allows us to cancel the thread and prevent an exception occuring
                // for events such as in when we need to quit the program
                bw.WorkerSupportsCancellation = true;

                // what to do in the background thread
                bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
                {
                    if (bw.CancellationPending)
                    {
                        args.Cancel = true;
                    }

                    //Configure paths if not dected by service
                    if (zabbixAgentPath == "")
                    {
                        zabbixAgentPath = GlobalVariables.defaultDeployPath + GlobalVariables.defautl32BitAgentFileName;
                        zabbixAgentPath = zabbixAgentPath.Replace(@"\", @"\\");
                    }
                    if (zabbixConfigPath == "")
                    {
                        zabbixConfigPath = GlobalVariables.defaultDeployPath + GlobalVariables.defaultConfigFileName;
                        zabbixConfigPath = zabbixConfigPath.Replace(@"\", @"\\");
                    }


                    //Stop Zabbix Service
                    strCmd = "\"" + zabbixAgentPath + "\" --config \"" + zabbixConfigPath + "\" --stop";
                    runCommand(strCmd.Replace(@"\\", @"\"), connection.wmiScope);

                    //Uninstall Zabbix Service
                    strCmd = "\"" + zabbixAgentPath + "\" --config \"" + zabbixConfigPath + "\" --uninstall";
                    runCommand(strCmd.Replace(@"\\", @"\"), connection.wmiScope);                  

                });

                // what to do when worker completes its task (notify the user)
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
                delegate(object o, RunWorkerCompletedEventArgs args)
                {
                    finished = true;
                    //UpdateProgress(finished);
                });


                bw.RunWorkerAsync();


                while (!(finished) && (!(bw.CancellationPending)))
                {
                    // TODO: This is a terrible way to process threads, need to find a proper solution.
                    Application.DoEvents();
                    // Using thread.sleep here for 50ms will at least prevent the CPU from being wasted by this loop.
                    Thread.Sleep(50 /* millisec */);
                }

                
            }
            catch (System.UnauthorizedAccessException unauthErr)
            {
                //DONE: Update the status of last action instead
                //MessageBox.Show("Insufficient permissions for computer: " + this.computerName + " Please try another credential. \n\nOriginating error message: " + unauthErr.Message);
                statusOfLastAction = "Insufficient permissions for computer: " + this.computerName + " Please try another credential. Originating error message: " + unauthErr.Message;
            }


        }
Ejemplo n.º 6
0
        public void StartProgram(string nameOfProcess, RemoteConnect connection)
        {
            connection.SetWMIScopeCIMv2(this);
            connection.wmiScope.Connect();

            string[] processToRun = new[] { nameOfProcess };
            ManagementClass wmiProcess = new ManagementClass(connection.wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
            wmiProcess.InvokeMethod("Create", processToRun);

        }