def callDevices(self): Log("Calling devices...") for port in self.ports: errorIndication, errorStatus, errorIndex, self.varBinds = self.cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((self.ip, port)), O_ID, O_DESCR, O_FPORTS, O_UPORTS, O_NETUP, O_NETDOWN, O_FANSPEED, O_VOLTAGE, O_TEMP, O_BANDLOAD, lookupNames=True, lookupValues=True) if errorIndication: print "Calling device error:"+port #logging.warning("Call device error. Port:" + port) Log("Call device error. Port:" + port,1) #raise Exception("Call device error.Port "+port) elif errorStatus: #print (errorStatus,port),"Call device Error." #raise Exception("Error occured: port-"+port+" status-"+errorStatus) Log("Error occured: port-"+port+" status-"+errorStatus,1) else: self.devices.append(self.varBinds) Log("Finished") self.makeXml()
def printToFile(self): Log("Printing data to file(data/device_info.txt...") output = open("data/device_info.txt",'r+') for dev in self.devices: for name,val in dev: output.write(str(name) + '\n' + str(val) + '\n' ) output.write('\n--------------\n') Log("Finished.")
def getDevicePorts(self): Log("Getting device ports...") infile = open('src/devices.txt','r') data = infile.readline() ports = [] ports = re.findall('\d+',data) self.ports = ports Log("Finished.")
def printInventory(self): Log("Printing inventory data...") ftp = FTP(self.ip) ftp.login() invent_file = open("inventory.txt",'wb') ftp.retrbinary('RETR inventory.txt',invent_file.write,8*1024) invent_file.close() with open("inventory.txt",'r') as f: for line in f: print line.rstrip() Log("Finished.")
def printDataForDevice(self,info_type,device_id): dic = self.getDictionary() errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((self.ip, device_id)), dic[info_type], lookupNames=True, lookupValues=True) if errorIndication: raise Exception("Call device error.Port "+port) Log("Call device error. Port:" + port,1) elif errorStatus: raise Exception("Error occured: port-"+port+" status-"+errorStatus) Log("Call device error. Port:" + port + "Error status:" + errorStatus,1) else: self.printVarBinds(varBinds,0)
def __init__(self,_ip): cm = ConfigManager() Log("Network manager started") self.ip = cm.getSnmpIp() self.ports = () self.cmdGen = cmdgen.CommandGenerator() self.devices = [] self.inventory = [] self.getDevicePorts() self.callDevices()
import smtplib from XmlManager import XmlManager from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from LogManager import Log #### Initializations #### # Initializing logging logger = Log.initialize('MailManager') def send(message, status): SMTP_HOST = XmlManager.primaryConfig["smtpHost"] SMTP_PORT = XmlManager.primaryConfig["smtpPort"] DEBUG_STATUS = False SENDER = XmlManager.primaryConfig["JarvisEmail"] RECEIVER = XmlManager.primaryConfig["PrimaryCustEmail"] PASSWORD = XmlManager.primaryConfig["JarvisPasscode"] SUBJECT = XmlManager.primaryConfig["NotificationEmailSubject"] try: # creates SMTP session s = smtplib.SMTP(SMTP_HOST, SMTP_PORT) # start TLS for security s.starttls() s.ehlo() # Switch to enable / disable debugging s.set_debuglevel(DEBUG_STATUS) # Authentication s.login(SENDER, PASSWORD) msg = MIMEMultipart('alternative')
from string import ascii_uppercase from XmlManager import XmlManager from datetime import datetime import MailManager as mail import os import shutil import sys from LogManager import Log #### Initializations #### # Initializing logging logger = Log.initialize('DriveManager') path_seperator = "\\" def get_usb_drive(identifier_file_name): platform_name = get_platform() if platform_name is not "Windows": path_seperator = "/" for drive in ascii_uppercase: fullpath = drive + ":\\" + identifier_file_name if os.path.exists(fullpath): return drive + ":\\" return "" def getFreeSpaceOnBackupDrive(driveLetter): abc = shutil.disk_usage(driveLetter) return abc.free
def makeXml(self): Log("Start making xml...") devices = [] xmlFile = open('data/xml/device_info.xml','w') out = open('data/out','r+') for dev in self.devices: for name,val in dev: out.write(str(val)+'&&') out.write('\n') out.close() xml = etree.Element('xml') performanceData = [] with open('data/out','r') as infile: for line in infile: performanceData = line.split('&&') root = etree.Element("Device") devId = etree.Element("Id") devId.text = performanceData[0] root.append(devId) sysDescr = etree.Element(SYSDESCR) sysDescr.text = performanceData[1] root.append(sysDescr) self.inventory.append(performanceData[1]) freePorts = etree.Element(FREEPORTS) freePorts.text = performanceData[2] root.append(freePorts) usedPorts = etree.Element(USEDPORTS) usedPorts.text = performanceData[3] root.append(usedPorts) netUp = etree.Element(NETUP) netUp.text = performanceData[4] root.append(netUp) netDown = etree.Element(NETDOWN) netDown.text = performanceData[5] root.append(netDown) fanSpeed = etree.Element(FANSPEED) fanSpeed.text = performanceData[6] root.append(fanSpeed) voltage = etree.Element(VOLTAGE) voltage.text = performanceData[7] root.append(voltage) temp = etree.Element(TEMP) temp.text = performanceData[8] root.append(temp) bandLoad = etree.Element(BANDLOAD) bandLoad.text = performanceData[9] root.append(bandLoad) xml.append(root) xmlFile.write(etree.tostring(xml,pretty_print=True)) Log("Finished.")
# Handling imports import DriveManager as dm # Takes care of drive in which backup is supposed to written import BackupDataManager as bdm # Takes care of data which is supposed to be backed up from XmlManager import XmlManager import MailManager as mail from LogManager import Log #### Initializations #### # Initializing Xml configuration management XmlManager.primaryConfig = XmlManager.MainConfig() XmlManager.paths = XmlManager.PathManager() # Initializing logging logger = Log.initialize('BackupEngine') #### Initializations #### # Getting Identified filename logger.debug("Fetching the name of the identifier file name from xml configuration") identifier_file_name=XmlManager.primaryConfig["IdentifierFile"] logger.debug("Fetched the name of the identifier file name from xml configuration") # Checking all drives for identifier file logger.debug("Checking all drives for identifier file") drive = dm.get_usb_drive(identifier_file_name) if drive!="": # Backup drive successfully connected / Identifier file found logger.info("Backup drive successfully connected") logger.debug("Checking free space in backup drive") # Checking the free space available on the backup drive in bytes free_space_backup_drive = dm.getFreeSpaceOnBackupDrive(drive)
def MainConfig(cls): logger.info("Initializing Xml configuration") try: configurationDetails = ET.parse( 'configuration.xml' ) #This file may not exist, introduce fatal error except Exception as err: logger.critical("Cannot parse configuration.xml") ConfigDict = {} if configurationDetails is not None: #Checking the log level logger.info("configuration.xml parsed successfully") ConfigDict["loggingLevel"] = configurationDetails.find( 'loggingLevel').text if ConfigDict["loggingLevel"] != "DEBUG": level = Log.getLogLevel(ConfigDict["loggingLevel"]) Log.loggingLevel = level logger.setLevel(level) for handler in logger.handlers: handler.setLevel(level) # Check if Email notifications are Enabled ConfigDict["EmailNotifications"] = configurationDetails.find( 'EmailNotifications').text ConfigDict["JarvisEmail"] = configurationDetails.find( 'JarvisEmail').text encPassword = configurationDetails.find('JarvisPasscode').text ConfigDict["JarvisPasscode"] = encPassword # Performing the Password decryption only if Email notifications are enabled if ConfigDict["EmailNotifications"] == 'Enabled': logger.debug("Performing the Password decryption") key = Crypt.loadKeyFile() if key is not "KO": logger.debug("Password decryption key is found") c = Crypt() decPassword = c.decrypt(encPassword.strip(), key) if decPassword != "": ConfigDict["JarvisPasscode"] = decPassword else: logger.critical("Error decrypting password" ) # Raise Fatal Error here else: logger.critical( "Error fetching key") # Raise Fatal Error here ConfigDict["PrimaryCustEmail"] = configurationDetails.find( 'PrimaryCustEmail').text ConfigDict["smtpHost"] = configurationDetails.find('smtpHost').text ConfigDict["smtpPort"] = configurationDetails.find('smtpPort').text ConfigDict["IdentifierFile"] = configurationDetails.find( 'IdentifierFile').text ConfigDict["BackupDirName"] = configurationDetails.find( 'BackupDirName').text ConfigDict["CheckedPathsFileName"] = configurationDetails.find( 'CheckedPathsFileName').text ConfigDict["BackupSummaryFileName"] = configurationDetails.find( 'BackupSummaryFileName').text ConfigDict["NotificationEmailSubject"] = configurationDetails.find( 'NotificationEmailSubject').text logger.info("Finished reading configuration.xml") return ConfigDict
import xml.etree.ElementTree as ET from Crypt import Crypt from LogManager import Log #### Initializations #### # Initializing logging logger = Log.initialize('XmlManager') class XmlManager: @classmethod def MainConfig(cls): logger.info("Initializing Xml configuration") try: configurationDetails = ET.parse( 'configuration.xml' ) #This file may not exist, introduce fatal error except Exception as err: logger.critical("Cannot parse configuration.xml") ConfigDict = {} if configurationDetails is not None: #Checking the log level logger.info("configuration.xml parsed successfully") ConfigDict["loggingLevel"] = configurationDetails.find( 'loggingLevel').text if ConfigDict["loggingLevel"] != "DEBUG": level = Log.getLogLevel(ConfigDict["loggingLevel"]) Log.loggingLevel = level logger.setLevel(level) for handler in logger.handlers: handler.setLevel(level)
import os from XmlManager import XmlManager import MailManager as mail from LogManager import Log #### Initializations #### # Initializing logging logger = Log.initialize('BackupDataManager') # Include a check for timeout and directory tree size depth for huge folders def get_size(start_path): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) # skip if it is symbolic link if not os.path.islink(fp): total_size += os.path.getsize(fp) return total_size def write_to_text_file(filename, data): try: handle = open(filename, "a+") handle.write(data) except FileNotFoundError: logger.error("File " + filename + " not found") if XmlManager.primaryConfig["EmailNotifications"] == "Enabled": # Email sending is enabled, send email