Advertisement
AceScottie

Logger,py

Dec 12th, 2019
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.18 KB | None | 0 0
  1. import os, sys, socket, threading, traceback, time, smtplib, ssl, psutil, ctypes, configparser
  2. from email.mime.application import MIMEApplication
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.text import MIMEText
  5. from email.utils import COMMASPACE, formatdate
  6. if os.name == 'nt':
  7.     import win32api, win32con
  8.     pass
  9. if getattr(sys, 'frozen', False):
  10.     exe_path = os.path.dirname(sys.executable)
  11. elif __file__:
  12.     exe_path = os.path.dirname(os.path.abspath(__file__))
  13.     pass
  14.  
  15. ##For testing:
  16. import socket, traceback, os, sys, time
  17. class Socket_Log():
  18.     def __inti__(self):
  19.         self.sock = None
  20.         create_socket()
  21.     def log(self, log):
  22.         try:
  23.             self.sock.sendall(str("log: %s, %s\r" %(strtime, log)).encode())
  24.         except:
  25.             self.create_socket()
  26.     def error(self, error):
  27.         try:
  28.             exc_type, exc_obj, exc_tb = sys.exc_info()
  29.             trace_stack = traceback.extract_tb(exc_tb)[-1]
  30.             trace_format = "Error in file "+str(trace_stack[0])+"\r     on line "+str(trace_stack[1])+", from module '"+str(trace_stack[2])+"'\r        "+str(trace_stack[3])
  31.             strtime = str(time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
  32.             self.sock.sendall(str("error: %s, %s, %s\r" %(strtime, error, trace_format)).encode())
  33.         except:
  34.             self.create_socket()
  35.     def create_socket(self):
  36.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  37.         self.sock.connect((socket.gethostname(), 6085))
  38.     def quitter(self):
  39.         self.sock.sendall(b'exit')
  40.  
  41. ##Add the above code to any program.
  42.  
  43. ##Initilise the logger functions:
  44. ##imports
  45. import time as pytime #fix so can use datetime time alongside
  46. import sys, traceback, os, subprocess, tempfile, psutil
  47. if os.name == 'nt': #windows fix
  48.     import win32api, win32con
  49.     pass
  50. if getattr(sys, 'frozen', False): #windows path fix
  51.     #os.chdir(sys._MEIPASS)
  52.     exe_path = os.path.dirname(sys.executable)
  53. elif __file__:
  54.     exe_path = os.path.dirname(os.path.abspath(__file__))
  55.     pass
  56. tmp = tempfile.mkdtemp()
  57. ##Proc Required:
  58. proc = [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if str(os.getpid()) in str(p.info['pid'])][0]
  59. proc = proc['name']
  60.  
  61. ##Initilise:
  62. print("%s\\logger\\Logger.exe, '%s', '%s'" %(exe_path, tmp, proc))
  63. subprocess.Popen(['%s\\logger\\Logger.exe' %(exe_path), tmp, proc])
  64. pytime.sleep(2)
  65. logger = Socket_Log()
  66.  
  67. ##use try/excoet Casees
  68. try:
  69.     #some code
  70. except Exception as err:
  71.     exc_type, exc_obj, exc_tb = sys.exc_info()
  72.     logger.error("MyFunction failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, traceback.print_tb(exc_tb)))
  73.  
  74. class socket_logger:
  75.     def __init__(self, tmp, proc):
  76.         self.proc = proc
  77.         self.log = []
  78.         self.tmpdir = tmp
  79.         self.file = "debug.log"
  80.         self.endstate = False
  81.         self.quit = False
  82.         self.error_state = False
  83.         self.config = {}
  84.     def read_config(self):
  85.         config = configparser.ConfigParser()
  86.         config.read(exe_path+'\\logger.ini')
  87.         details = {}
  88.         for key, value in config['EMAIL'].items():
  89.             print(key, value)
  90.             details[key] = value
  91.         return details
  92.     def starter(self):
  93.         self.config = self.read_config()
  94.         t=threading.Thread(target=self.app_run)
  95.         t.start()
  96.         time.sleep(1)
  97.         socket.setdefaulttimeout(5)
  98.         serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  99.         serversocket.bind((socket.gethostname(), 6085))
  100.         serversocket.listen(1)
  101.         while not self.quit:
  102.             try:
  103.                 clientsocket, address = serversocket.accept()
  104.                 break
  105.             except:
  106.                 pass
  107.         while not self.quit:
  108.             while not self.quit:
  109.                 try:
  110.                     data = clientsocket.recv(65565)
  111.                     break
  112.                 except:
  113.                     pass
  114.             if data == b'':
  115.                 try:
  116.                     clientsocket.send(b"t", timeout=1)
  117.                 except:
  118.                     clientsocket, address = serversocket.accept()
  119.             elif data == b'exit':
  120.                 self.endstate = True
  121.                 self.quit = True
  122.             else:
  123.                 if type(data) != type("str"):
  124.                     data = data.decode()
  125.                 if data[0:3] == "Log":
  126.                     self.log_input(data)
  127.                 elif data[0:5] == "Error":
  128.                     self.error_state = True
  129.                     self.log_input(data)
  130.         if self.endstate == False:
  131.             self.log_input("Program exited without sending quit.")
  132.             estate = ctypes.windll.user32.MessageBoxW(None, 'The Application closed unexpectedly.\nWould you like to send a log?', 'App Error',  1)
  133.             if estate == 1:
  134.                 with open(self.tmpdir+self.file, "w+") as f:
  135.                     f.write("\r\n".join(self.log))
  136.                 self.send_mail(self.tmpdir+self.file)
  137.                 os.remove(self.tmpdir+self.file)
  138.         elif self.error_state == True:
  139.             self.log_input("Program exited but errors detected")
  140.             try:
  141.                 clientsocket.close()
  142.             except:
  143.                 pass
  144.             estate = ctypes.windll.user32.MessageBoxW(None, 'Some Errors were detected.\nWould you like to send a log?', 'App Error',  1)
  145.             if estate == 1:
  146.                 with open(self.tmpdir+self.file, "w+") as f:
  147.                     f.write("\r\n".join(self.log))
  148.                 self.send_mail(self.tmpdir+self.file)
  149.                 os.remove(self.tmpdir+self.file)
  150.         else:
  151.             try:
  152.                 clientsocket.close()
  153.             except:
  154.                 pass
  155.     def app_run(self):
  156.         while not self.quit:
  157.             try:
  158.                 [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if self.proc in p.info['name']][0]
  159.             except:
  160.                 self.quit = True
  161.                 break
  162.             time.sleep(1)
  163.     def log_input(self, text):
  164.         self.log.append(text)
  165.         pass
  166.     def send_mail(self, file, server="smtp.live.com", server_port=587):
  167.         msg = MIMEMultipart()
  168.         msg['From'] = self.config['from']
  169.         msg['To'] = self.config['to']
  170.         msg['Subject'] = "Debug Log"
  171.         msg.attach(MIMEText("System Debug Log"))
  172.         with open(file, "rb") as fil:
  173.             part = MIMEApplication(fil.read(), Name=os.path.basename(file))
  174.         part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(file)
  175.         msg.attach(part)
  176.         smtp = smtplib.SMTP(server, server_port)
  177.         smtp.ehlo()
  178.         smtp.starttls()
  179.         smtp.ehlo()
  180.         smtp.login(self.config['from'], self.config['pass'])
  181.         smtp.set_debuglevel(True)
  182.         smtp.sendmail(msg['From'], msg['To'], msg.as_string())
  183.         smtp.quit()
  184. if __name__ == "__main__":
  185.     try:
  186.         if len(sys.argv) == 3:
  187.             logger = socket_logger(sys.argv[1], sys.argv[2])
  188.             logger.starter()
  189.         else:
  190.             ctypes.windll.user32.MessageBoxW(None, 'The Log failed to initilise.\nFailed to create with system arguments: 1001.\nPlease Contact your Administrator', 'Logger Error',  0)
  191.     except:
  192.         raise
  193.  
  194.  
  195. ##Required logger.ini:
  196. [EMAIL]
  197. to = some_email
  198. from = hotmail_email
  199. pass = hotmail_password
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement