.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);
            }
        }
    }
}

}

目录
相关文章
|
6月前
|
C++ Windows
.NET Framework安装不成功,下载`NET Framework 3.5`文件,Microsoft Visual C++
.NET Framework常见问题及解决方案汇总,涵盖缺失组件、安装失败、错误代码等,提供多种修复方法,包括全能王DLL修复工具、微软官方运行库及命令行安装等,适用于Windows系统,解决应用程序无法运行问题。
936 3
|
10月前
|
监控 关系型数据库 MySQL
zabbix7.0.9安装-以宝塔安装形式-非docker容器安装方法-系统采用AlmaLinux9系统-最佳匹配操作系统提供稳定运行环境-安装教程完整版本-优雅草卓伊凡
zabbix7.0.9安装-以宝塔安装形式-非docker容器安装方法-系统采用AlmaLinux9系统-最佳匹配操作系统提供稳定运行环境-安装教程完整版本-优雅草卓伊凡
780 30
|
11月前
|
监控 Linux
yum install -y net-snmp-devel 安装不成功 zabbix项目安装,Errors during downloading metadata for repository ‘extras-common’:问题解决方案-优雅草卓伊凡
yum install -y net-snmp-devel 安装不成功 zabbix项目安装,Errors during downloading metadata for repository ‘extras-common’:问题解决方案-优雅草卓伊凡
541 13
yum install -y net-snmp-devel 安装不成功 zabbix项目安装,Errors during downloading metadata for repository ‘extras-common’:问题解决方案-优雅草卓伊凡
|
11月前
|
监控 Linux PHP
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
415 20
|
算法 Java 测试技术
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
347 13
|
开发框架 .NET C#
在 ASP.NET Core 中创建 gRPC 客户端和服务器
本文介绍了如何使用 gRPC 框架搭建一个简单的“Hello World”示例。首先创建了一个名为 GrpcDemo 的解决方案,其中包含一个 gRPC 服务端项目 GrpcServer 和一个客户端项目 GrpcClient。服务端通过定义 `greeter.proto` 文件中的服务和消息类型,实现了一个简单的问候服务 `GreeterService`。客户端则通过 gRPC 客户端库连接到服务端并调用其 `SayHello` 方法,展示了 gRPC 在 C# 中的基本使用方法。
308 5
在 ASP.NET Core 中创建 gRPC 客户端和服务器
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
敏捷开发 缓存 中间件
.NET技术的高效开发模式,涵盖面向对象编程、良好架构设计及高效代码编写与管理三大关键要素
本文深入探讨了.NET技术的高效开发模式,涵盖面向对象编程、良好架构设计及高效代码编写与管理三大关键要素,并通过企业级应用和Web应用开发的实践案例,展示了如何在实际项目中应用这些模式,旨在为开发者提供有益的参考和指导。
146 3
|
存储 消息中间件 NoSQL
Redis 入门 - C#.NET Core客户端库六种选择
Redis 入门 - C#.NET Core客户端库六种选择
716 8
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
Android远程连接和登录FTPS服务代码(commons.net库)
347 1

热门文章

最新文章

推荐镜像

更多