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

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

}

上一篇:一探究竟:善用 MaxCompute Studio 分析 SQL 作业


下一篇:linux基础命令介绍五:文本过滤 grep