Example #1
0
hosts_no_match = []
date_curr = datetime.now()
"""
Find all hosts that match the expired period
"""
for host in hosts:
    matchObj = re.search(r'_(\d{6})\d+_', host['name'], re.M | re.I)
    if matchObj:
        host_date = datetime.strptime('20%d' % int(matchObj.group(1)),
                                      '%Y%m%d')
        timediff = (date_curr - host_date).days
        if (timediff >= int(args.max_age)):
            host['timediff'] = timediff
            hosts_exclude.append(host)
    else:
        logger.debug("No matches for host: %s" % host)
        hosts_no_match.append(host)
"""
Perform (or not >> --no-run) the removal of preveously identified hosts
"""
total = hosts_exclude.__len__()
logger.info("Hosts to remove: %d" % total)
if args.run and total > 0:
    x = 0
    bar = ProgressBar(
        maxval=total,
        widgets=[Percentage(),
                 ReverseBar(),
                 ETA(),
                 RotatingMarker(),
                 Timer()]).start()
Example #2
0
hosts_no_match = []
date_curr = datetime.now()

"""
Find all hosts that match the expired period
"""
for host in hosts:
	matchObj = re.search( r'_(\d{6})\d+_', host['name'], re.M|re.I)
	if matchObj:
		host_date = datetime.strptime('20%d' % int(matchObj.group(1)), '%Y%m%d')
		timediff = (date_curr - host_date).days
		if ( timediff >= int(args.max_age) ):
			host['timediff'] = timediff
			hosts_exclude.append(host)
	else:
		logger.debug("No matches for host: %s" % host)
		hosts_no_match.append(host)



"""
Perform (or not >> --no-run) the removal of preveously identified hosts
"""
total = hosts_exclude.__len__()
logger.info("Hosts to remove: %d" % total)
if args.run and total > 0:
	x = 0
	bar = ProgressBar(maxval=total,widgets=[Percentage(), ReverseBar(), ETA(), RotatingMarker(), Timer()]).start()
	logger.echo = False
	for host in hosts_exclude:
		x += 1
LOGFILE = "/tmp/%s.log" % path.basename(argv[0])
logger = LogPrint(echo=args.verbose, logfile=LOGFILE, loglevel=args.loglevel.upper())
try:
	zapi = ZabbixAPI(args.url,timeout=TIMEOUT)
	zapi.login(args.user,args.password)
except Exception, e:
	logger.error("Unable to login: %s" % (e))
	exit(1)

# Filtra do hostgroup _DELETED_ os hosts com status 0.
a = zapi.host.get(groupids=[ args.groupid ],selectInterfaces='extend',output=['name','hostid'],filter={"status": 0})
#,templateids=['10069'])

for host in a:
	logger.debug("Doing host %s" % host['name'])
	ok = 0
	for ip in host['interfaces']:
		if ip['main'] == '1':
			zapi.host.update(hostid=host['hostid'],status=1)
			# Verifico se pareco linux. Poderia verificar pelo template... Mas ai seriam multiplas buscas
			if ( 'lf' in host['name'] or 'ls' in host['name'] or 'lb' in host['name'] ):
				if args.sshkey:
					exe = "ssh -i %s root@%s \"/etc/init.d/snmpd stop\"" % (ip['ip'],args.sshkey)
				else:
					exe = "ssh root@%s \"/etc/init.d/snmpd stop\"" % (ip['ip'])
				(status,out) = commands.getstatusoutput(exe)
				logger.warning("Failed on %s" % ip['ip'])
	if ok == 0:
		logger.warning("Failed for %s" % host['name'])
zapi.user.logout()
logger.info('1) Descobrir as redes:')
network_ranges = network_api_get_ranges()
for local in network_ranges:
	logger.info('Achei {0} redes para {1}'.format((len(network_ranges[local]) -2),local) ) # diminuo dois para ignorar o disabled e total_weight

#2) Identificar proxies disponiveis
logger.info('2) Descobrir os proxies cadastrados:')
proxies = proxies_get()
for local in proxies:
	#logger.print_json(proxies[local])
	logger.info('Achei {0} proxies para {1}'.format(len(proxies[local]),local))

#2.1) Calcular a distribuicao das redes por proxy
#2.2) Atribuir peso de quantidade maxima de hosts por rede, e calcular assim por proxy
discovery_rule_per_proxy()
logger.debug('2.1) Total de ranges por proxy:')
if ( loglevels[args.loglevel.upper()] < loglevels['INFO'] ):
	for local in proxies:
		for x in proxies[local]:
			logger.debug('\tRanges p/ {0} = {1}'.format(x['host'],len(x['ranges'])))

#3) Distribuir de fato os discoveries nos proxies
logger.info('3) Realocar e desabilitar todas as regras de discovery para os proxies')
proxy_distribute_rules()

#4) Identificar os hosts que devem ser migrados de proxy
logger.info('4) Identificar os hosts que devem ser migrados de proxy')
if ( args.move ):
	hosts_get_all()
else:
	logger.info('\t--no-move utilizado. Nao necessario.')
try:
    zapi = ZabbixAPI(args.url, timeout=TIMEOUT)
    zapi.login(args.user, args.password)
except Exception, e:
    logger.error("Unable to login: %s" % (e))
    exit(1)

# Filtra do hostgroup _DELETED_ os hosts com status 0.
a = zapi.host.get(groupids=[args.groupid],
                  selectInterfaces='extend',
                  output=['name', 'hostid'],
                  filter={"status": 0})
#,templateids=['10069'])

for host in a:
    logger.debug("Doing host %s" % host['name'])
    ok = 0
    for ip in host['interfaces']:
        if ip['main'] == '1':
            zapi.host.update(hostid=host['hostid'], status=1)
            # Verifico se pareco linux. Poderia verificar pelo template... Mas ai seriam multiplas buscas
            if ('lf' in host['name'] or 'ls' in host['name']
                    or 'lb' in host['name']):
                if args.sshkey:
                    exe = "ssh -i %s root@%s \"/etc/init.d/snmpd stop\"" % (
                        ip['ip'], args.sshkey)
                else:
                    exe = "ssh root@%s \"/etc/init.d/snmpd stop\"" % (ip['ip'])
                (status, out) = commands.getstatusoutput(exe)
                logger.warning("Failed on %s" % ip['ip'])
    if ok == 0: