我有一个python脚本,它分割Icinga GUI命令并将特定的命令发送给卫星主机。
脚本完成了它所写的内容,但我遇到了两个问题:
第一:我在第16行之后没有得到调试输出(" cgi_cmd = open(cgi_cmd_file,' r')")
第二:脚本使用高达100%的CPU,即使它每次获取空行时都应暂停5秒钟。
我可以在这里使用一些帮助,谢谢!
我的第一个问题与命名管道的工作方式有关。如果首先打开它,它只能打开阅读。
第二个问题是我检查循环内线的方式,感谢Peter Wood。
#!/usr/bin/python
import string, os, sys, re, spur, logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Imports done.')
# Define files and open
cgi_cmd_file = '/var/spool/icinga/cmd/cgi.cmd'
icinga_cmd_file = '/var/spool/icinga/cmd/icinga.cmd'
icinga_log_file = '/var/log/icinga/iscrdr_collector.log'
sat_log_file = '/var/log/icinga/iscrdr_satelite.log'
logging.debug('Files defined.')
cgi_cmd = open(cgi_cmd_file, 'r')
icinga_cmd = open(icinga_cmd_file, 'w')
logging.debug('Files opened.')
# Compile regex pattern for reschedule service and host checks
pattern = re.compile('SCHEDULE_.*_.*_CHECK.+?\d{10}')
logging.debug('Regex pattern compiled.')
# List of satelite hosts
satelite_hosts = [
['hostname','user','pw'],
['hostname','user','pw'],
['hostname','user','pw'],
]
logging.debug('Satelite hosts defined.')
#
# Code Area
#
def send_to_sat(message):
command = "/bin/echo '" + string.strip(message) + "' > /var/spool/icinga/cmd/icinga.cmd"
for i in satelite_hosts:
shell = spur.SshShell(hostname=i[0], username=i[1], password=i[2])
with shell:
result = shell.run(["sh", "-c", command])
logging.debug('Command send to' + i[0] + '.')
with open(sat_log_file, 'a') as sat_log:
sat_log.write(string.strip(message + str(result.return_code)) + "\n")
def send_to_icinga(message):
with open(icinga_cmd_file, 'w') as icinga_cmd:
icinga_cmd.write(string.strip(message) + "\n")
with open(icinga_log_file, 'a') as icinga_log:
icinga_log.write(string.strip(message) + "\n")
logging.debug('Command send to Icinga.')
# Split reschedule commands from command stream and write them to file
while True:
logging.debug('This is a loop run.')
line = cgi_cmd.readline()
if re.findall(r'SCHEDULE_.*_.*_CHECK.+?\d{10}', line):
send_to_sat(line)
elif line != '':
send_to_icinga(line)
else:
logging.debug('No Command.')
time.sleep(5)
continue