· 9 years ago · Jun 15, 2017, 05:36 PM
1import pexpect
2import string
3import datetime
4import MySQLdb
5from pexpect import pxssh
6import time
7import datetime
8import threading
9from threading import Timer
10import warnings
11import re
12import logging
13import signal
14import sys
15
16#set up the logger
17#set up object to access the database
18db = MySQLdb.connect("localhost","root","","CPUmonitor")
19print(db)
20cursor = db.cursor()
21startTime = time.time()
22
23#delay between
24refreshRate = 3
25
26class sshSession(object):
27 def __init__(self,cardName,ip,username,password):
28 self.cardName = cardName
29 self.ip = ip
30 self.username = username
31 self.password = password
32 self.handler = pxssh.pxssh() #create ssh handler
33 self._processDict = {}#{'process_name':column_index}
34 #create a new table in the database
35 sql = "DROP TABLE IF EXISTS "+self.cardName+";"
36 #sql = """CREATE TABLE """+self.cardName+""" (time TIMESTAMP) IF NOT EXISTS """+self.cardName
37 cursor.execute(sql)
38 sql = "CREATE TABLE "+self.cardName+" (time FLOAT);"
39 cursor.execute(sql)
40 self.running = True
41
42 def login(self): #logs in using the ssh handler created in __init__
43 self.handler.login(self.ip,self.username,self.password)
44 print('logged in to '+self.cardName)
45
46 def logout(self):
47 self.handler.logout()
48
49 def ping(self):
50 print("pinging")
51 self.running = False #stops execution of dataloop
52 #self.handler.logout()
53 self.handler.sendline('ping '+self.ip) #ping with a very long timeout
54 self.handler.prompt(timeout=-1) #expect the prompt with no timeout
55 print("card responded")
56 #executes this code if prompt found
57 #self.login() #login
58 self.running = True
59
60 def dataLoop(self):
61 if(self.running):
62 self.refreshData()
63 time.sleep(refreshRate)
64 self.dataLoop()
65
66 def refreshData(self): #read the output of top command
67 #change to top -d 1 -n 3 | awk '{ print $10","$13 }'
68 command = "top -d 1 -n "+str(refreshRate)+" | awk \'{ print $10 \" \" $13 }\'"
69 self.handler.sendline(command)
70 successful = self.handler.prompt(timeout=30)
71 if(not successful):
72 print(self.cardName+" timed out!!!!")
73 self.ping()
74
75 output = self.handler.before
76 newOutput = output.strip()
77 #print(newOutput)
78 #print(repr(newOutput))
79 index = newOutput.rfind("\r\n \r\n")
80 #print(index)
81 newOutput = newOutput[index+5:]
82 newOutput = newOutput.replace('\\x','')
83 lines = newOutput.split('\r\n')
84
85 data_to_be_inserted = [0]*(len(self._processDict)+1) #will become the row inserted into the db
86 data_to_be_inserted[0] = time.time()-startTime
87
88 for line in lines:
89 delimiter = line.find(' ')
90 CPU = line[:delimiter]
91 process = line[delimiter+1:]
92 invalid_characters = ['.','\x1b','/','-','+',':',';','*','[',']']
93 for character in invalid_characters:
94 process = process.replace(character,'')
95 if(process.isdigit()):
96 process.append('a')
97 if process in self._processDict: #check if the process is already a column in the db
98 column_index = self._processDict[process]
99 data_to_be_inserted[column_index] = CPU
100 else:
101 column_index = len(self._processDict)+1
102 self._processDict[process] = column_index
103 data_to_be_inserted.append(CPU)
104 #add a new column to the database with label of process
105 sql = "ALTER TABLE "+self.cardName+" ADD "+process+" FLOAT DEFAULT 0;"
106 cursor.execute(sql)
107 #put the data into the database
108 data_to_be_inserted = tuple(data_to_be_inserted)
109 #print(data_to_be_inserted)
110 sql = "INSERT INTO "+self.cardName+" VALUES "+str(data_to_be_inserted)
111 #print(sql)
112 cursor.execute(sql)
113
114#open and read the config file
115config = open('config.txt','r')
116lines = config.readlines()
117config.close()
118#concatenate array into one long string
119text = ''.join(lines)
120#search for all matches to pattern
121regex = '(\S+)\n\s+IP: (\S+)\n\s+USER: (\S+)\n\s+PASSWORD: (\S+)'
122regex = re.compile(regex)
123matches = re.findall(regex,text)
124
125#use matches to create spawn and login children (ssh objects) and add them to the list of children
126childList = []
127for match in matches:
128 name,ip,user,password = match
129 #print(name)
130 temp = sshSession(name,ip,user,password)
131 temp.login()
132 childList.append(temp)
133print('doing something')
134#def thread(child):
135# child.refreshData()
136# time.sleep(refreshRate)
137# thread(child)
138
139threadList = []
140for child in childList:
141 #print('before before')
142 t = threading.Thread(target=child.dataLoop)
143 t.daemon = True
144 threadList.append(t)
145 #print('before')
146 t.start()
147 #print('after')
148
149print('threads started')
150
151#for child in childList:
152# child.ping()
153# print('trying to ping')
154
155def signal_handler(signal,frame):
156 print('Ctrl-C pressed')
157 for child in childList:
158 child.logout()
159 print('logged out of children')
160 sys.exit(0)
161signal.signal(signal.SIGINT, signal_handler)
162print('after signal things')
163signal.pause()
164#for child in childList:
165 #child.dataLoop() #start dataloop threads for all children
166
167#while(True):
168# for child in childList:
169# child.dataLoop() #will start timers in refreshData class that loop back to themselves
170# time.sleep(1)