Skip to content

Instantly share code, notes, and snippets.

@hedgeven
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hedgeven/ed7c271b230a14f66f01 to your computer and use it in GitHub Desktop.
Save hedgeven/ed7c271b230a14f66f01 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
import re
import os
import sys
import time
import syslog
from socket import socket
WORK_DIR = '/var/cache/zabbix/mka2/'
DEFAULT_PORT = 1000
GET_PORT_TIMEOUT = 3
GET_T_TIMEOUT = 1
def main(argv):
if len(argv)>1:
host = argv[1]
try:
port = int(argv[2])
except:
port = DEFAULT_PORT
else:
print("Usage: %s HOST [PORT]" % argv[0])
sys.exit(1)
try:
if not os.path.exists(WORK_DIR):
os.mkdir(WORK_DIR)
os.chdir(WORK_DIR)
except:
print("No access to %s" % WORK_DIR)
syslog.syslog(syslog.LOG_ERR, "No access to %s" % WORK_DIR)
sys.exit(1)
work_file = WORK_DIR + host
if not os.path.exists(work_file):
try:
open(work_file, 'a').close()
except:
print("No access to %s" % work_file)
syslog.syslog(syslog.LOG_ERR, "No access to %s" % work_file)
sys.exit(1)
cache_update(host, port)
def cache_update(host, port):
result = {}
try:
for line in open(host, 'r').readlines():
kv = line.split(':')
if len(kv) == 2:
result[kv[0]] = kv[1]
except:
pass
try:
s = socket()
s.settimeout(2)
s.connect((host, port))
s.recv(256)
s.send('get_port\r\n')
time.sleep(GET_PORT_TIMEOUT)
data = s.recv(1024)
s.send('get_t\r\n')
time.sleep(GET_T_TIMEOUT)
data += s.recv(1024)
s.close()
except:
print("Error connecting to %s %s" % (host, port))
syslog.syslog(syslog.LOG_ERR, "Error connecting to %s %s" % (host, port))
sys.exit(1)
for line in data.splitlines():
if re.match(r'[PT].*#[ ]?[\d]{1,2} = [\d.]{1,5}', line):
s = re.search(r'([PT]).*#[ ]?([\d]{1,2}) = ([\d.]{1,5})',line).groups()
result["%s%s" % (s[0], s[1])] = s[2]
try:
f = open(host, 'w')
for k in sorted(result.keys()):
f.write("%s:%s\n" % (k,result[k]))
f.close()
except:
print("No access to the file %s%s" % (WORK_DIR, host))
syslog.syslog(syslog.LOG_ERR, "No access to the file %s%s" % (WORK_DIR, host))
sys.exit(1)
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment