Commits

Yuri Piratello  committed 1f4464b

First commit

  • Participants

Comments (0)

Files changed (141)

+*.pyc
+.idea
+settings.py
+settings.local.py

File client/__init__.py

+__author__ = 'yuri'
+  

File client/client.py

+# encoding: utf-8
+import httplib
+import time
+import plugins
+import subprocess
+import os
+import platform
+import datetime
+import commands
+from deploy import execute_task
+import sys
+import client_utils
+
+try:
+    from hashlib import md5  #nao existe no 2.4
+except:
+    from md5 import md5
+
+#adicionais
+interface = ''
+_so = platform.uname()[0]
+hostname = platform.uname()[1]
+
+PROJECT_DIR = os.path.realpath(os.path.dirname(sys.argv[0]))
+if _so == 'Linux':
+    PLUGINS_DIR = PROJECT_DIR + '/plugins'
+    PLUGINS_BKP_DIR =PROJECT_DIR + '/bkp'
+elif _so == 'Windows':
+    PLUGINS_DIR = PROJECT_DIR + '\\plugins'
+    PLUGINS_BKP_DIR = PROJECT_DIR + '\\bkp'
+
+URL_PLUGINS = 'http://localhost'
+SERVER = 'localhost'
+PORT = 8003
+HEADERS = {}
+
+if not os.path.isdir(PLUGINS_BKP_DIR):
+    os.mkdir(PLUGINS_BKP_DIR)
+
+
+## codigo do nosklo do #python-br
+def netstat_info():
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-rn'], stdout=subprocess.PIPE, env={'LANG': 'C'})
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-rnf', 'inet'], stdout=subprocess.PIPE)
+        for i in xrange(3):
+            p.stdout.readline() # linhas que atrapalham a leitura
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+if _so == 'Linux':
+    iface_key = 'iface'
+else:
+    iface_key = 'netif'
+
+# identifica a interface primaria de roteamento
+if not _so == 'Windows':
+    for row in netstat_info():
+        if 'UG' in row['flags']:
+            iface = row[iface_key]
+            break
+
+def gen_id():
+    if _so == 'Linux':
+        lineMac = commands.getoutput("ifconfig").split("\n")[0].split()
+        if lineMac[3] == 'HWaddr':
+            mac = lineMac[4]
+        else:
+            mac = lineMac[6]
+        # IP linux comando ip route get 8.8.8.8
+        ip = commands.getoutput('ip route get 8.8.8.8').replace('\n','').split()[commands.getoutput('ip route get 8.8.8.8').replace('\n','').split().index('src')+1]
+        HASH = mac + ' ' + ip + ' ' + hostname
+    elif _so == 'Windows':
+        ip = client_utils.getIPAddressesWindows()[0]
+        mac = client_utils.getMACAddressWindows(ip)[0]
+        HASH = mac + ' ' + ip + ' ' + hostname
+    else:
+        p = subprocess.Popen(['/sbin/ifconfig', iface], stdout=subprocess.PIPE)
+        p.stdout.readline().strip() ## ignorar primeira linha da saida do ifconfig
+        mac = p.stdout.readline().strip().split()[1]
+        p.stdout.readline().strip()
+        ip = p.stdout.readline().strip().split()[1]
+        HASH = mac + ' ' + ip + ' ' + hostname
+    return md5(HASH).hexdigest()
+
+def getHost():
+    """
+        Retorna uma tupla com: Hostname, Mac, IP
+    """
+    retorno = []
+    retorno.append(hostname)
+    if _so == 'Linux':
+        lineMac = commands.getoutput("ifconfig").split("\n")[0].split()
+        if lineMac[3] == 'HWaddr':
+            retorno.append(lineMac[4])
+        else:
+            retorno.append(lineMac[6])
+        # IP linux comando ip route get 8.8.8.8
+        retorno.append(commands.getoutput('ip route get 8.8.8.8').replace('\n','').split()[commands.getoutput('ip route get 8.8.8.8').replace('\n','').split().index('src')+1])
+    elif _so == 'Windows':
+        retorno.append(client_utils.getMACAddressWindows(client_utils.getIPAddressesWindows()[0])[0])
+        retorno.append(client_utils.getIPAddressesWindows()[0])
+    else:
+        p = subprocess.Popen(['/sbin/ifconfig', iface], stdout=subprocess.PIPE)
+        p.stdout.readline().strip() ## ignorar primeira linha da saida do ifconfig
+        retorno.append(p.stdout.readline().strip().split()[1])
+        p.stdout.readline().strip()
+        retorno.append(p.stdout.readline().strip().split()[1])
+    return retorno
+
+Data = plugins.Data
+host = getHost()
+
+Data.append(['identify', str(datetime.datetime.now()), 'hostname', host[0]])
+Data.append(['identify', str(datetime.datetime.now()), 'mac', host[1]])
+Data.append(['identify', str(datetime.datetime.now()), 'ip', host[2]])
+try:
+    while True:
+#        try:
+        if Data:
+            HEADERS['Data'] = Data.pop(0)
+            HEADERS['HID'] = gen_id()
+            con = httplib.HTTPConnection(SERVER, PORT)
+            con.request('GET','/', None, HEADERS)
+            req = con.getresponse()
+            print ""
+            print "%s PEGOU O RESPONSE!!!!" % str(datetime.datetime.now())[:19]
+            print ""
+            print "Headers"
+            print req.getheaders()
+            print ""
+            headers = req.getheaders()
+            for header in headers:
+                print ""
+                print "HEADER"
+                print header
+                if header[0][:4] == "task":
+                    task = header[1].split('#_#')
+                    print "------"*10
+                    print "Eh uma task %s - %s" % (task[1],task[2])
+                    print "------"*10
+                    result, HEADERS['Data'] = execute_task(hid=gen_id(),task=task[1],task_id=task[0],plugin=task[2])
+                    if result == "reload":
+                        print "------"*10
+                        print "Recarregando plugins...."
+                        print "------"*10
+                        reload(plugins)
+                        print "------"*10
+                        print "Plugins recarregados!"
+                        print "------"*10
+                    HEADERS['HID'] = gen_id()
+                    print "------"*10
+                    print "Enviando HEADERS"
+                    print "------"*10
+                    print HEADERS
+                    print "------"*10
+                    con2 = httplib.HTTPConnection(SERVER, PORT)
+                    con2.request('GET','/', None, HEADERS)
+                    req2 = con2.getresponse()
+                    headers2 = req2.getheaders()
+                    print "HEADERS 2"
+                    for header2 in headers2:
+                        print "%s: %s" % header2
+                    time.sleep(1)
+                    print "FECHANDO CON2"
+                    con2.close()
+            print "FECHANDO CON"
+            con.close()
+#        except:
+#            print "try again"
+        time.sleep(1)
+except KeyboardInterrupt:
+    print " Bye!"
+    from signal import SIGKILL
+    os.kill(os.getpid(),SIGKILL)

File client/client_utils.py

+def getIPAddressesWindows():
+    from ctypes import Structure, windll, sizeof
+    from ctypes import POINTER, byref
+    from ctypes import c_ulong, c_uint, c_ubyte, c_char
+    MAX_ADAPTER_DESCRIPTION_LENGTH = 128
+    MAX_ADAPTER_NAME_LENGTH = 256
+    MAX_ADAPTER_ADDRESS_LENGTH = 8
+    class IP_ADDR_STRING(Structure):
+        pass
+    LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING)
+    IP_ADDR_STRING._fields_ = [
+        ("next", LP_IP_ADDR_STRING),
+        ("ipAddress", c_char * 16),
+        ("ipMask", c_char * 16),
+        ("context", c_ulong)]
+    class IP_ADAPTER_INFO (Structure):
+        pass
+    LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO)
+    IP_ADAPTER_INFO._fields_ = [
+        ("next", LP_IP_ADAPTER_INFO),
+        ("comboIndex", c_ulong),
+        ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)),
+        ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)),
+        ("addressLength", c_uint),
+        ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH),
+        ("index", c_ulong),
+        ("type", c_uint),
+        ("dhcpEnabled", c_uint),
+        ("currentIpAddress", LP_IP_ADDR_STRING),
+        ("ipAddressList", IP_ADDR_STRING),
+        ("gatewayList", IP_ADDR_STRING),
+        ("dhcpServer", IP_ADDR_STRING),
+        ("haveWins", c_uint),
+        ("primaryWinsServer", IP_ADDR_STRING),
+        ("secondaryWinsServer", IP_ADDR_STRING),
+        ("leaseObtained", c_ulong),
+        ("leaseExpires", c_ulong)]
+    GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo
+    GetAdaptersInfo.restype = c_ulong
+    GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)]
+    adapterList = (IP_ADAPTER_INFO * 10)()
+    buflen = c_ulong(sizeof(adapterList))
+    rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen))
+    ips = []
+    if rc == 0:
+        for a in adapterList:
+            adNode = a.ipAddressList
+            while True:
+                ipAddr = adNode.ipAddress
+                if ipAddr:
+                    if ipAddr != '0.0.0.0' and ipAddr != '127.0.0.0':
+                        ips.append(ipAddr)
+                adNode = adNode.next
+                if not adNode:
+                    break
+    return ips
+
+def getIPAddressesLinux():
+    import array
+    import struct
+    import socket
+    import fcntl
+    ips = []
+    ifaces = []
+    SIOCGIFCONF = 0x8912  #define SIOCGIFCONF
+    BYTES = 4096          # Simply define the byte size
+    # get_iface_list function definition 
+    # this function will return array of all 'up' interfaces 
+    # create the socket object to get the interface list
+    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    # prepare the struct variable
+    names = array.array('B', '\0' * BYTES)
+    # the trick is to get the list from ioctl
+    bytelen = struct.unpack('iL', fcntl.ioctl(sck.fileno(), SIOCGIFCONF, struct.pack('iL', BYTES, names.buffer_info()[0])))[0]
+    # convert it to string
+    namestr = names.tostring()
+    # return the interfaces as array
+    ifaces = [namestr[i:i+32].split('\0', 1)[0] for i in range(0, bytelen, 32)]
+    # well, what to do? print it out maybe... 
+    for iface in ifaces:
+        if not iface == 'lo':
+            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+            ips.append(socket.inet_ntoa(fcntl.ioctl(
+                s.fileno(),
+                0x8915,  # SIOCGIFADDR
+                struct.pack('256s', iface[:15])
+            )[20:24]))
+    return ips
+
+def getMACAddressWindows(host='localhost'):
+    """ Returns the MAC address of a network host, requires >= WIN2K. """
+    # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812
+    import ctypes
+    import socket
+    import struct
+ 
+    # Check for api availability
+    try:
+        SendARP = ctypes.windll.Iphlpapi.SendARP
+    except:
+        raise NotImplementedError('Usage only on Windows 2000 and above')
+ 
+    # Doesn't work with loopbacks, but let's try and help.
+    if host == '127.0.0.1' or host.lower() == 'localhost':
+        host = socket.gethostname()
+ 
+    # gethostbyname blocks, so use it wisely.
+    try:
+        inetaddr = ctypes.windll.wsock32.inet_addr(host)
+        if inetaddr in (0, -1):
+            raise Exception
+    except:
+        hostip = socket.gethostbyname(host)
+        inetaddr = ctypes.windll.wsock32.inet_addr(hostip)
+ 
+    buffer = ctypes.c_buffer(6)
+    addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
+    if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
+        raise WindowsError('Retreival of mac address(%s) - failed' % host)
+ 
+    # Convert binary data into a string.
+    macaddr = ''
+    for intval in struct.unpack('BBBBBB', buffer):
+        if intval > 15:
+            replacestr = '0x'
+        else:
+            replacestr = 'x'
+        if macaddr != '':
+            macaddr = ':'.join([macaddr, hex(intval).replace(replacestr, '')])
+        else:
+            macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
+ 
+    return macaddr.upper()

File client/deploy.py

+# encoding: utf-8
+"""
+user.py
+
+Created by Yuri Zanola Piratello on 2011-09-22.
+"""
+import ConfigParser
+import datetime
+import httplib
+import shutil
+import urllib2
+import os
+
+URL_PLUGINS = 'http://localhost/plugins'
+PLUGINS_DIR = '/home/yuri/client/plugins'
+PLUGINS_BKP_DIR = '/home/yuri/client/bkp'
+SERVER = 'localhost'
+PORT = 8003
+HEADERS = {}
+
+if not os.path.exists('/tmp/noc_plugins/'):
+    os.mkdir('/tmp/noc_plugins/')
+
+def write_cfg(plugin=''):
+    print "(write_cfg) - Escrevendo cfg (%s)" % plugin
+    if not os.path.isfile(PLUGINS_DIR + '/%s.cfg'):
+        plugin_cfg = open('%s/%s.cfg' % (PLUGINS_DIR, plugin), 'w')
+        cfg = ConfigParser.RawConfigParser()
+        cfg.add_section('global')
+        cfg.write(plugin_cfg)
+        plugin_cfg.close()
+
+def get_plugin_conf(hid, plugin):
+    print "(get_plugin_conf) - Baixando configuracoes do plugin (%s)" % plugin
+    new_sleep = 0
+    add_params = ''
+    HEADERS = {}
+    HEADERS['Data'] = 'get_plugin_conf#_#%s' % plugin
+    HEADERS['HID'] = hid
+    print "HEADERS DEPLOY"
+    print HEADERS
+    con = httplib.HTTPConnection(SERVER, PORT)
+    con.request('GET','/', None, HEADERS)
+    req = con.getresponse()
+    headers = req.getheaders()
+    print "get_plugin_conf - headers"
+    print headers
+    for header in headers:
+        print 'Header'
+        print header
+        if header[0]=='plugin_configuration':
+            print "Plugin Configuration"
+            add_params = header[1].split('#_#')[1:]
+            new_sleep = header[1].split('#_#')[0].split(":")
+            new_sleep = datetime.time(int(new_sleep[0]),int(new_sleep[1]),int(new_sleep[2]))
+            new_sleep = new_sleep.second + (new_sleep.minute*60) + (new_sleep.hour*3600)
+    print "New Sleep"
+    print new_sleep
+    print "add_params"
+    print add_params
+    return new_sleep, add_params
+
+def get_plugin(hid='', plugin=''):
+    print "(get_plugin) - Baixando plugin (%s)" % plugin
+    plugin_download = urllib2.urlopen('%s/%s.py' % (URL_PLUGINS, plugin))
+    plugin_py = open('tmp/noc_plugins/%s.py' % plugin, 'w')
+    plugin_py.write(plugin_download.read())
+    plugin_py.close()
+    if os.path.isfile("%s/%s.py" % (PLUGINS_DIR, plugin)) and os.path.isfile("%s/%s.cfg" % (PLUGINS_DIR, plugin)):
+        shutil.copy2(PLUGINS_DIR + "/%s.py" % plugin, PLUGINS_BKP_DIR +'/%s.py_%s' % (plugin,str(datetime.datetime.now()).replace(" ","_")[:19]))
+        shutil.copy2(PLUGINS_DIR + "/%s.cfg" % plugin, PLUGINS_BKP_DIR +'/%s.cfg_%s' % (plugin,str(datetime.datetime.now()).replace(" ","_")[:19]))
+    shutil.copy2('tmp/%s.py' % plugin, '%s/%s.py' % (PLUGINS_DIR, plugin))
+    os.remove('tmp/%s.py' % plugin)
+    write_cfg(plugin)
+    update_plugin(hid, plugin)
+    return True
+
+def update_plugin(hid='', plugin=''):
+    '''
+        Atualiza as configuracoes do plugin passado no parametro
+    '''
+    print "(update_plugin) - Atualizando plugin (%s) " % plugin
+    if os.path.isfile(PLUGINS_DIR + "/%s.py" % plugin) and os.path.isfile(PLUGINS_DIR + "/%s.cfg" % plugin):
+
+        shutil.copy2(PLUGINS_DIR + '/%s.cfg' % plugin, PLUGINS_DIR + '/%s.cfg.bkp' % plugin)
+        #Set Configs
+        total_seconds, add_params = get_plugin_conf(hid, plugin)
+        cp = ConfigParser.RawConfigParser()
+        cp.add_section('global')
+        cp.set('global','sleep',total_seconds)
+        if add_params[0]:
+            for add_conf in add_params:
+                cp.set('global','%s' % add_conf.split('=')[0],'%s' % add_conf.split('=')[1])
+        file = open(PLUGINS_DIR + "/%s.cfg" % plugin, 'r+')
+        cp.write(file)
+        file.close()
+        return True
+    else:
+        return get_plugin(hid, plugin)
+
+def execute_task(hid='', task='', task_id='', plugin=''):
+    print "(execute) - Executando tarefa (%s) plugin (%s)" % (task, plugin)
+    if task == "update_plugin":
+        if update_plugin(hid, plugin):
+            updateInit(hid)
+            return "reload","update_task#_#%s#_#0" % str(task_id)
+        else:
+            return "fail","update_task#_#%s#_#1" % str(task_id)
+
+
+# ATUALIZA __init__.py com todos os plugins, etc
+def updateInit(hid = ''):
+    all_plugins_host = []
+    all_plugins_local= []
+    HEADERS = {}
+    HEADERS['Data'] = 'get_plugins_on_host'
+    HEADERS['HID'] = hid
+    con = httplib.HTTPConnection(SERVER, PORT)
+    con.request('GET','/', None, HEADERS)
+    req = con.getresponse()
+    headers = req.getheaders()
+    print "Headers  - get_plugins_on_host"
+    print headers
+    for header in headers:
+        if header[0] == 'plugin_on_host':
+            plugins = header[1].split(', ')
+            for plugin in plugins:
+                all_plugins_host.append(plugin)
+    dirList=os.listdir(PLUGINS_DIR)
+    for file_name in dirList:
+        #get extension
+        if file_name.split('.')[1] == "cfg" and len(file_name.split('.')) == 2:
+            #add plugin
+            all_plugins_local.append(file_name.split('.')[0])
+    print "Plugins local"
+    print all_plugins_local
+    print "Plugins host"
+    print all_plugins_host
+    for plugin_host in all_plugins_host:
+        #verifica se todos os plugins configurados no banco, estao no host
+        if plugin_host not in all_plugins_local:
+            #caso nao esteja, baixa o plugin
+            get_plugin(hid, plugin_host)
+    #faz backup do __init__.py dos plugins
+    shutil.copy2(PLUGINS_DIR + '/__init__.py', PLUGINS_BKP_DIR +"/__init__.py.bkp_%s" % str(datetime.datetime.now()).replace(" ","_")[:19])
+    new_text_init = 'import plugin\n'
+    for plugin in all_plugins_host:
+        new_text_init = new_text_init + "\nimport %s" % plugin
+    new_text_init = new_text_init + "\nData = plugin.Data\n"
+    file = open(PLUGINS_DIR + '/__init__.py','w')
+    file.write(new_text_init)

File client/plugin.log

Empty file added.

File client/plugins/__init__.py

+import plugin
+import teste10sec
+import check_task
+#import uptime
+#import memory
+#import diskusage
+#import network
+#import user
+#import portscan
+#import process
+#import temperature
+Data = plugin.Data

File client/plugins/check_task.py

+__author__ = 'yuri'
+import plugin
+
+Data = plugin.Data
+
+class check_task(plugin.Plugin):
+    def action(self):
+        ret = {}
+        ret['check_task'] = 'check_task'
+        return ret
+check_task()

File client/plugins/deploy.cfg

+[global]
+sleep=5

File client/plugins/diskusage.cfg

+[global]
+sleep = 120

File client/plugins/diskusage.py

+import plugin
+import subprocess
+import os
+_so = os.uname()[0]
+def read_df():
+    p = subprocess.Popen(['df'], stdout=subprocess.PIPE)
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+class diskusage(plugin.Plugin):
+    def action(self):
+        data = dict()
+        if _so == 'Linux':
+            for line in read_df():
+                if 'none' not in line['filesystem'] and 'tmpfs' not in line['filesystem'] and 'udev' not in line['filesystem']:
+                    data['%s_available' % line['filesystem']] = line['available']
+                    data['%s_used' % line['filesystem']] = line['used']
+                    data['%s_1k_blocks' % line['filesystem']] = line['1k-blocks']
+                    data['%s_mounted' % line['filesystem']] = line['mounted']
+                    data['%s_capacity' % line['filesystem']] = line['use%']
+        else:
+            for line in read_df():
+                data['%s_used' % line['filesystem']] = line['used']
+                data['%s_available' % line['filesystem']] = line['avail']
+                data['%s_512_blocks' % line['filesystem']] = line['512-blocks']
+                data['%s_capacity' % line['filesystem']] = line['capacity']
+                data['%s_mounted' % line['filesystem']] = line['mounted']
+        return data
+
+diskusage()

File client/plugins/memory.cfg

+[global]
+sleep = 90

File client/plugins/memory.py

+import psutil
+import plugin
+Data = plugin.Data
+
+class memory(plugin.Plugin):
+    """docstring for memory"""
+    def action(self):
+        data = dict()
+        data['total_memory'] = str(int(psutil.TOTAL_PHYMEM)/1024**2)
+        data['used_memory'] = str(int(psutil.used_phymem())/1024**2)
+        data['avaible_memory'] = str(int(psutil.avail_phymem())/1024**2)
+        data['total_swap_memory'] = str(int(psutil.total_virtmem())/1024**2)
+        data['used_swap_memory'] = str(int(psutil.used_virtmem())/1024**2)
+        data['avaible_swap_memory'] = str(int(psutil.avail_virtmem())/1024**2)
+        return data
+
+memory()

File client/plugins/memory.py.old

+import plugin
+Data = plugin.Data
+
+import os
+
+class memory(plugin.Plugin):
+    def action(self):
+        data = dict()
+        values = os.popen('free').read().split('\n')
+        memory = []
+        for i in values[1].split(' '):
+            if i and i != 'Mem:':
+                memory.append(i)
+        swap = []
+        for i in values[3].split(' '):
+            if i and i != 'Swap:':
+                swap.append(i)
+        data['memory_total'] = memory[0]
+        data['memory_used'] = memory[1]
+        data['memory_free'] = memory[2]
+        data['memory_shared'] = memory[3]
+        data['memory_buffers'] = memory[4]
+        data['memory_cached'] = memory[5]
+        data['swap_total'] = swap[0]
+        data['swap_used'] = swap[1]
+        data['swap_free'] = swap[2]
+        return data
+
+
+memory()
+

File client/plugins/network.cfg

+[global]
+sleep = 45

File client/plugins/network.py

+# encoding: utf-8
+import subprocess
+import os
+import plugin
+#adicionais
+interface=''
+
+_so = os.uname()[0]
+
+## codigo do nosklo do #python-br
+def netstat_info():
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-rn'], stdout=subprocess.PIPE, 
+           env={'LANG': 'C'})
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-rnf', 'inet'], stdout=subprocess.PIPE)
+        for i in xrange(3):
+            p.stdout.readline() # linhas que atrapalham a leitura
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+
+def netstat_packets(interface=None):
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-i'], stdout=subprocess.PIPE) # -i ou --interfaces retorna a mesma coisa !!!
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-I', interface], stdout=subprocess.PIPE)
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((p, part.strip()) for p, part in zip(header, line.split()))
+            
+if _so == 'Linux':
+    iface_key = 'iface'
+else:
+    iface_key = 'netif'
+
+# identifica a interface primaria de roteamento
+for row in netstat_info():
+    if 'UG' in row['flags']:
+        iface = row[iface_key]
+        break
+
+def get_network_info(interface):
+    data = {}
+    if _so == 'Linux':
+        for row in netstat_packets():
+            if row['iface'] == interface:
+                data['mtu'] = row['mtu']
+                data['packets_in'] = row['rx-ok']
+                data['packets_in_errors'] = row['rx-err']
+                data['packets_in_dropped'] = row['rx-drp']
+                data['packets_in_over'] = row['rx-ovr']
+                data['packets_out'] = row['tx-ok']
+                data['packets_out_errors'] = row['tx-err']
+                data['packts_out_dropped'] = row['tx-drp']
+                data['packets_out_over'] = row['tx-ovr']
+    else:
+        for row in netstat_packets(interface):
+            if 'Link' in row['network']:
+                data['packets_in'] = row['ipkts']
+                data['mtu'] = row['mtu']
+                data['packets_in_errors'] = row['ierrs']
+                data['packets_out'] = row['opkts']
+                data['packets_out_errors'] = row['oerrs']
+                data['device'] = row['name']
+                data['packets_collision'] = row['coll']
+    data['device'] = interface 
+    return [(key,value) for (key,value) in data.items()]
+
+        
+class network (plugin.Plugin):
+        def action(self):
+            data = dict(get_network_info(iface))
+            return data                              
+network()

File client/plugins/plugin.py

+import time
+import os.path
+import datetime
+import threading
+import ConfigParser
+
+# adicionais
+Data = list()
+
+class Plugin(threading.Thread):
+    configFile = None
+    config = None
+
+    def __init__(self, *args, **kwargs):
+        threading.Thread.__init__(self, *args, **kwargs)
+        self.config = dict()
+        self.config['noConfigFile'] = None
+        self.config['sleep'] = 3600
+        self.config['plugin'] = str(self)[1:-1].split('(')[0]
+        configFile = "plugins/%s.cfg" % self.config['plugin'] 
+        if os.path.isfile(configFile):
+            self.configFile = configFile
+            cp = ConfigParser.ConfigParser()
+            try:
+                cp.readfp(open(self.configFile))
+                for item in cp.items('global'):
+                    self.config[item[0]] = item[1]
+            except:
+               self.config['noConfigFile'] = True
+        self.start()
+
+    def action(self):
+        data = dict()
+        return data
+
+    def save(self, data=None):
+        if data:
+            session = str(datetime.datetime.now())
+            for key in data.keys():
+                values = list()
+                values.append(self.config['plugin'])
+                values.append(session)
+                values.append(key)
+                values.append(data[key])
+                Data.append(values)
+
+    def run(self):
+        while True:
+            time.sleep(float(self.config['sleep']))
+            data = self.action()
+            if data:
+                self.save(data)

File client/plugins/plugins_lucas/__init__.py

+import plugin
+Data = plugin.Data
+#import hardware
+#import uptime
+#import dns
+#import webservice
+#import mediaproxy
+#import diskusage
+import openser

File client/plugins/plugins_lucas/asdsad.py

+#!/bin/env python2
+import dmidecode
+import plugin
+Data = plugin.Data
+memoria = dmidecode.memory()
+memorialimpa=dict()
+
+def tiraespaco():
+    for i in memoria.keys():
+        for key in memoria[i]['data'].keys():
+            if type(memoria[i]['data'][key]) == list:
+                memoria[i]['data'][key] = memoria[i]['data'][key][6:7].pop() 
+            memoria[i]['data'][key] = str(memoria[i]['data'][key]).replace(' ', '')
+            memoria[i]['data'][key.replace(' ', '')] = memoria[i]['data'][key]
+            del memoria[i]['data'][key]
+            
+def removerdicdata():    
+    for i in memoria.keys():
+        for jey in memoria[i]:
+            if str(jey) != "data":
+                memorialimpa["%s_%s" % (i,jey)] = memoria[i][jey]
+            #del memoria[i][jey]
+        for key in memoria[i]['data'].keys():
+            #print i, type(i) , key, type(key)
+            memorialimpa["%s_%s" % (i,key)] = memoria[i]['data'][key]
+        #del memoria[i]['data']
+
+
+
+    
+class hardware(plugin.Plugin):
+     def action(self):
+        data = dict()   
+        for item in memorialimpa.keys():
+            data[item] = memorialimpa[item]
+                   
+        return data
+
+tiraespaco()
+removerdicdata()
+hardware()
+#print memoria

File client/plugins/plugins_lucas/client.py

+# encoding: utf-8
+import httplib
+import time
+import plugins
+import subprocess
+import os
+try:
+    from hashlib import md5  #nao existe no 2.4
+except:
+    from md5 import md5
+
+
+#adicionais
+interface = ''
+_so = os.uname()[0]
+hostname = os.uname()[1]
+
+## codigo do nosklo do #python-br
+
+def netstat_info():
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-rn'], stdout=subprocess.PIPE, 
+           env={'LANG': 'C'})
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-rnf', 'inet'], stdout=subprocess.PIPE)
+        for i in xrange(3):
+            p.stdout.readline() # linhas que atrapalham a leitura
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+if _so == 'Linux':
+    iface_key = 'iface'
+else:
+    iface_key = 'netif'
+
+# identifica a interface primaria de roteamento
+for row in netstat_info():
+    if 'UG' in row['flags']:
+        iface = row[iface_key]
+        break
+
+def gen_id():
+    if _so == 'Linux':
+        p = subprocess.Popen(['/sbin/ifconfig', iface], stdout=subprocess.PIPE)
+        mac = p.stdout.readline().strip().split()[4]
+        ip = p.stdout.readline().strip().replace('addr:','').split()[1]
+        HASH = mac + '|' + ip + '|' + hostname
+    else:
+        p = subprocess.Popen(['/sbin/ifconfig', iface], stdout=subprocess.PIPE)
+        p.stdout.readline().strip() ## ignorar primeira linha da saida do ifconfig
+        mac = p.stdout.readline().strip().split()[1]
+        p.stdout.readline().strip()
+        ip = p.stdout.readline().strip().split()[1]
+        HASH = mac + '|' + ip + '|' + hostname
+    return md5(HASH).hexdigest()
+
+
+
+SERVER = '10.192.250.234'
+PORT = 8000
+HEADERS = {}
+HEADERS['Client'] = 'DevMonCli 0.1'
+HEADERS['Acao'] = 'Funcao'
+Data = plugins.Data
+
+
+while True:
+     try:
+         if Data:
+             HEADERS['Data'] = Data.pop(0)
+             HEADERS['HID'] = gen_id()
+             con = httplib.HTTPConnection(SERVER, PORT)
+             con.request('GET','/', None, HEADERS)
+ 
+             req = con.getresponse()
+ 
+             headers = req.getheaders()
+             for header in headers:
+                 print('%s: %s' % header)
+ 
+             con.close()
+     except:
+         print "try again"
+     time.sleep(1)

File client/plugins/plugins_lucas/compress.py

+#!/usr/bin/env python
+import os
+import optparse
+import subprocess
+import sys
+
+here = os.path.dirname(__file__)
+
+def main():
+    usage = "usage: %prog [file1..fileN]"
+    description = """With no file paths given this script will automatically
+compress all jQuery-based files of the admin app. Requires the Google Closure
+Compiler library and Java version 6 or later."""
+    parser = optparse.OptionParser(usage, description=description)
+    parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar",
+                      help="path to Closure Compiler jar file")
+    parser.add_option("-v", "--verbose",
+                      action="store_true", dest="verbose")
+    parser.add_option("-q", "--quiet",
+                      action="store_false", dest="verbose")
+    (options, args) = parser.parse_args()
+
+    compiler = os.path.expanduser(options.compiler)
+    if not os.path.exists(compiler):
+        sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler)
+
+    if not args:
+        if options.verbose:
+            sys.stdout.write("No filenames given; defaulting to admin scripts\n")
+        args = [os.path.join(here, f) for f in [
+            "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]]
+
+    for arg in args:
+        if not arg.endswith(".js"):
+            arg = arg + ".js"
+        to_compress = os.path.expanduser(arg)
+        if os.path.exists(to_compress):
+            to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js"))
+            cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min)
+            if options.verbose:
+                sys.stdout.write("Running: %s\n" % cmd)
+            subprocess.call(cmd.split())
+        else:
+            sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress)
+
+if __name__ == '__main__':
+    main()

File client/plugins/plugins_lucas/daemonize.py

+import os
+import sys
+
+UMASK = 0
+WORKDIR = "/tmp"
+MAXFD = 1024
+
+if (hasattr(os, "devnull")):
+   REDIRECT_TO = os.devnull
+else:
+   REDIRECT_TO = "/dev/null"
+
+def createDaemon():
+   try:
+      pid = os.fork()
+   except OSError, e:
+      raise Exception, "%s [%d]" % (e.strerror, e.errno)
+
+   if (pid == 0):
+      os.setsid()
+      try:
+         pid = os.fork()
+      except OSError, e:
+         raise Exception, "%s [%d]" % (e.strerror, e.errno)
+
+      if (pid == 0):
+         os.chdir(WORKDIR)
+         os.umask(UMASK)
+      else:
+         os._exit(0)
+   else:
+      os._exit(0)
+
+   import resource
+   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
+   if (maxfd == resource.RLIM_INFINITY):
+      maxfd = MAXFD
+  
+   for fd in range(0, maxfd):
+      try:
+         os.close(fd)
+      except OSError:
+         pass
+
+   os.open(REDIRECT_TO, os.O_RDWR)
+   os.dup2(0, 1)
+   os.dup2(0, 2)
+
+   return(0)

File client/plugins/plugins_lucas/diskusage.py

+import plugin
+import subprocess
+import os
+_so = os.uname()[0]
+def read_df():
+    p = subprocess.Popen(['df'], stdout=subprocess.PIPE)
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+class diskusage(plugin.Plugin):
+    def action(self):
+        data = dict()
+        if _so == 'Linux':
+            for line in read_df():
+                if 'none' not in line['filesystem'] and 'tmpfs' not in line['filesystem'] and 'udev' not in line['filesystem']:
+                    data['%s_available' % line['filesystem']] = line['available']
+                    data['%s_used' % line['filesystem']] = line['used']
+                    data['%s_1k_blocks' % line['filesystem']] = line['1k-blocks']
+                    data['%s_mounted' % line['filesystem']] = line['mounted']
+                    data['%s_capacity' % line['filesystem']] = line['use%']
+        else:
+            for line in read_df():
+                data['%s_used' % line['filesystem']] = line['used']
+                data['%s_available' % line['filesystem']] = line['avail']
+                data['%s_512_blocks' % line['filesystem']] = line['512-blocks']
+                data['%s_capacity' % line['filesystem']] = line['capacity']
+                data['%s_mounted' % line['filesystem']] = line['mounted']
+        return data
+        
+
+diskusage()

File client/plugins/plugins_lucas/dns.py

+import plugin
+Data = plugin.Data
+
+import os
+
+class dns(plugin.Plugin):
+    def action(self):
+        data = dict()
+        dir = os.path.dirname(__file__)
+        shparams = ""
+        for i in self.params:
+            shparams += i + "=" + self.params[i] + " "
+        values = os.popen('sh %s/%s/dns.sh %s' % (dir,self.config['plugin'],shparams)).read().split('\n')
+        for value in values:
+            if value :
+                key = value.split('|')
+                data[key[0]] = key[1]
+	return data
+
+
+dns()
+

File client/plugins/plugins_lucas/hardware.py

+import plugin
+import dmidecode
+Data = plugin.Data
+
+lista=[]
+def lerdmidecode(dicionario, anterior=''):
+    for i in dicionario:
+        ant = ''
+        teste = dicionario[i]
+        
+        if isinstance(teste, list):
+            if teste.count(None) == 11:
+                dicionario[i]=dicionario[i][6:7].pop()
+                
+        if isinstance(teste, dict):
+            #print i, type(i)
+            if i != '':
+                #print ant, type(an
+                ant = anterior + "%s*&&*" % i
+            else:
+                ant = ''
+            lerdmidecode(teste, anterior=ant)
+
+        else:
+            resultado(um="%s%s,"  % (anterior, i),dois="%s" % dicionario[i])
+         
+
+def resultado(um='',dois=''):
+    lista.append((um,dois))
+        
+
+lerdmidecode(dmidecode.memory())
+lerdmidecode(dmidecode.bios())
+lerdmidecode(dmidecode.baseboard())
+lerdmidecode(dmidecode.processor())
+lerdmidecode(dmidecode.system())
+lerdmidecode(dmidecode.connector())
+lerdmidecode(dmidecode.slot())
+
+
+#for i in lista:
+#    print i[0], i[1]
+
+
+class hardware(plugin.Plugin):
+    def action(self):
+        data = dict()
+        for i in lista:
+            data[i[0]] = i[1]
+
+        return data
+        
+        
+hardware()

File client/plugins/plugins_lucas/macfield.py

+import re
+
+from django.utils.translation import ugettext_lazy as _
+from django.forms import fields
+from django.db import models
+
+MAC_RE = r'^([0-9a-fA-F]{2}([:-]?|$)){6}$'
+mac_re = re.compile(MAC_RE)
+
+class MACAddressFormField(fields.RegexField):
+    default_error_messages = {
+        'invalid': _(u'Enter a valid MAC address.'),
+    }
+
+    def __init__(self, *args, **kwargs):
+        super(MACAddressFormField, self).__init__(mac_re, *args, **kwargs)
+
+class MACAddressField(models.Field):
+    empty_strings_allowed = False
+    def __init__(self, *args, **kwargs):
+        kwargs['max_length'] = 17
+        super(MACAddressField, self).__init__(*args, **kwargs)
+
+    def get_internal_type(self):
+        return "CharField"
+
+    def formfield(self, **kwargs):
+        defaults = {'form_class': MACAddressFormField}
+        defaults.update(kwargs)
+        return super(MACAddressField, self).formfield(**defaults)

File client/plugins/plugins_lucas/manage.py

+#!/usr/bin/env python
+from django.core.management import execute_manager
+import imp
+try:
+    imp.find_module('settings') # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
+    sys.exit(1)
+
+import settings
+
+if __name__ == "__main__":
+    execute_manager(settings)

File client/plugins/plugins_lucas/mediaproxy.py

+import plugin
+import socket
+Data = plugin.Data
+
+
+
+def lermediaproxy(ip,port):
+    try:
+        cliente = socket.socket()
+        cliente.connect((ip,int(port)))
+        cliente.send("status\n")
+        retorno = cliente.recv(1024)[6:7]
+        cliente.close()
+    except:
+        retorno = "-1"
+        
+    return retorno
+
+
+class mediaproxy(plugin.Plugin):
+    """
+    """
+    
+    def action(self):
+        data=dict()
+        #print self.config["ip"], self.config["port"]
+        data['status']= lermediaproxy(ip=self.config["ip"],port=self.config["port"])
+        return data
+
+
+
+
+mediaproxy()

File client/plugins/plugins_lucas/memory.py

+import psutil
+import plugin
+Data = plugin.Data
+
+class memory(plugin.Plugin):
+    """docstring for memory"""
+    def action(self):
+        data = dict()
+        data['total_memory'] = int(psutil.TOTAL_PHYMEM)/1024**2
+        data['used_memory'] = int(psutil.used_phymem())/1024**2
+        data['avaible_memory'] = int(psutil.avail_phymem())/1024**2
+        data['total_swap_memory'] = int(psutil.total_virtmem())/1024**2
+        data['used_swap_memory'] = int(psutil.used_virtmem())/1024**2
+        data['avaible_swap_memory'] = int(psutil.avail_virtmem())/1024**2
+        return data
+
+memory()

File client/plugins/plugins_lucas/mimi.py

+#!/bin/env python2
+import dmidecode
+import plugin
+memoria = dmidecode.memory()
+
+
+def tiraespaco():
+    for i in memoria.keys():
+        for key in memoria[i]['data'].keys():
+            if type(memoria[i]['data'][key]) == list:
+	  	        aux = memoria[i]['data'][key][6:7].pop()
+
+            memoria[i]['data'][key] = aux 
+            memoria[i]['data'][key] = str(memoria[i]['data'][key]).replace(' ', '')
+            memoria[i]['data'][key.replace(' ', '')] = memoria[i]['data'][key]
+            del memoria[i]['data'][key]
+            
+
+class Hardware(plugin.Plugin):
+    def action(self):
+      tiraespaco()
+      data = dict()
+      print memoria.keys()
+      for key in memoria.keys():
+          data[key] = memoria[key]
+      return data
+
+Hardware()

File client/plugins/plugins_lucas/models.py

+from django.db import models
+import macfield
+# Create your models here.
+class Plugin(models.Model):
+    name = models.CharField(max_length=100)
+    description = models.TextField()
+    tag = models.SlugField()
+    def __unicode__(self):
+        return u'%s' %(self.name)
+
+
+
+class Host(models.Model):
+    hid = models.CharField(max_length=32)
+    name = models.CharField(max_length=100)
+    ip = models.IPAddressField()
+    mac = macfield.MACAddressField()
+    def __unicode__(self):
+            return u'%s' % (self.hid)
+
+class Data(models.Model):
+    dtrecording = models.DateTimeField(auto_now=False)
+    dtexecution = models.DateTimeField(auto_now=False)
+    key = models.CharField(max_length=200)
+    value = models.CharField(max_length=100)
+    id_host = models.ForeignKey(Host)
+    id_plugin = models.ForeignKey(Plugin)
+    def __unicode__(self):
+        return u'%s %s %s %s %s %s' % (self.dtrecording, self.dtexecution, self.key, self.value, self.id_host, self.id_plugin)

File client/plugins/plugins_lucas/network.py

+# encoding: utf-8
+import subprocess
+import os
+import plugin
+#adicionais
+interface=''
+
+_so = os.uname()[0]
+
+## codigo do nosklo do #python-br
+def netstat_info():
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-rn'], stdout=subprocess.PIPE, 
+           env={'LANG': 'C'})
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-rnf', 'inet'], stdout=subprocess.PIPE)
+        for i in xrange(3):
+            p.stdout.readline() # linhas que atrapalham a leitura
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((k, part.strip()) for k, part in zip(header, line.split()))
+
+
+def netstat_packets(interface=None):
+    if _so == 'Linux':
+        p = subprocess.Popen(['netstat', '-i'], stdout=subprocess.PIPE) # -i ou --interfaces retorna a mesma coisa !!!
+        p.stdout.readline() # ignora linha de titulo
+    else:
+        p = subprocess.Popen(['netstat', '-I', interface], stdout=subprocess.PIPE)
+    header = p.stdout.readline().lower().split()
+    for line in p.stdout:
+        yield dict((p, part.strip()) for p, part in zip(header, line.split()))
+            
+if _so == 'Linux':
+    iface_key = 'iface'
+else:
+    iface_key = 'netif'
+
+# identifica a interface primaria de roteamento
+for row in netstat_info():
+    if 'UG' in row['flags']:
+        iface = row[iface_key]
+        break
+
+def get_network_info(interface):
+    data = {}
+    if _so == 'Linux':
+        for row in netstat_packets():
+            if row['iface'] == interface:
+                data['mtu'] = row['mtu']
+                data['packets_in'] = row['rx-ok']
+                data['packets_in_errors'] = row['rx-err']
+                data['packets_in_dropped'] = row['rx-drp']
+                data['packets_in_over'] = row['rx-ovr']
+                data['packets_out'] = row['tx-ok']
+                data['packets_out_errors'] = row['tx-err']
+                data['packts_out_dropped'] = row['tx-drp']
+                data['packets_out_over'] = row['tx-ovr']
+    else:
+        for row in netstat_packets(interface):
+            if 'Link' in row['network']:
+                data['packets_in'] = row['ipkts']
+                data['mtu'] = row['mtu']
+                data['packets_in_errors'] = row['ierrs']
+                data['packets_out'] = row['opkts']
+                data['packets_out_errors'] = row['oerrs']
+                data['device'] = row['name']
+                data['packets_collision'] = row['coll']
+    data['device'] = interface 
+    return [(key,value) for (key,value) in data.items()]
+
+        
+class network (plugin.Plugin):
+        def action(self):
+            data = dict(get_network_info(iface))
+            return data                              
+network()

