Commit 344b865c authored by Erik Alexandre Pucci's avatar Erik Alexandre Pucci

Merge remote branch 'windows-collect/master'

Signed-off-by: default avatarErik Alexandre Pucci <eap08@c3sl.ufpr.br>
parents ccb2949a ce61b222
C3SL - Centro de Computacao Cientifica e Software Livre
Agtha Cristina de Nadai
Adriano da Luz
Aryane Ast dos Santos
Bruno Cesar Ribas
Carlos Carvalho
Cleide Luzia Bonfim Possamai
Daniel Weingaertner
Danilo Kiyoshi Simizu Yorinori
Diego Giovane Pasqualin
Eduardo Cunha de Almeida
Erik Alexandre Pucci
Fabiano Silva
Felipe Cys Laskoski
Guilherme Zasyeki Machado
Jorge Augusto Meira
Josiney de Souza
Juliana Bueno
Klismann Smoger Mottin
Luis Carlos Erpen de Bona
Marcos Castilho
Marcos Sunye
Pedro Eugenio Rocha
Renan Franca De Miranda
Ricardo Tavares De Oliveira
Rubens Massayuki Suguimoto
Thiago Henrique Dos Santos Picharski
Tiago Rodrigo Kepe
Victor Tarabola Cortiano
Vinicius Kwiecien Ruoso
This diff is collapsed.
all: src/compile.py src/proinfodataAgent.py src/collect.py
@cd src/ && python compile.py py2exe
# Copyright (C) 2004-2011 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
#
# This file is part of windows-coleta
#
# windows-coleta is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#coding: utf-8
import os
import _winreg
import ctypes
import wmi
import socket
import struct
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
# Return the value from key/subkey in windows registry
def getRegistryValue(key, subkey, value):
key = getattr(_winreg, key)
handle = _winreg.OpenKey(key, subkey)
(value, type) = _winreg.QueryValueEx(handle, value)
return value
# Return INEP
def getINEP():
return getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "INEP")
# Return Windows version
def getOSInfo(key):
return getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", key)
# Return CPU model installed in the machine
def getCpu():
return getRegistryValue("HKEY_LOCAL_MACHINE", "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString")
# Return the machine mac address
def getMac(host):
# 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
if host == '127.0.0.1' or host.lower() == 'localhost':
host = socket.gethostname()
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('Retrieval 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'
macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '' ), ":"],)
return macaddr.upper()
# Return the total physical memory installed in the machine
def getRam():
c = wmi.WMI()
mem = 0
for i in c.Win32_PhysicalMemory():
mem = mem + int (i.Capacity)
return mem / 1024
# Return disk model
def getHDDModel(disk):
return disk.Model
# Return disk size in Gigabytes
def getHDDSize(disk):
return int(disk.Size) / (1024 * 1024 * 1024)
# Return the total size of non Windows partitions
def nonWindowsPartitionSize(c):
size = 0
for partition in c.Win32_DiskPartition():
if partition.Description != "Installable File System":
if partition.Description != "Unknown":
size = size + int (partition.Size)
return size
# Return the total used disk
def diskUsed(c):
free = 0
size = 0
for disk in c.Win32_LogicalDisk (DriveType = 3):
free = free + int (disk.FreeSpace)
size = size + int (disk.Size)
return size - free
# Main collect function. This function gets the machine information and creates
# the XML
def collect():
mainTag = Element('collect')
# Collect INEP
inep = getINEP()
tagInep = SubElement(mainTag, 'inep')
tagInepValue = SubElement(tagInep, 'number', {'type':'int', 'value':inep})
# Inventory
tagInventory = SubElement(mainTag, 'inventory')
# Collect Hard Disk
c = wmi.WMI()
tagInventoryDisk = SubElement (tagInventory, 'disk', {'type':'tree'})
hddQuantity = 0
for disk in c.win32_DiskDrive():
if disk.MediaType != "Removable Media":
hddQuantity = hddQuantity + 1
tagInventoryHddQuantity = SubElement(tagInventoryDisk, 'hdd', {'quantity': str(hddQuantity)})
hddNumber = "hdd"
i = -1
for disk in c.win32_DiskDrive():
if disk.MediaType != "Removable Media":
i = i + 1
hddSize = getHDDSize(disk)
hddModel = getHDDModel(disk)
hddNumber = ''.join(["hdd", str(i)])
used = nonWindowsPartitionSize(c) + diskUsed(c)
used = used / (1024 * 1024 * 1024)
tagInventoryHdd = SubElement(tagInventoryHddQuantity, hddNumber)
tagInventoryHddValue1 = SubElement(tagInventoryHdd, 'model', {'type':'string', 'value': hddModel})
tagInventoryHddValue2 = SubElement(tagInventoryHdd, 'size', {'type':'int', 'value': str(hddSize)})
tagInventoryHddValue3 = SubElement(tagInventoryHdd, 'used', {'type':'int', 'value': str(used)})
# Collect Memory
memory = getRam()
tagInventoryMemory = SubElement(tagInventory, 'memory')
tagInventoryMemoryValue = SubElement(tagInventoryMemory, 'size', {'type':'int', 'value': str(memory)})
# Collect OS
os = getOSInfo("ProductName")
tagInventoryOs = SubElement(tagInventory, 'os')
tagInventoryOsValue1 = SubElement(tagInventoryOs, 'distro', {'type':'string', 'value':os})
tagInventoryOsValue2 = SubElement(tagInventoryOs, 'kernel', {'type':'string', 'value':'Windows'})
tagInventoryOsValue3 = SubElement(tagInventoryOs, 'type', {'type':'string', 'value':'Windows'})
# Collect CPU
cpuVersion = getCpu()
tagInventoryCPU = SubElement ( tagInventory, 'processor' )
tagInventoryCPU_value = SubElement ( tagInventoryCPU, 'model',
{'type':'string', 'value':cpuVersion} )
# Collect Mac Address
macAddress = getMac('localhost')
macAddress = macAddress[0:-1]
tagMac = SubElement(mainTag, 'mac-address')
tagMacValue = SubElement(tagMac, 'number', {'type':'string', 'value':macAddress})
tagProject = SubElement( mainTag, 'project')
tagProjectSource = SubElement(tagProject, 'source', {'type':'int', 'value':"0"})
tagUse = SubElement(mainTag, 'use')
tagUseBandUsage = SubElement(tagUse, 'bandwidth-usage', {'type':'tree'})
for i in range(1, 289):
tagNetUse = SubElement(tagUseBandUsage, 'netuse', {'id':str(i)})
tagDate = SubElement(tagNetUse, 'date', {'value':'0001-01-01', 'type':'string'})
tagTime = SubElement(tagNetUse, 'time', {'value':'0:0', 'type':'string'})
tagRx = SubElement(tagNetUse, 'rx')
tagPackets = SubElement(tagRx, 'packets', {'value':"0", 'type':'int'})
tagBytes = SubElement(tagRx, 'bytes', {'value':"0", 'type':'int'})
tagTx = SubElement(tagNetUse, 'tx')
tagPackets = SubElement(tagTx, 'packets', {'value':"0", 'type':'int'})
tagBytes = SubElement(tagTx, 'bytes', {'value':"0", 'type':'int'})
return mainTag
#coding: utf-8
from distutils.core import setup
import py2exe
setup(console=['proinfodataAgent.py'])
\ No newline at end of file
# Copyright (C) 2004-2011 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
#
# This file is part of windows-coleta
#
# windows-coleta is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#coding: utf-8
import os
import sys
import _winreg
import shutil
import subprocess
import urllib
from time import localtime, strftime
from xml.etree.ElementTree import tostring
import collect
import glob
# ==========================================
# Constants
# ==========================================
# TODO: Check compatibility with 64bit Windows (Program Files(x86) folder)
PROINFODATAPATH = os.environ["ProgramFiles"] + "\\ProInfoData"
URL = ""
# Log lifetime in days
LOGLIFETIME = 30
# ==========================================
# Classes definitions
# ==========================================
# Class log: log manipulation
class Log():
# Verify if today's log exist. If exists, the log is opened. Otherwise,
# a new one is created
def __init__(self):
date = strftime("%Y%m%d", localtime())
logpath = PROINFODATAPATH + "\log"
logfilename = date + ".log"
if (os.path.exists(logpath + "\\" + logfilename)):
self.logfile = file(logpath + "\\" + logfilename,"a")
else:
self.logfile = file(logpath + "\\" + logfilename,"w")
self.write("START: Proinfodata Agent Windows.")
def write(self, str):
self.logfile.write(strftime("%I:%M:%S", localtime()) + ": ")
self.logfile.write(str + "\n")
def close(self):
self.logfile.close()
def flush(self):
self.logfile.flush()
class clientError():
def __init__(self, retCode, error):
self.code = retCode
self.errorMsg = error
# ==========================================
# Functions definitions
# ==========================================
# Get the proinfodata version
def getVersion():
return collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "Version")
# Write INEP in conf\inep file
def writeInepConf(inep):
inepConfFile = file(PROINFODATAPATH + "\\conf\\inep", "w")
inepConfFile.write(inep)
inepConfFile.close()
# Write Version in conf\version file
def writeVersionConf(version):
versionConfFile = file(PROINFODATAPATH + "\\conf\\version", "w")
versionConfFile.write(version)
versionConfFile.close()
# Call client.exe returning the returncode and the output
def callClient(args):
clientPath = "\"" + PROINFODATAPATH + "\\bin\\client.exe" + "\""
proc = subprocess.Popen(clientPath + args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
out = proc.communicate()
return (proc.returncode, out)
# Check for updates
def verifyUpdate():
args = " --update --url=" + URL
(phost, pport, puser, ppass) = getProxyInfo()
if phost != "":
args += " --phost=" + phost
if pport != "":
args += " --pport=" + pport
if puser != "" or ppass != "":
args += " --puid=" + puser + " --ppasswd=" + ppass
(returnCode, output) = callClient(args)
if returnCode == 0:
return 0
if returnCode == 4:
updatelink = output[0].split("\n")[0]
return updatelink
else:
raise clientError(returnCode, output)
# Save the old collect-data file
def backupCollectData():
if os.path.exists(PROINFODATAPATH + "\\data\\collect-data.xml"):
date = strftime("%Y%m%d-%I%M%S", localtime())
shutil.copy(PROINFODATAPATH + "\\data\\collect-data.xml",\
PROINFODATAPATH + "\\data\\collect-data" + date + ".xml")
return 0
# Delete old log files
def deleteOldLogs():
logPath = PROINFODATAPATH + "\\log"
today = strftime("%Y%m%d", localtime())
ageLimit = int(today) - LOGLIFETIME
for infile in glob.glob(os.path.join(logPath, '*.log')):
try:
fileDate = int(infile.split("\\")[-1].split(".")[0].strip())
except:
continue
if fileDate <= ageLimit:
os.remove(infile)
# Get proxy information from Windows registry
def getProxyInfo():
phost = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyHost")
pport = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyPort")
puser = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyUser")
ppass = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyPass")
return (phost, pport, puser, ppass)
# Send the collect-data.xml
def sendData():
args = " --inventory --url=" + URL + " --inep=" + inep
(phost, pport, puser, ppass) = getProxyInfo()
if phost != "":
args += " --phost=" + phost
if pport != "":
args += " --pport=" + pport
if puser != "" or ppass != "":
args += " --puid=" + puser + " --ppasswd=" + ppass
(returnCode, output) = callClient(args)
if returnCode != 0:
raise clientError(returnCode, output)
return 0
# Create collect-data.xml file
def writeCollectData(collectData):
collectDataFile = file(PROINFODATAPATH + "\\data\\collect-data.xml", "w")
collectDataFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
collectDataFile.write(tostring(collectData))
collectDataFile.close()
# Download the update package
def downloadUpdate(link):
urllib.urlretrieve(link, PROINFODATAPATH + "\\update\\updatePackage.exe")
# Call the update package
def callUpdater():
updaterPath = "\"" + PROINFODATAPATH + "\\update\\updatePackage.exe" + "\""
args = "/S"
proc = subprocess.Popen(updaterPath + args)
# Wait to be killed
out = proc.communicate()
# ==========================================
# Main program
# ==========================================
# Open the logfile
log = Log()
# Delete old log files
try:
deleteOldLogs()
except:
log.write("WARNING: Failed to delete old log files.")
# Get Version from Windows Registry
try:
version = getVersion()
except:
log.write("ERROR(1): Failed to check Version in Windows registry.")
log.close()
sys.exit(1)
# Get INEP from Windows Registry
try:
inep = collect.getINEP()
except:
log.write("ERROR(2): Failed to check INEP in Windows registry.")
log.close()
sys.exit(2)
# Write inep and version conf files
try:
writeVersionConf(version)
writeInepConf(inep)
except:
log.write("ERROR(3): Cannot write inep or version conf files.")
log.close()
sys.exit(3)
# Check if PROINFODATAPATH\bin\client.exe exists
if not (os.path.exists(PROINFODATAPATH + "\\bin\\client.exe")):
log.write("ERROR(4): client.exe not found.")
log.close()
sys.exit(4)
# Check for updates
try:
updatelink = verifyUpdate()
except clientError, e:
log.write("ERROR(5): Failed to check for updates. Client returned " + str(e.code) + ".")
log.write("Client message: " + str(e.errorMsg))
log.close()
sys.exit(5)
# If update is needed
if(updatelink):
log.write("UPDATE: New update package available.")
# Get remote version
# The update link is in the format: "http://url/proinfodata-windows_x.x.x.exe
# where x.x.x is the remote version
newVersion = updatelink.split("_")[-1].replace(".exe", "")
log.write("UPDATE: Updating from " + version + " to " + newVersion.strip() + ".")
try:
downloadUpdate(updatelink)
except:
log.write("ERROR(6): Failed to dowload update package.")
log.close()
sys.exit(6)
# The update package will be an NSIS installer. This installer will kill
# this process to overwrite the files. After that, the installer will call
# this process again (now updated)
try:
log.write("UPDATE: Stopping for update process.")
log.flush()
callUpdater()
except:
log.write("ERROR(7): Failed to call the updater.")
log.close()
sys.exit(7)
else:
log.write("UPDATE: No updates are available.")
# Collect data
try:
collectData = collect.collect()
except:
log.write("ERROR(8): Failed to collect data.")
log.close()
sys.exit(8)
# Write the collect-data.xml file
try:
writeCollectData(collectData)
except:
log.write("ERROR(9): Failed to write collect-data.xml.")
log.close()
sys.exit(9)
# Send data
try:
sendData()
except clientError, e:
log.write("ERROR(10): Failed to send data. Client returned " + str(e.code) + ".")
log.write("Client message: " + str(e.errorMsg))
log.close()
sys.exit(10)
except:
log.write("ERROR(11): Failed to get the proxy information from Windows registry.")
log.close()
sys.exit(11)
# If everything ran ok, exit with success status
log.write("EXIT(0): Success.")
log.close()
sys.exit(0)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment