Changeset 445
- Timestamp:
- 05/15/08 12:17:27
- Arquivos:
-
- cacic/trunk/agente-linux/pycacic/src/README (modified) (1 diff)
- cacic/trunk/agente-linux/pycacic/src/cacic.py (modified) (5 diffs)
- cacic/trunk/agente-linux/pycacic/src/chksis.py (modified) (1 diff)
- cacic/trunk/agente-linux/pycacic/src/coletores/col_hard.py (modified) (1 diff)
- cacic/trunk/agente-linux/pycacic/src/coletores/lib/computador.py (modified) (2 diffs)
- cacic/trunk/agente-linux/pycacic/src/coletores/lib/lshw (modified) (previous)
- cacic/trunk/agente-linux/pycacic/src/coletores/lib/url.py (modified) (2 diffs)
- cacic/trunk/agente-linux/pycacic/src/config/cacic.conf (modified) (2 diffs)
- cacic/trunk/agente-linux/pycacic/src/config/io.py (modified) (12 diffs)
- cacic/trunk/agente-linux/pycacic/src/ger_cols.py (modified) (11 diffs)
- cacic/trunk/agente-linux/pycacic/src/globals.py (modified) (5 diffs)
- cacic/trunk/agente-linux/pycacic/src/lang/language.py (modified) (2 diffs)
- cacic/trunk/agente-linux/pycacic/src/teste_coletores.py (deleted)
- cacic/trunk/agente-linux/pycacic/src/update.py (added)
Legenda:
- Não modificado
- Adicionado
- Removido
- Modificado
- Copiado
- Movido
cacic/trunk/agente-linux/pycacic/src/README
r425 r445 7 7 # |__| /__/ \____/ |__| \__\ \____/ |__| \____/ # 8 8 # # 9 # VERSAO TESTE#9 # VERSAO DESENVOLVIMENTO # 10 10 # # 11 11 ################################################################ 12 12 13 Primeiramente deve-se alterar, configurar, o arquivo /config/cacic.conf13 Primeiramente deve-se alterar, configurar, o arquivo config/cacic.conf 14 14 informando o endereco, usuario e senha do Gerente Web. 15 15 16 Apos executar, como super usuario, o arquivo /cacic.py que ficara rodando em background.17 Para utilizar a interface deve executar o arquivo /gui.py (como usuario normal),18 enecessario ter instalado o GTK+, PyGTK e o Glade. Caso execute corretamente ira16 Apos executar, como super-usuario, o arquivo cacic.py que ficara rodando em background. 17 Para utilizar a interface deve executar o arquivo gui.py (como usuario normal). 18 E necessario ter instalado o GTK+, PyGTK e o Glade. Caso execute corretamente ira 19 19 aparecer um icone no systray. Ao clicar nesse icone abre a janela com a possibilidade 20 20 de forcar uma coleta. 21 21 22 obs: Ao clicar em "Forcar Coleta" observe no terminal que esta rodando o /cacic.py se apareceu22 obs: Ao clicar em "Forcar Coleta" observe no terminal que esta rodando o cacic.py se apareceu 23 23 a mensagem de "coleta forcada". 24 24 cacic/trunk/agente-linux/pycacic/src/cacic.py
r437 r445 5 5 import time 6 6 import thread 7 7 8 from socket import * 8 9 from ger_cols import * 9 10 from globals import Globals 10 11 12 import gc as garbage_collector 13 11 14 class Cacic: 12 15 13 VERSION = ' 1.0.0'16 VERSION = '0.0.1' 14 17 15 18 def __init__(self): 16 19 try: 17 # adiciona o diretorio do pycacic ao sys.path 18 sys.path[0] = Globals.PATH 20 # somente executa se estiver como root 21 if not self.isRoot(): 22 raise Exception("Para executar o programa é necessário ser super-usuário (root).") 19 23 24 # verifica se o pycacic esta instalado 25 # senao chama configurador do cacic.conf 20 26 if not Globals.INSTALLED: 21 27 Globals.install() 22 28 23 if not self.isRoot(): 24 raise Exception("Para executar o programa é necessário estar como super usuário (root).") 25 29 # Habilita o coletor de lixo do Python 30 garbage_collector.enable() 26 31 print "\n\tBem-Vindo ao PyCacic\n" 27 32 # flags do Gerente de Coletas … … 34 39 self.host, self.port, self.buf, self.addr = Globals.getSocketAttr() 35 40 # criando socket 36 self.udp_sock = socket.socket(AF_INET, SOCK_DGRAM) 37 self.udp_sock.bind(self.addr) 41 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 42 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 43 self.sock.bind(self.addr) 38 44 # executa thread para escutar o socket 39 45 thread.start_new_thread(self.checkSocket, ()) … … 46 52 self.conecta() 47 53 # com o coletor parado (dormindo) dispara timeout para iniciar a coleta 48 # apos o intervalo de tempo definido pelo servidor 54 # apos o intervalo de tempo definido pelo servidor 49 55 thread.start_new_thread(self.timeout, ()) 50 56 # intervalo 51 57 self.interval = self.gc.getInterval() 52 print(" `---- Coleta iniciara daqui a %s minutos" % (self.interval/60)) 53 #self.atualiza() 58 print(" `---- Coleta iniciara em %s minutos" % (self.interval/60)) 54 59 # se esta habilitado a executar ou e uma coleta forcada 55 60 if self.gc_ok or len(self.isforcada) > 0: … … 61 66 # inicia coletas 62 67 self.gc.coletas_forcadas = self.isforcada 63 self.start() 68 self.start() 69 # Executa o coletor de lixo 70 garbage_collector.collect() 64 71 time.sleep(2) 65 # fechando conexao 66 self.udp_sock.close() 72 # sai 73 self.quit() 74 except socket.error, e: 75 print 'PyCacic already is running.' 67 76 except Exception, e: 68 import traceback 69 traceback.print_exc() 70 print e 77 print e 78 # remover depois 79 import traceback 80 traceback.print_exc() 71 81 72 82 def isRoot(self): … … 101 111 print(" Contato com o Gerente Web: %s" % strftime("%H:%M:%S")) 102 112 self.gc.readXML(xml) 113 # verifica atualizacao 114 """ 115 if self.gc.hasNew(): 116 print ' Versao nova disponivel !!!' 117 print ' `--- Iniciando atualizacao...' 118 self.gc.atualiza() 119 print ' `--- Novo pacote salvo' 120 #chama atualizador e sai 121 os.system('python %s/update.py -pkg %s -tmp %s &' % (Globals.PATH, self.gc.pacote_disponivel, 'pycacic_temp')) 122 #self.quit() 123 """ 103 124 104 125 def checkSocket(self): 105 126 """Verifica comunicacao com a interface""" 106 data, self.addr = self.udp_sock.recvfrom(self.buf)107 self.isforcada.append(data)108 self.checkSocket()127 while 1: 128 data, self.addr = self.sock.recvfrom(self.buf) 129 self.isforcada.append(data) 109 130 131 def quit(self): 132 """Sai do programa fechando conexao do socket""" 133 self.sock.close() 134 print 'Bye' 135 sys.exit() 110 136 111 137 if __name__ == '__main__': cacic/trunk/agente-linux/pycacic/src/chksis.py
r417 r445 5 5 pass 6 6 7 # ESCREVER CÓDIGO EM SHELL SCRIPT PARA MONITORAR DE HORA-EM-HORA (CRON) 8 # SE O CACIC.PY ESTÁ EM EXECUÇÃO. cacic/trunk/agente-linux/pycacic/src/coletores/col_hard.py
r437 r445 43 43 inicio = strftime("%H:%M:%S") 44 44 # CPUs 45 CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial(), 'te_cpu_frequencia###%s' % i.getFrequencia()]) for i in self.computer.getCPU()]) 45 # removido frequencia CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial(), 'te_cpu_frequencia###%s' % i.getFrequencia()]) for i in self.computer.getCPU()]) 46 CPUs = '#CPU#'.join(['#FIELD#'.join(['te_cpu_desc###%s' % i.getDescricao(), 'te_cpu_fabricante###%s' % i.getFabricante(), 'te_cpu_serial###%s' % i.getSerial()]) for i in self.computer.getCPU()]) 46 47 self.addChave('te_Tripa_CPU', CPUs) 47 48 # Placas/Configuracoes de Redes cacic/trunk/agente-linux/pycacic/src/coletores/lib/computador.py
r434 r445 518 518 # modificando a permissao do arquivo 519 519 if stat.S_IMODE(os.lstat(lshw)[stat.ST_MODE]) < 448: 520 os.chmod(lshw, 777)520 os.chmod(lshw, 0755) 521 521 return commands.getoutput(lshw + " -xml") 522 522 else: … … 647 647 if a == 'id' and valor[0:3] == 'ide': 648 648 self.getIDEInfo(filho) 649 if a == 'id' and valor in ('network','bridge'):649 if a == 'id' and (valor[0:7] == 'network' or valor[0:6] == 'bridge'): 650 650 self.getRedeInfo(filho) 651 651 if a == 'id' and valor == 'communication': cacic/trunk/agente-linux/pycacic/src/coletores/lib/url.py
r434 r445 22 22 import ftplib 23 23 from coletores.coletor import * 24 from xml.dom import minidom, Node 24 25 25 26 class URL : … … 65 66 def isOK(self, xml): 66 67 """Retorna se o XML gerado esta valido ou nao""" 67 status = xml.getElementsByTagName('STATUS')[0].firstChild.nodeValue 68 if status != "OK": 69 return 0 # False 70 return 1 # True 68 try: 69 xml = minidom.parseString(xml) 70 status = xml.getElementsByTagName('STATUS')[0].firstChild.nodeValue 71 if status != "OK": 72 return 0 # False 73 return 1 # True 74 except: 75 return 0 71 76 72 77 def ftpConecta(self, server, login, senha): cacic/trunk/agente-linux/pycacic/src/config/cacic.conf
r434 r445 1 1 <?xml version="1.0" encoding="iso-8859-1" ?> 2 2 <config> 3 <status> 4 <param id="installed" value="yes" /> 5 <param id="test" value="no" /> 6 </status> 3 <pycacic id="agente_pycacic"> 4 <dir>/usr/share/pycacic</dir> 5 <hash>ZZZ</hash> 6 <password>PW_CACIC</password> 7 <status> 8 <param id="installed" value="yes" /> 9 <param id="test" value="no" /> 10 </status> 11 </pycacic> 7 12 <server id="gerente_web"> 8 <address>http://1 0.71.0.121</address>13 <address>http://127.0.0.1</address> 9 14 <ws>/cacic2/ws/</ws> 10 15 <page>get_config.php</page> … … 14 19 <description>Endereco (address) do servidor Gerente Web para buscar informacoes sobre quais coletas devem ser realizadas, intervalo de tempo entre elas, atualizao, etc. Senha (password) para acesso. E arquivo (file) que efetuara esta resposta.</description> 15 20 </server> 16 <local>17 <dir>/usr/share/pycacic</dir>18 <sha1>XXXX</sha1>19 </local>20 21 <socket> 21 22 <host>localhost</host> cacic/trunk/agente-linux/pycacic/src/config/io.py
r434 r445 14 14 import sys, os 15 15 from xml.dom import minidom, Node 16 from globals import Globals 16 17 17 18 class IOConfig: … … 20 21 21 22 Responsavel por guardar o caminho do arquivo de 22 configuracao do Cacic e efetuar a leitura dos nos principais23 configuracao do PyCacic e efetuar a leitura dos nos principais 23 24 dele. 24 25 """ 25 26 26 FILE = '%s/config/cacic.conf' % sys.path[0]27 FILE = '%s/config/cacic.conf' % Globals.PATH 27 28 28 29 def exists(): … … 59 60 return root.getElementsByTagName('coletores')[0] 60 61 61 def getStatus(): 62 def getPycacic(): 63 """Retorna o node do Pycacic""" 64 root = IOConfig.getRoot() 65 return root.getElementsByTagName('pycacic')[0] 66 67 def getPycacicStatus(): 62 68 """Retorna o node de status""" 63 root = IOConfig.getRoot() 64 return root.getElementsByTagName('status')[0] 69 pycacic = IOConfig.getPycacic() 70 for no in pycacic.childNodes: 71 if no.nodeType == Node.ELEMENT_NODE and no.nodeName == 'status': 72 return no 65 73 66 74 def getSocket(): … … 74 82 getServer = staticmethod(getServer) 75 83 getColetores = staticmethod(getColetores) 76 getStatus = staticmethod(getStatus) 84 getPycacic = staticmethod(getPycacic) 85 getPycacicStatus = staticmethod(getPycacicStatus) 77 86 getSocket = staticmethod(getSocket) 78 87 … … 82 91 83 92 Responsavel por efetuar a leitura do arquivo de configuracao 84 do cacic. Informando dados como endereco do Gerente Web,93 do PyCacic. Informando dados como endereco do Gerente Web, 85 94 usuario e senha, etc. 86 95 … … 98 107 server[no.nodeName] = no.firstChild.nodeValue 99 108 return server 109 110 def getPycacic(): 111 """Retorna um dicionario contendo as informacoes sobre o PyCacic""" 112 pycacic = {'dir' : '', 'hash' : '', 'password' : ''} 113 config = IOConfig.getPycacic() 114 for no in config.childNodes: 115 if no.nodeType == Node.ELEMENT_NODE: 116 pycacic[no.nodeName] = no.firstChild.nodeValue 117 return pycacic 100 118 101 119 def getColetor(id): … … 113 131 return coletor 114 132 115 def get Status(id):133 def getPycacicStatus(id): 116 134 """ 117 135 Retorna um dicionario contendo as informacoes de … … 119 137 """ 120 138 status = {'id' : '', 'value' : ''} 121 sts = IOConfig.get Status()139 sts = IOConfig.getPycacicStatus() 122 140 for no in sts.childNodes: 123 141 if no.nodeType == Node.ELEMENT_NODE: … … 138 156 139 157 getServer = staticmethod(getServer) 158 getPycacic = staticmethod(getPycacic) 140 159 getColetor = staticmethod(getColetor) 141 getStatus = staticmethod(getStatus) 142 getSocket = staticmethod(getSocket) 143 160 getPycacicStatus = staticmethod(getPycacicStatus) 161 getSocket = staticmethod(getSocket) 144 162 145 163 class Writer: … … 148 166 149 167 Responsavel por efetuar a escrita no arquivo de configuracao 150 do cacic. Alterando dados como se e instalacao, endereco do168 do PyCacic. Alterando dados como se e instalacao, endereco do 151 169 Gerente Web, usuario e senha, etc. 152 170 """ … … 185 203 Writer.saveXML(config.replace(sv, server)) 186 204 187 def set Status(s, v):188 """Modifica o status """205 def setPycacicStatus(s, v): 206 """Modifica o status do Pycacic""" 189 207 config = IOConfig.getFile() 208 re_pc = re.compile('<pycacic(?:.|\n)*</pycacic>') 190 209 re_st = re.compile('<status(?:.|\n)*</status>') 191 210 re_pr = re.compile('<param.*?id="'+s+'".*?/>') 211 pc = re_pc.findall(config)[0] 192 212 st = re_st.findall(config)[0] 193 213 pr = re_pr.findall(config)[0] 194 214 status = st 215 pycacic = pc 195 216 if (v): 196 217 v = "yes" … … 198 219 v = "no" 199 220 status = status.replace(pr, Writer.setNodeAttrib(pr, "value", v)) 200 Writer.saveXML(config.replace(st, status))201 221 pycacic = pycacic.replace(st, status) 222 Writer.saveXML(config.replace(pc, pycacic)) 202 223 203 224 saveXML = staticmethod(saveXML) 204 225 setServer = staticmethod(setServer) 205 set Status = staticmethod(setStatus)226 setPycacicStatus = staticmethod(setPycacicStatus) 206 227 setNodeValue = staticmethod(setNodeValue) 207 228 setNodeAttrib = staticmethod(setNodeAttrib) cacic/trunk/agente-linux/pycacic/src/ger_cols.py
r437 r445 14 14 import os 15 15 import sys 16 import commands 16 17 17 18 from coletores.coletor import * … … 63 64 # configuracoes gerais 64 65 self.versao_atual = version 65 self.versao_disponivel = '' 66 self.hash_atual = Reader.getPycacic()['hash'] 67 self.hash_disponivel = 'ZZZ' 68 self.pacote_disponivel = '' 66 69 self.exibe_bandeja = 'N' 67 70 self.exibe_erros_criticos = 'N' … … 108 111 } 109 112 self.dicionario = { 110 'te_versao_cacic' : version,111 'te_versao_gercols' : version,112 113 'in_chkcacic' : self.coletor.encripta(''), 113 114 'in_teste' : self.coletor.encripta(''), … … 116 117 'id_ftp' : self.coletor.encripta(''), 117 118 'te_fila_ftp' : self.coletor.encripta(''), 118 'te_versao_cacic' : self.coletor.encripta( version),119 'te_versao_gercols' : self.coletor.encripta( version),119 'te_versao_cacic' : self.coletor.encripta(self.versao_atual), 120 'te_versao_gercols' : self.coletor.encripta(self.versao_atual), 120 121 'te_tripa_perfis' : self.coletor.encripta(''), 121 } 122 122 } 123 123 self.separador = '=CacicIsFree=' 124 124 … … 165 165 return xml 166 166 except Exception, e: 167 raise Exception(e .message)167 raise Exception(e) 168 168 169 169 def addColeta(self, col, valor): … … 175 175 """ Le o XML gerado pelo servidor WEB """ 176 176 # returns void 177 #print "XML: "+xml178 self.xml = minidom.parseString(xml)179 177 # se nao achar o status==OK, retorna 180 if not self.url.isOK( self.xml):178 if not self.url.isOK(xml): 181 179 raise Exception('Erro ao ler XML do servidor, status não disponível') 180 self.xml = minidom.parseString(xml) 182 181 root = self.xml.getElementsByTagName('CONFIGS')[0] 183 182 # Coletores … … 187 186 for no in root.childNodes: 188 187 if no.nodeType == Node.ELEMENT_NODE: 189 if no.firstChild.nodeValue != '': 188 if no.firstChild.nodeValue != '': 190 189 if no.nodeName == 'cs_auto_update': 191 190 self.update_auto = self.decode(no.firstChild.nodeValue) … … 207 206 pass 208 207 # VERSOES 209 elif no.nodeName == 'TE_VERSAO_PYCACIC_DISPONIVEL': 210 self.versao_disponivel = self.decode(no.firstChild.nodeValue) 208 elif no.nodeName == 'TE_HASH_PYCACIC': 209 self.hash_disponivel = self.decode(no.firstChild.nodeValue) 210 elif no.nodeName == 'TE_PACOTE_PYCACIC_DISPONIVEL': 211 self.pacote_disponivel = self.decode(no.firstChild.nodeValue) 211 212 elif no.nodeName == 'in_exibe_bandeja': 212 213 self.exibe_bandeja = self.decode(no.firstChild.nodeValue) … … 244 245 return self.coletor.decripta(data).replace('\x00','') 245 246 246 def isNew(self, current, new):247 def hasNew(self, current='', new=''): 247 248 """Compara as versoes, atual com a disponivel.""" 248 return (current.replace('.','') < new.replace('.','')) 249 if current == '' or new == '': 250 current, new = self.hash_atual, self.hash_disponivel 251 return (current != new) 249 252 250 253 def atualiza(self): 251 """Atualiza os modulos dos coletores""" 252 """ 253 TODO: definir como vai ficar a string de destino dos arquivos 254 """ 254 """Atualiza os modulos dos coletores caso tenha alguma versao nova.""" 255 255 try: 256 256 # se nao tem versao nova retorna 257 if not self.isNew(self.versao_atual, self.versao_disponivel): 258 return 257 if not self.hasNew(): return '' 259 258 # conecta ao servidor ftp para buscar atualizacao 260 259 self.url.ftpConecta(self.update_server, self.update_user, self.update_pass) 260 # altera o diretorio do servidor para aonde esta o pacote 261 261 self.url.ftpAlteraDir(self.update_path) 262 #self.url.getFile('vaca.exe', 'vaca.exe') 262 # pega o pacote e salva no temporario 263 self.url.getFile(self.pacote_disponivel, '/tmp/%s' % self.pacote_disponivel) 263 264 self.url.ftpDesconecta() 264 265 except Exception, e: … … 272 273 for col in self.coletores.values(): 273 274 col.start() 274 self.coletor.addChave(col.getUVCKey(), col.getChave('UVC')) 275 if self.all_forcada or (col.getName() in self.coletas_forcadas) or col.isReady(self.OUTPUT_DAT): 275 self.coletor.addChave(col.getUVCKey(), col.getChave('UVC')) 276 if self.all_forcada or (col.getName() in self.coletas_forcadas) or col.isReady(self.OUTPUT_DAT): 276 277 page = Reader.getColetor(col.getName())['page'] 277 278 dict = col.getEncryptedDict() … … 287 288 server = '%s%s%s' % (self.cacic_server, self.cacic_ws, self.coletas_enviar[col]['page']) 288 289 xml = self.conecta(server, self.coletas_enviar[col]['dict']) 289 if self.url.isOK( minidom.parseString(xml)):290 if self.url.isOK(xml): 290 291 print(' `---- Envio OK') 291 292 else: cacic/trunk/agente-linux/pycacic/src/globals.py
r433 r445 15 15 import sys 16 16 import commands 17 from config.io import Reader 18 from config.io import Writer 17 19 18 20 19 class Globals: … … 30 29 def getSocketAttr(): 31 30 """Retorna as informacoes do Socket""" 31 from config.io import Reader 32 32 sock = Reader.getSocket() 33 33 host = sock['host'] … … 39 39 def install(): 40 40 """Abre console para configuracao do PyCacic""" 41 from config.io import Writer 41 42 print "\n\t--- Bem-Vindo a Configuracao do PyCacic ---" 42 43 print "\n\tapos preencher as informacoes abaixo o programa ira iniciar\n" … … 58 59 Globals.install() 59 60 return 60 Writer.set Status('installed', 1)61 Writer.setPycacicStatus('installed', 1) 61 62 if addr[len(addr)-1] == '/': addr = addr[:-1] 62 63 Writer.setServer('address', addr) … … 83 84 84 85 def isInstalled(): 85 return (Reader.getStatus('installed')['value'] == 'yes') 86 from config.io import Reader 87 return (Reader.getPycacicStatus('installed')['value'] == 'yes') 86 88 87 89 cacic/trunk/agente-linux/pycacic/src/lang/language.py
r434 r445 5 5 import codecs 6 6 from xml.dom import minidom, Node 7 8 from globals import Globals 7 9 8 10 class Language: … … 42 44 def openXML(self): 43 45 """Abre o arquivo XML contendo o idioma escolhido""" 44 xml_file = open( sys.path[0]+ '/lang/' + self.langs[self.lang], 'r').read()46 xml_file = open(Globals.PATH + '/lang/' + self.langs[self.lang], 'r').read() 45 47 self.xml = minidom.parseString(xml_file) 46 48