File client/plugins/plugins_lucas/openser.py

+import socket
+import plugin
+import time
+Data = plugin.Data
+#from socket import *
+def testesip(ip=None,port=None):
+    teste = "REGISTER sip:555.555.555.555 SIP/2.0\nContent-Length: 0\nVia: SIP/2.0/UDP 555.555.555.555:5060;rport;branch=z9hG4bKvPCUMOX6FBP4ndB50JefUQ..\nFrom:'Teste' <sip:teste@555.555.555>;tag=108770813642\nExpires: 180\nTo: 'Teste' <sip:teste@555.555.555.555>\nContact:<sip:teste@555.555.555.555:5060>\nCSeq: 1 REGISTER\nMax-Forwards: 70\nCall-ID: 877231864@555.555.555.555\n"
+    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    s.settimeout(3)
+    s.sendto(teste, (ip,int(port)))
+    a = ''
+    try:
+        a = s.recv(1024)
+    except:
+        pass
+        
+    time.sleep(0.5)
+    s.close()
+
+    if a:
+        return "Ok"
+    else:
+        return "Error"
+
+    
+
+
+class openser(plugin.Plugin):
+    def action(self):
+        data = dict()
+        data['status']= testesip(ip=self.config["ip"],port=self.config["port"])
+        return data
+
+
+
+
+
+
+
+openser()
+        
+
+    
+    

File client/plugins/plugins_lucas/paginator.py

+#  Based on: http://www.djangosnippets.org/snippets/73/
+#
+#  Modified by Sean Reifschneider to be smarter about surrounding page
+#  link context.  For usage documentation see:
+#
+#     http://www.tummy.com/Community/Articles/django-pagination/
+
+from django import template
+
+register = template.Library()
+
+def paginator(context, adjacent_pages=2):
+    """
+    To be used in conjunction with the object_list generic view.
+
+    Adds pagination context variables for use in displaying first, adjacent and
+    last page links in addition to those created by the object_list generic
+    view.
+
+    """
+    startPage = max(context['page'] - adjacent_pages, 1)
+    if startPage <= 3: startPage = 1
+    endPage = context['page'] + adjacent_pages + 1
+    if endPage >= context['pages'] - 1: endPage = context['pages'] + 1
+    page_numbers = [n for n in range(startPage, endPage) \
+            if n > 0 and n <= context['pages']]
+    page_obj = context['page_obj']
+    paginator = context['paginator']
+
+    return {
+        'page_obj': page_obj,
+        'paginator': paginator,
+        'hits': context['hits'],
+        'results_per_page': context['results_per_page'],
+        'page': context['page'],
+        'pages': context['pages'],
+        'page_numbers': page_numbers,
+        'next': context['next'],
+        'previous': context['previous'],
+        'has_next': context['has_next'],
+        'has_previous': context['has_previous'],
+        'show_first': 1 not in page_numbers,
+        'show_last': context['pages'] not in page_numbers,
+    }
+
+register.inclusion_tag('paginator.html', takes_context=True)(paginator)

File client/plugins/plugins_lucas/plugin.py

+Data = list()
+
+import md5
+import time
+import os.path
+import datetime
+import threading
+import ConfigParser
+
+class Plugin(threading.Thread):
+    configFile = None
+    config = None
+    params = None
+    con = None
+    cur = None
+
+    def __init__(self, *args, **kwargs):
+        threading.Thread.__init__(self, *args, **kwargs)
+        self.config = dict()
+        self.params = dict()
+        self.config['noConfigFile'] = None
+        self.config['sleep'] = 3600
+        self.config['plugin'] = str(self)[1:-1].split('(')[0]
+        configFile = "plugins/%s/%s.cfg" % (self.config['plugin'],self.config['plugin']) 
+        if os.path.isfile(configFile):
+            self.configFile = configFile
+            cp = ConfigParser.ConfigParser()
+            try:
+                cp.readfp(open(self.configFile))
+                for item in cp.items('global'):
+                    self.config[item[0]] = item[1]
+                for item in cp.items('params'):
+                    self.params[item[0]] = item[1]
+            except:
+               self.config['noConfigFile'] = True
+        self.start()
+
+    def action(self):
+        data = dict()
+        return data
+
+    def save(self, data=None):
+        if data:
+            session = str(datetime.datetime.now())
+            for key in data.keys():
+                values = list()
+                values.append(self.config['plugin'])
+                values.append(session)
+                values.append(key)
+                values.append(data[key])
+                Data.append(values)
+
+    def run(self):
+        while True:
+            time.sleep(float(self.config['sleep']))
+            data = self.action()
+            if data:
+                self.save(data)

File client/plugins/plugins_lucas/portscan.py

+#!/usr/bin/env python
+# encoding: utf-8
+from socket import *   
+import plugin  
+
+
+class portscan(plugin.Plugin):
+    def action(self):
+        data = dict()
+        target = 'localhost' 
+        targetIP = gethostbyname(target)  
+        for i in xrange(0,65335):  
+            s = socket(AF_INET, SOCK_STREAM)  
+            result = s.connect_ex((targetIP, i))  
+            if(result == 0) :  
+                data['%d' % i] = 'Open'
+        return data
+
+portscan()

File client/plugins/plugins_lucas/process.py

+#!/usr/bin/env python
+# encoding: utf-8
+"""
+process.py
+
+Created by Lucas de Biaggi Januário on 2011-02-23.
+"""
+import psutil
+import plugin
+
+def process_list():
+    p_list=list(psutil.process_iter())[:-6:-1]
+    for i in xrange(len(p_list)):
+       yield str(p_list[i]).replace('(','').replace(',','').replace(')','').replace('pid=','').split()[1]
+
+
+def run_process_list():
+    count=0
+    data=dict()
+    for i in process_list():
+        p=psutil.Process(int(i))
+        count+=1
+        data['process_%s_name' % count] = p.name
+        data['process_%s_memory_percent' % count] = p.get_memory_percent()
+        data['process_%s_cpu_percent' % count] = p.get_cpu_percent(interval=0.0001)
+        data['process_%s_memory_used' % count] = p.get_memory_info()
+    return data
+
+
+class process(plugin.Plugin):
+    def action(self):
+        data=dict()
+        data=run_process_list()
+        return data
+        
+try:
+    process()
+except NoSuchProcess:
+    process()
+

File client/plugins/plugins_lucas/psycopg.py

Empty file added.

File client/plugins/plugins_lucas/radius.py

