Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pexpect
- import string
- import datetime
- import MySQLdb
- from pexpect import pxssh
- import time
- import datetime
- import threading
- from threading import Timer
- import warnings
- import re
- import logging
- import signal
- import sys
- #set up the logger
- #set up object to access the database
- db = MySQLdb.connect("localhost","root","","CPUmonitor")
- print(db)
- cursor = db.cursor()
- startTime = time.time()
- #delay between
- refreshRate = 3
- class sshSession(object):
- def __init__(self,cardName,ip,username,password):
- self.cardName = cardName
- self.ip = ip
- self.username = username
- self.password = password
- self.handler = pxssh.pxssh() #create ssh handler
- self._processDict = {}#{'process_name':column_index}
- #create a new table in the database
- sql = "DROP TABLE IF EXISTS "+self.cardName+";"
- #sql = """CREATE TABLE """+self.cardName+""" (time TIMESTAMP) IF NOT EXISTS """+self.cardName
- cursor.execute(sql)
- sql = "CREATE TABLE "+self.cardName+" (time FLOAT);"
- cursor.execute(sql)
- self.running = True
- def login(self): #logs in using the ssh handler created in __init__
- self.handler.login(self.ip,self.username,self.password)
- print('logged in to '+self.cardName)
- def logout(self):
- self.handler.logout()
- def ping(self):
- print("pinging")
- self.running = False #stops execution of dataloop
- #self.handler.logout()
- self.handler.sendline('ping '+self.ip) #ping with a very long timeout
- self.handler.prompt(timeout=-1) #expect the prompt with no timeout
- print("card responded")
- #executes this code if prompt found
- #self.login() #login
- self.running = True
- def dataLoop(self):
- if(self.running):
- self.refreshData()
- time.sleep(refreshRate)
- self.dataLoop()
- def refreshData(self): #read the output of top command
- #change to top -d 1 -n 3 | awk '{ print $10","$13 }'
- command = "top -d 1 -n "+str(refreshRate)+" | awk \'{ print $10 \" \" $13 }\'"
- self.handler.sendline(command)
- successful = self.handler.prompt(timeout=30)
- if(not successful):
- print(self.cardName+" timed out!!!!")
- self.ping()
- output = self.handler.before
- newOutput = output.strip()
- #print(newOutput)
- #print(repr(newOutput))
- index = newOutput.rfind("\r\n \r\n")
- #print(index)
- newOutput = newOutput[index+5:]
- newOutput = newOutput.replace('\\x','')
- lines = newOutput.split('\r\n')
- data_to_be_inserted = [0]*(len(self._processDict)+1) #will become the row inserted into the db
- data_to_be_inserted[0] = time.time()-startTime
- for line in lines:
- delimiter = line.find(' ')
- CPU = line[:delimiter]
- process = line[delimiter+1:]
- invalid_characters = ['.','\x1b','/','-','+',':',';','*','[',']']
- for character in invalid_characters:
- process = process.replace(character,'')
- if(process.isdigit()):
- process.append('a')
- if process in self._processDict: #check if the process is already a column in the db
- column_index = self._processDict[process]
- data_to_be_inserted[column_index] = CPU
- else:
- column_index = len(self._processDict)+1
- self._processDict[process] = column_index
- data_to_be_inserted.append(CPU)
- #add a new column to the database with label of process
- sql = "ALTER TABLE "+self.cardName+" ADD "+process+" FLOAT DEFAULT 0;"
- cursor.execute(sql)
- #put the data into the database
- data_to_be_inserted = tuple(data_to_be_inserted)
- #print(data_to_be_inserted)
- sql = "INSERT INTO "+self.cardName+" VALUES "+str(data_to_be_inserted)
- #print(sql)
- cursor.execute(sql)
- #open and read the config file
- config = open('config.txt','r')
- lines = config.readlines()
- config.close()
- #concatenate array into one long string
- text = ''.join(lines)
- #search for all matches to pattern
- regex = '(\S+)\n\s+IP: (\S+)\n\s+USER: (\S+)\n\s+PASSWORD: (\S+)'
- regex = re.compile(regex)
- matches = re.findall(regex,text)
- #use matches to create spawn and login children (ssh objects) and add them to the list of children
- childList = []
- for match in matches:
- name,ip,user,password = match
- #print(name)
- temp = sshSession(name,ip,user,password)
- temp.login()
- childList.append(temp)
- print('doing something')
- #def thread(child):
- # child.refreshData()
- # time.sleep(refreshRate)
- # thread(child)
- threadList = []
- for child in childList:
- #print('before before')
- t = threading.Thread(target=child.dataLoop)
- t.daemon = True
- threadList.append(t)
- #print('before')
- t.start()
- #print('after')
- print('threads started')
- #for child in childList:
- # child.ping()
- # print('trying to ping')
- def signal_handler(signal,frame):
- print('Ctrl-C pressed')
- for child in childList:
- child.logout()
- print('logged out of children')
- sys.exit(0)
- signal.signal(signal.SIGINT, signal_handler)
- print('after signal things')
- signal.pause()
- #for child in childList:
- #child.dataLoop() #start dataloop threads for all children
- #while(True):
- # for child in childList:
- # child.dataLoop() #will start timers in refreshData class that loop back to themselves
- # time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement