使用zabbix监控位于局域网中的主机,由于被监控主机没有公网ip,所以使用主动式zabbix_agentd进行监控。
主动式监控(zabbix_agentd主动向zabbix_server发送数据)配置文件
#### 日志文件位置
LogFile=c:\zabbix_agentd\zabbix_agentd.log
#### 禁用被动模式
StartAgents=0
#### 主动上传数据ip地址
ServerActive=210.73.27.13
#### 主机名(对应zabbix_server中的配置)
Hostname=zhezhao
#### 每隔1分钟,向zabbix_server确认一次需要收集的数据
RefreshActiveChecks=60
现在有个需求,就是zabbix_server的域名(或者ip地址)在将来有可能会发生变化,要求可以通过web页面修改zabbix_agent配置文件中的ServerActive参数,并重启服务。
我们先读取zabbix_agentd.conf配置文件,通过正则表达式替换ServerActive参数。
我们可以通过添加.net framework库中的System.ServiceProcess
引用,来停止和开启zabbix_agentd服务。
替换完成配置文件中的ServerActive参数之后,重启zabbix_agentd服务,新的配置文件就会生效。
using System.ServiceProcess;
using System.Text.RegularExpressions;
using System.Web.Mvc;
namespace zabbix.Controllers
{
public class IndexController : Controller
{
private ServiceController service;
public IndexController()
{
this.service = new ServiceController("Zabbix Agent");
}
// GET: Index
public ActionResult Index()
{
//读取zabbi_agent服务状态
string state = this.service.Status.ToString();
ViewBag.state = state;
return View();
}
public string Status()
{
string state = this.service.Status.ToString();
return state;
}
public string Stop()
{
this.service.Stop();
this.service.WaitForStatus(ServiceControllerStatus.Stopped);
return "操作成功";
}
public string Start()
{
this.service.Start();
//等待服务到达运行状态
this.service.WaitForStatus(ServiceControllerStatus.Running);
return "操作成功";
}
public string ReStart()
{
this.Stop();
this.Start();
return "操作成功";
}
private string ReConfig()
{
string newIp;
//检查ip参数
if (Request["ip"].Trim() == "") {
return "ip参数不正确";
}
newIp = Request["ip"].Trim();
newIp = newIp+"\n";
string config = System.IO.File.ReadAllText(@"C:\zabbix_agentd\conf\zabbix_agentd.conf");
Regex r = new Regex("ServerActive=(.*)\n");
if (r.IsMatch(config))
{
MatchCollection mc = r.Matches(config);
string val = mc[0].Value;
string[] arr = val.Split('=');
string oldIp = arr[1];
string newConfig = config.Replace(oldIp, newIp);
System.IO.File.WriteAllText(@"C:\zabbix_agentd\conf\zabbix_agentd.conf.backup",config);
System.IO.File.WriteAllText(@"C:\zabbix_agentd\conf\zabbix_agentd.conf", newConfig);
//检查服务是否在运行
if (this.Status() != "Running")
{
this.Start();
}else
{
this.ReStart();
}
return "操作成功";
}
else
{
return "配置文件写入失败";
}
}
}
}
使用说明
直接在vs中调试程序会报错,因为默认用户的权限是不能重启zabbix服务的。
我们需要发布到IIS服务器,然后为它创建一个应用池,该应用池的“标识”设置为一个有权限的用户即可。
地址 | 说明 |
---|---|
IndexController/Status | 查询Zabbix Agent服务运行状态 |
IndexController/Stop | 停止Zabbix Agent服务 |
IndexController/Start | 开启Zabbix Agent服务 |
IndexController/Restart | 重启Zabbix Agent服务 |
IndexController/ReConfig | 接收ip参数,修改zabbix配置文件,并重启服务 |