我有一个来自Nagios的配置文件,我正在成功地解析它来提取所有的host_names。然后,我可以使用这些信息与我们的服务器列表进行比较,看看是否有什么是我没有监控的。有其他方法可以做到这一点,但它给了我一个借口,在我的Powershell和Regex上工作。我的配置中的相关示例是:
定义主机{使用windows-server;从模板host_name server1继承默认值;我们给主机别名server1的名称;与主机地址10.10.10.19关联的更长的名称;主机}的IP地址定义主机{使用windows-服务器;从模板host_name server2继承默认值;我们给这个主机别名server2的名称;与主机地址10.10.13.62相关联的更长的名称;主机}的IP地址定义主机{使用windows-server;从模板host_name server3继承默认值;我们要给该主机别名server3的名称;与主机地址10.10.10.21相关联的较长名称;主机}定义服务的IP地址{使用通用服务hostgroup_name windows-server service_description CPU使用check_command check_nrpe!alias_cpu }定义服务{使用通用服务host_name server1 service_description内存check_command check_nrpe!alias_mem }
我有下面的powershell片段和regex查询
$text = [IO.File]::ReadAllText("windows.cfg")
$text | Select-String '(?smi)(?<=host\{).*?(?=\})' -AllMatches |
Foreach {$_.Matches} |
ForEach-Object {$_.Value} |
Select-String '(?smi)(?<=host_name\s+)\w+' -AllMatches |
Foreach {$_.Matches} |
ForEach-Object {$_.Value}我匹配主机{和}之间的内容,这确保我不会从服务和主机组定义中获得额外的主机。对于每一次匹配,我都要查找在静态主机名和一些空格之后存在的整个单词。
它确实有效,我只想知道是否有一种更有效的或替代的regex方法。我试着把它全部变成一个查询,但是我可以让它工作,所以我将它嵌套在代码中。我也要明白
发布于 2014-07-11 14:17:59
我会这样做:
$text | Select-String 'host{[\s\S]*?}' -AllMatches | % {
$_.Matches.Groups.Value
} | Select-String 'host_name\s*(\S+)' | % {
$_.Matches.Groups[1].Value
}可能有一种方法可以使用单个正则表达式(不确定)来实现这一点,但上面的内容可能更容易理解和维护。
发布于 2014-07-11 13:54:19
我通常会这样处理这样的问题:
(@'
define host{
use windows-server ; Inherit default values from a template
host_name server1 ; The name we're giving to this host
alias server1 ; A longer name associated with the host
address 10.10.10.19 ; IP address of the host
}
define host{
use windows-server ; Inherit default values from a template
host_name server2 ; The name we're giving to this host
alias server2 ; A longer name associated with the host
address 10.10.13.62 ; IP address of the host
}
define host{
use windows-server ; Inherit default values from a template
host_name server3 ; The name we're giving to this host
alias server3 ; A longer name associated with the host
address 10.10.10.21 ; IP address of the host
}
define service{
use generic-service
hostgroup_name windows-servers
service_description CPU Usage
check_command check_nrpe!alias_cpu
}
define service{
use generic-service
host_name server1
service_description Memory
check_command check_nrpe!alias_mem
}
'@).split("`n") |
foreach {$_.trim()} | set-content windows.cfg
get-content windows.cfg -ReadCount 1000 |
foreach {$_ -match '^\s*host_name' -replace '^\s*host_name\s+(\S+).+','$1'}
server1
server2
server3
server1在-ReadCount中使用Get-Content使您可以在可控块中处理文件数据,因此,如果您向它抛出一个大文件,就不会出现内存问题。由于它将字符串数组传递到管道中,所以-match和-replace作为数组操作符工作,同时执行整个数组,-match过滤掉host_name记录,然后-replace从字符串中提取值。
https://stackoverflow.com/questions/24698384
复制相似问题