.NET自动安装zabbix客户端(代码)

简介: using System;using System.Collections.Generic;using System.Text;using System.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Management;
using System.ServiceProcess;

namespace Zabbix3AgentSetup
{
class Program
{
static void Main(string[] args)
{
// string test=File.ReadAllText("../../serverip.txt");
// Console.WriteLine(test);
// Console.Read();
killProcess("zabbix_agentd");
if(ServiceIsExisted("Zabbix Agent")){
if (GetOSBit() != 32)
{
RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win64\zabbix_agentd.exe -d -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
}
else
{
RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win32\zabbix_agentd.exe -d -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
}
}
if(Directory.Exists(@"c:\zabbix_agents_2.4.4.win"))
{
Directory.Delete(@"c:\zabbix_agents_2.4.4.win", true);
}
Directory.CreateDirectory(@"c:\zabbix_agents_2.4.4.win");
CopyFile(@"....\zabbix_agents_2.4.4.win", @"c:\zabbix_agents_2.4.4.win");
string machineName = Environment.MachineName;
string serverip = File.ReadAllText(@"....\serverip.txt");
string str1 = ("ServerActive=" + serverip);
string str2 = ("Hostname=" + machineName);
using (FileStream fs = new FileStream(@"c:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("{0}\n", str1, DateTime.Now);
sw.WriteLine("{0}\n", str2, DateTime.Now);
sw.Flush();
}
}

            if (GetOSBit() != 32)
            {
                RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win64\zabbix_agentd.exe -i -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
                RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win64\zabbix_agentd.exe -s -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
            }
            else {
                RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win32\zabbix_agentd.exe -i -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
                RunCmd(@"C:\zabbix_agents_2.4.4.win\bin\win32\zabbix_agentd.exe -s -c C:\zabbix_agents_2.4.4.win\conf\zabbix_agentd.win.conf");
            }
        StartService("Zabbix Agent");
        Console.WriteLine("done");
        }

    static bool ServiceIsExisted(string serviceName)
    {
        ServiceController[] services = ServiceController.GetServices();
        foreach (ServiceController s in services)
        {
            if (s.ServiceName == serviceName)
            {
                return true;
            }
        }
        return false;
    }
    static void killProcess(string name)
    {
        Process[] pro = Process.GetProcesses();//获取已开启的所有进程

        //遍历所有查找到的进程

        for (int i = 0; i < pro.Length; i++)
        {

            //判断此进程是否是要查找的进程
            if (pro[i].ProcessName.ToString().ToLower() == name)
            {
                pro[i].Kill();//结束进程
            }
        }
    }
    public static void StartService(string serviceName)
    {
        try
        {
            using (System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName))
            {
                TimeSpan timeout = new TimeSpan(0, 0, 15);
             
                    if (sc.Status != ServiceControllerStatus.Running)
                    {
                        sc.Start();
                        sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
                    }
                }
        }
        catch (Exception e)
        {
           
        }
    }
    /// <summary> 
    /// 获取操作系统位数(x32/64) 
    /// </summary> 
    /// <returns>int</returns> 
    public static int GetOSBit()
    {
        try
        {
            string addressWidth = String.Empty;
            ConnectionOptions mConnOption = new ConnectionOptions();
            ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption);
            ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery);
            ManagementObjectCollection mObjectCollection = mSearcher.Get();
            foreach (ManagementObject mObject in mObjectCollection)
            {
                addressWidth = mObject["AddressWidth"].ToString();
            }
            return Int32.Parse(addressWidth);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            return 32;
        }
    }
    static void RunCmd(string cmdStr)
    {

        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
        p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
        p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
        p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
        p.StartInfo.CreateNoWindow = true;//不显示程序窗口
        p.Start();//启动程序

        //向cmd窗口发送输入信息
        p.StandardInput.WriteLine(cmdStr);
        p.StandardInput.WriteLine("exit");
        p.StandardInput.AutoFlush = true;
        //p.StandardInput.WriteLine("exit");
        //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
        //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令



        //获取cmd窗口的输出信息
      //string output = p.StandardOutput.ReadToEnd();

        //StreamReader reader = p.StandardOutput;
        //string line=reader.ReadLine();
        //while (!reader.EndOfStream)
        //{
        //    str += line + "  ";
        //    line = reader.ReadLine();
        //}

        p.WaitForExit();//等待程序执行完退出进程
        p.Close();


       // Console.WriteLine(output);
    }
    /// <summary>
    /// 复制文件
    /// </summary>
    /// <param name="sources">源路径</param>
    /// <param name="dest">新路径</param>
    static void CopyFile(string sources, string dest)
    {
        DirectoryInfo dinfo = new DirectoryInfo(sources);
        //注,这里面传的是路径,并不是文件,所以不能保含带后缀的文件                
        foreach (FileSystemInfo f in dinfo.GetFileSystemInfos())
        {
            //目标路径destName = 目标文件夹路径 + 原文件夹下的子文件(或文件夹)名字                
            //Path.Combine(string a ,string b) 为合并两个字符串                     
            String destName = Path.Combine(dest, f.Name);
            if (f is FileInfo)
            {
                //如果是文件就复制       
                File.Copy(f.FullName, destName, true);//true代表可以覆盖同名文件                     
            }
            else
            {
                //如果是文件夹就创建文件夹然后复制然后递归复制              
                Directory.CreateDirectory(destName);
                CopyFile(f.FullName, destName);
            }
        }
    }
}

}

目录
相关文章
|
2月前
|
监控 关系型数据库 Linux
|
24天前
|
域名解析 缓存 监控
安装zabbix时报错Could not resolve host: mirrors.huaweicloud.com;Unknown error解决办法
安装zabbix时报错Could not resolve host: mirrors.huaweicloud.com;Unknown error解决办法
|
24天前
|
监控 关系型数据库 应用服务中间件
Linux zabbix监控 软件的安装
Linux zabbix监控 软件的安装
|
1月前
|
XML 开发框架 .NET
【.NET Core】常见C#代码约定
【.NET Core】常见C#代码约定
25 5
|
29天前
|
安全 程序员 Shell
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8
|
1月前
|
NoSQL 大数据 Redis
分享5款.NET开源免费的Redis客户端组件库
分享5款.NET开源免费的Redis客户端组件库
|
2月前
|
JSON 编解码 Go
Golang深入浅出之-HTTP客户端编程:使用net/http包发起请求
【4月更文挑战第25天】Go语言`net/http`包提供HTTP客户端和服务器功能,简化高性能网络应用开发。本文探讨如何发起HTTP请求,常见问题及解决策略。示例展示GET和POST请求的实现。注意响应体关闭、错误处理、内容类型设置、超时管理和并发控制。最佳实践包括重用`http.Client`,使用`context.Context`,处理JSON以及记录错误日志。通过实践这些技巧,提升HTTP编程技能。
44 1
|
2月前
|
Go 开发者
Golang深入浅出之-HTTP客户端编程:使用net/http包发起请求
【4月更文挑战第24天】Go语言的`net/http`包在HTTP客户端编程中扮演重要角色,但使用时需注意几个常见问题:1) 检查HTTP状态码以确保请求成功;2) 记得关闭响应体以防止资源泄漏;3) 设置超时限制,避免长时间等待;4) 根据需求处理重定向。理解这些细节能提升HTTP客户端编程的效率和质量。
36 1
|
2月前
|
监控 关系型数据库 MySQL
红帽 9 zabbix 安装流程
Zabbix是一个监控软件,用于确保企业服务架构的安全运行,具备灵活的告警机制和分布式监控能力。它由Server、Web页面、数据库、Proxy和Agent五个组件组成。工作流程中,Agent在目标设备上收集数据,Server存储和处理数据,Web页面提供监控信息。Zabbix支持主动和被动两种数据收集模式。在Redhat 9.2环境下,安装包括关闭防火墙、设置SELinux、安装MySQL、创建Zabbix数据库和用户、安装Zabbix RPM包及配置服务。完成安装后,通过Web界面使用Admin账号和预设密码zabbix登录。
50 2
|
2月前
|
开发框架 缓存 前端开发
安装ASP.NET AJAX (一安装)
安装ASP.NET AJAX (一安装)
41 0

推荐镜像

更多