+#!/bin/env python2
+from plugins import Plugins
+import pyrad
+
+def teste_radius():

File client/plugins/plugins_lucas/server.py

+import datetime
+from BaseHTTPServer import *
+
+class myServer(HTTPServer):
+    pass
+
+
+class myHandler(BaseHTTPRequestHandler):
+    server_version = 'DevMonSrv 0.1'
+    sys_version = ''
+    def do_GET(r):
+        r.send_response(200)
+        r.send_header('HeaderChave','HeaderValor')
+        r.end_headers()
+        
+        fp = open('recebidos.txt', 'a')
+        fp.write('\n%s\n' % datetime.datetime.now())
+        for header in r.headers.items():
+            fp.write('%s: %s\n' % header)
+        fp.close()
+
+
+server_address = ('', 8000)
+httpd = myServer(server_address, myHandler)
+httpd.serve_forever()

File client/plugins/plugins_lucas/server2.py

+import datetime
+from BaseHTTPServer import *
+import psycopg2
+import os
+### DB ###
+conn = psycopg2.connect("dbname=teste user=postgres password=123456")
+cur = conn.cursor()
+##########
+### Variaveis ###
+hid = ''
+ip = ''
+SQL_HID = "INSERT INTO noc_host (hid, name, ip, mac) VALUES (%s, %s, %s, %s);"
+SQL_PLUGIN = "INSERT INTO noc_plugin (name, description, tag) VALUES (%s, %s, %s);"
+SQL = "INSERT INTO noc_data (dtrecording, dtexecution, key, value, id_host_id, id_plugin_id) VALUES (%s, %s, %s, %s, %s, %s);"
+name = 'hostname'
+mac = '00:00:00:00:00:00'
+desc = 'desc'
+tag = 'tag'
+class myServer(HTTPServer):
+    pass
+
+class myHandler(BaseHTTPRequestHandler):
+    server_version = 'DevMonSrv 0.1'
+    sys_version = os.uname()[1]
+    def do_GET(r):
+        r.send_response(200)
+        r.send_header('HeaderChave','HeaderValor')
+        r.end_headers()
+
+        print r.headers.items()
+        hid = str(r.headers.items()[4][1])
+        dados = r.headers.items()[5][1]
+        dados=dados[1:-1].replace("'","").split(', ')
+        # print dados
+        plugin=dados[0]
+        ip  = r.client_address[0]
+        DATA_PLUGIN = (str(plugin), str(desc), str(tag),)
+        DATA_HID = (str(hid), str(name), str(ip), str(mac),)
+        #### Cadastro PLUGIN
+        cur.execute("SELECT * from noc_plugin where name = '%s'" % DATA_PLUGIN[0])
+        cur.fetchall()
+        if cur.rowcount:
+            print 'plugin cadastrado'
+        else:
+            cur.execute(SQL_PLUGIN, DATA_PLUGIN)
+
+        
+        #### Cadastro HID
+        cur.execute("SELECT * FROM noc_host where hid = '%s';" % DATA_HID[0])
+        cur.fetchall()
+        if cur.rowcount:
+            print 'HID NA DB!!! '
+        else:
+            cur.execute(SQL_HID, DATA_HID)        
+            print 'cadastrado novo client'
+        # IDS para tabela noc_data
+        cur.execute("SELECT id FROM noc_host where hid = '%s';" % DATA_HID[0])
+        id_hid = cur.fetchall()
+        print id_hid
+        id_hid = str(id_hid).replace('[','').replace(']','').replace('(','').replace(')','').replace(',','')
+        cur.execute("SELECT id FROM noc_plugin where name = '%s'" % DATA_PLUGIN[0])
+        id_plugin = cur.fetchall()
+        id_plugin = str(id_plugin).replace('[','').replace(']','').replace('(','').replace(')','').replace(',','')
+        dtrecord = str(datetime.datetime.now())
+        #### Cadastro das infos geradas pelos plugins
+        DATA = (str(dtrecord),str(dados[1]),str(dados[2]), str(dados[3]), str(id_hid), str(id_plugin))
+        cur.execute(SQL, DATA)
+        try:
+            conn.commit()
+            
+        except:
+            print 'travou-se'
+        
+        
+
+server_address = ('', 8000)
+httpd = myServer(server_address, myHandler)
+httpd.serve_forever()
+

File client/plugins/plugins_lucas/t.py

+import time
+import plugins
+
+Data = plugins.Data
+
+while True:
+    if Data:
+        item = Data.pop(0)
+        print item
+    time.sleep(0.5)

File client/plugins/plugins_lucas/t2.py

+#!/usr/bin/python2
+
+import time
+import plugins_bkp as plugins
+
+Data = plugins.Data
+
+while True:
+    if Data:
+        item = Data.pop(0)
+        print item
+    time.sleep(0.2)

File client/plugins/plugins_lucas/tBanco.py

+#!/usr/bin/python
+__author__ = 'yuri'
+#['plugin','data-hora','chave','valor']
+#['uptime', '2011-07-06 21:08:45.416558', 'uptime', '']
+import time
+import plugins
+import MySQLdb as mysql
+
+
+Data = plugins.Data
+
+while True:
+    if Data:
+        item = Data.pop(0)
+        try:
+            con = mysql.connect(host='localhost', user='root', passwd='123mudar', db='noc')
+            cur = con.cursor()
+            sql = "insert into core_information (hid_id, plugin, dt, plugin_key, value) values ('3b9866eda23990e3389496ba494c6d74','%s','%s','%s','%s')" % (item[0],item[1],item[2], item[3])
+            #print sql
+            cur.execute(sql)
+            cur.execute("select hid from core_host where hid = '3b9866eda23990e3389496ba494c6d74'")
+            con.commit()
+            cur.close()
+            con.close()
+        except:
+            print "Nao foi possivel conectar ao banco"
+    time.sleep(0.2)

File client/plugins/plugins_lucas/temperature.py

+#!/usr/bin/env python
+# encoding: utf-8
+"""
+temperature.py
+
+Created by Lucas de Biaggi Januário on 2011-02-25.
+Copyright (c) 2011 __Feito Por Lucas Januário__. All rights reserved.
+"""
+import plugin
+
+
+def read_temp():
+    try:
+        f = open('/proc/acpi/thermal_zone/THRM/temperature')
+    except:
+        print "cannot read /proc/acpi/thermal_zone/THRM/temperature check if acpi is on"
+    # com o arquivo de temperatura aberto o f ira ler a temperature
+    f=f.readline().strip().split()
+    ## exclui 'temperature' da lista que esta em f
+    del(f[0])
+    headers = ['temperature', 'unit_scale']
+    yield dict(zip(headers,f))
+
+
+class temperature(plugin.Plugin):
+        def action(self):
+            data=dict()
+            for i in read_temp():
+                data=i
+            return data
+            
+
+temperature()
+    
+        

File client/plugins/plugins_lucas/teste.py

+#!/usr/bin/env python
+
+import time
+import daemonize
+
+def log():
+    fp = open('log.log', 'a')
+    fp.write(str(time.time()))
+    fp.write('\n')
+    fp.close()
+
+daemonize.createDaemon()
+
+while True:
+    time.sleep(5)
+    log()

File client/plugins/plugins_lucas/teste10sec.py

+import plugin
+