Advertisement
Tlams

MYSQL_Connector

Oct 22nd, 2013
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.46 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. #Script d'analyse de log chat JKA
  5.  
  6. import time
  7. import datetime
  8. import ConfigParser
  9. import socket
  10. import hashlib
  11. import threading
  12. import MySQLdb as mdb
  13. import os, sys
  14. from sys import exit
  15. ####
  16.  
  17. def __unicode__(self):
  18.     return unicode(self.name)
  19.  
  20. def strReplace(str, array):
  21.     for search, replace in array:
  22.         str = str.replace(search, replace)
  23.     return str
  24. ###
  25.  
  26.  
  27. #LECTURE LOCAL LOG
  28. class thread_send(threading.Thread):    
  29.     def __init__(self, nom=''):
  30.         threading.Thread.__init__(self)
  31.         self.nom = nom
  32.         self.Terminated = False
  33.        
  34.     def run(self):
  35.         new_back = "none"      
  36.         lastmessage = ""
  37.         new = ""
  38.         pass_starup = 0
  39.         autodebogue = int(0)
  40.         global lastmessage
  41.         global con
  42.         global autodebogue
  43.        
  44.         while True:
  45.             try:
  46.                 with con:
  47.                     sql_request = "SELECT " +  MYSQL_BD_Col_username + "," + MYSQL_BD_Col_Message + " FROM " + MYSQL_TB_NAME + " ORDER BY " + MYSQL_BD_Col_id + " DESC LIMIT 1"
  48.                     cur.execute(sql_request)
  49.                     data = cur.fetchall()
  50.                     for row in data :
  51.                         new = row[1]
  52.             except:
  53.                 print "An error occurred while selecting the message in the database"
  54.                 autodebogue = autodebogue + int(1)
  55.                 print u"Auto-debug [",autodebogue,"/4]"
  56.                 if (autodebogue == 4):
  57.                     print "Automatic debugging!"
  58.                     workingdir = os.getcwd()
  59.                     os.startfile(workingdir + "\JKA_BDD_client.exe")
  60.                     os._exit(1)
  61.                    
  62.             if (pass_starup == 0):
  63.                 new_back = new
  64.                 pass_starup = 1
  65.                
  66.             if ((new != new_back) and (new != "") and (new != lastmessage)):
  67.                 PEERS_COUNT = int(0)  
  68.                 while PEERS_COUNT != len(LIST_SERVER.split(',')):
  69.                     try:
  70.                         PEER = LIST_SERVER.split(',')[PEERS_COUNT]
  71.                         PORT_PEER = PEER.split(':')[1]
  72.                         IP_PEER = PEER.split(':')[0]
  73.                         sock.sendto(USERNAME + "|-|" + hashlib.sha256(PASSWORD).hexdigest() + "|-|" + TAG + "|-|" + str(row[0]) + "|-|" + str(row[1]), (IP_PEER, int(PORT_PEER)))
  74.                     except:
  75.                         print "An error has occurred while the sending"                
  76.                     PEERS_COUNT = PEERS_COUNT + 1                            
  77.                 new_back = new
  78.             time.sleep(0.5)
  79.            
  80.     def stop(self):
  81.         self.Terminated = True
  82.  
  83. #RECEPTION
  84. class thread_recept(threading.Thread):    
  85.     def __init__(self, nom=''):
  86.         threading.Thread.__init__(self)
  87.         self.nom = nom
  88.         self.Terminated = False
  89.        
  90.     def run(self):
  91.         autodebogue = int(0)
  92.         global lastmessage
  93.         global con
  94.         global autodebogue
  95.         while True:
  96.                 data, addr = sock_recu.recvfrom(1024)
  97.                 if addr[0] in AUTORISE_IPS_LIST:
  98.                     try:
  99.                         DATE = int(time.time())
  100.                         SERVERNAME_recv = data.split('|-|')[0]
  101.                         PASSWORD_recv = data.split('|-|')[1]
  102.                         TAG_recv = data.split('|-|')[2]
  103.                         NAME_recv = data.split('|-|')[3]
  104.                         MESSAGE_recv = data.split('|-|')[4]
  105.                         MESSAGE_recv = strReplace(MESSAGE_recv, replace_color_flag)
  106.                         error = False
  107.                     except:
  108.                         print "An error has occurred while processing!"
  109.                         error = True
  110.                        
  111.                     if ((hashlib.sha256(PASSWORD).hexdigest() == PASSWORD_recv) and (error == False)):
  112.                         lastmessage = MESSAGE_recv
  113.                         print u"Received data[",SERVERNAME_recv,"]",NAME_recv,":",MESSAGE_recv
  114.                         if (MYSQL_BD_Col_time_format == "UNIX"):
  115.                             date = int(time.time())
  116.                         else:
  117.                             date = int(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
  118.                            
  119.                         try:
  120.                             with con:
  121.                                 sql_request = "INSERT INTO " + MYSQL_TB_NAME + " (" + MYSQL_BD_Col_username + "," + MYSQL_BD_Col_Message + "," + MYSQL_BD_Col_time + ") VALUES ('[" + mdb.escape_string(SERVERNAME_recv) + "]" + mdb.escape_string(NAME_recv) + "','" + mdb.escape_string(MESSAGE_recv) + "','" + str(date) + "')"
  122.                                 cur.execute(sql_request)                      
  123.                         except:
  124.                             print u"An error occurred while adding the message in the database"
  125.                             autodebogue = autodebogue + int(1)
  126.                             print u"Auto-debug [",autodebogue,"/4]"
  127.                             if (autodebogue == 4):
  128.                                 print "Automatic debugging!"
  129.                                 workingdir = os.getcwd()
  130.                                 os.startfile(workingdir + "\JKA_BDD_client.exe")
  131.                                 os._exit(1)
  132.                                                          
  133.                 else:
  134.                     print u"Unauthorized IP!"              
  135.              
  136.     def stop(self):
  137.         self.Terminated = True
  138.  
  139. print "------------------------"
  140. print "-- Programme de Tlams"
  141. print "-- Version 1.0"
  142. print "-- Date: 28/09/13"
  143. print "-- Langage: Python V2.7"
  144. print u"-- Email: tlams[at]free.fr"
  145. print u"-- Fonction: Script de chat inter-serveur JKA / BDD MOD"
  146. print "------------------------"
  147. print ""
  148.  
  149. time.sleep(1)
  150.  
  151. #LECTURE DU FICHIER DE CONFIGURATION    
  152. print "Opening configurations file...",
  153. try:
  154.     config = ConfigParser.RawConfigParser()
  155.     config.read('config.ini')
  156.     print "[OK]"
  157. except:
  158.     print "[FAILED]"
  159.     print u"Opening the configuration file (config.ini) failed!"
  160.     print "File not available."
  161.     print "Closing..."
  162.     time.sleep(5)
  163.     exit(0)
  164.  
  165. time.sleep(1)
  166.  
  167. #SCRIPT INFO
  168. TAG = "BDD_JKA"
  169.  
  170. #TRAITEMENT DU FICHIER DE CONFIG
  171. print u"Reading the configuration file..."
  172. try:
  173.     MYSQL_BD_Col_Message = config.get('MYSQL', 'MYSQL_BD_Col_Message')
  174.     print u"[Info-config]MYSQL colonne message:",MYSQL_BD_Col_Message
  175.     MYSQL_BD_Col_username = config.get('MYSQL', 'MYSQL_BD_Col_username')
  176.     print u"[Info-config]MYSQL colonne user:",MYSQL_BD_Col_username
  177.     MYSQL_BD_Col_id = config.get('MYSQL', 'MYSQL_BD_Col_id')
  178.     print u"[Info-config]MYSQL colonne ID:",MYSQL_BD_Col_id
  179.     MYSQL_BD_Col_time = config.get('MYSQL', 'MYSQL_BD_Col_time')
  180.     print u"[Info-config]MYSQL colonne time:",MYSQL_BD_Col_time
  181.     MYSQL_BD_Col_time_format = config.get('MYSQL', 'MYSQL_BD_Col_time_format')
  182.     print u"[Info-config]MYSQL colonne time format:",MYSQL_BD_Col_time_format  
  183.     MYSQL_TB_NAME = config.get('MYSQL', 'MYSQL_TB_NAME')
  184.     print u"[Info-config]MYSQL table:",MYSQL_TB_NAME
  185.     MYSQL_BD_NAME = config.get('MYSQL', 'MYSQL_BD_NAME')
  186.     print u"[Info-config]MYSQL database:",MYSQL_BD_NAME
  187.     MYSQL_PASSWORD = config.get('MYSQL', 'MYSQL_PASSWORD')
  188.     MYSQL_USER = config.get('MYSQL', 'MYSQL_USER')
  189.     print u"[Info-config]MYSQL user:",MYSQL_USER
  190.     MYSQL_IP = config.get('MYSQL', 'MYSQL_IP')
  191.     print u"[Info-config]MYSQL serveur IP:",MYSQL_IP
  192.  
  193.     LOCAL_IP = config.get('LOCAL', 'IP')
  194.     print u"[Info-config]Script IP:",LOCAL_IP
  195.     LOCAL_PORT = config.get('LOCAL', 'PORT')
  196.     print u"[Info-config]Script PORT:",LOCAL_PORT
  197.     USERNAME = config.get('LOCAL', 'Username')
  198.     print u"[Info-config]Serveur nom:",USERNAME
  199.     PASSWORD = config.get('LOCAL', 'Password')
  200.     LIST_SERVER = config.get('PEERS', 'List_servers')
  201.     print u"[Info-config]Liste PEERS:",LIST_SERVER
  202.     AUTORISE_IPS = config.get('PEERS', 'IP_Autorise')
  203.     print u"[Info-config]IP autorisés:",AUTORISE_IPS
  204.  
  205.    
  206. except:
  207.     print "[FAILED]"
  208.     print "File is corrupt or the data are invalid !"
  209.     print "Closing..."
  210.     time.sleep(5)
  211.     exit(0)
  212.  
  213. print ""
  214.  
  215. time.sleep(1)
  216.  
  217. # CREATION DU TABLEAU IP AUTORISES
  218. AUTORISE_IPS_LIST = []
  219. nb_ips = int(0)
  220.  
  221. while nb_ips != len(AUTORISE_IPS.split(',')):
  222.     AUTORISE_IPS_LIST.append(AUTORISE_IPS.split(',')[nb_ips])
  223.     nb_ips = nb_ips + 1
  224.  
  225. #PREPARATION SOCKET UDP
  226. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  227. sock_recu = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  228.  
  229.  
  230. #CONNEXION MYSQL
  231. try:
  232.     global con
  233.     print u"Database connection...",
  234.     con = mdb.connect(MYSQL_IP, MYSQL_USER, MYSQL_PASSWORD, MYSQL_BD_NAME)
  235.     print "[OK]"
  236. except:
  237.     print "Connection Error !"
  238.     print "Closing..."
  239.     time.sleep(5)
  240.     exit(0)
  241.    
  242. cur = con.cursor()
  243.  
  244.  
  245. #CREATION DU SOCK LOCAL
  246. print "Opening a local sock...",
  247. try:
  248.     sock_recu.bind((LOCAL_IP, int(LOCAL_PORT)))
  249.     print "[OK]"
  250. except:  
  251.     print "[FAILED]"
  252.     print u"A socket is already open on this port!"
  253.     print "Closing..."
  254.     time.sleep(5)
  255.     exit(0)
  256.  
  257. #FLAG LIST
  258. replace_color_flag = [('^0', ''), ('^1', ''), ('^2', ''), ('^3', ''), ('^4', ''), ('^5', ''), ('^6', ''), ('^7', ''), ('^8', '')]
  259.  
  260.    
  261. #START THREAD
  262.        
  263. a = thread_send('envoi_donne')
  264. a.start()
  265.  
  266. b = thread_recept('recept_donne')
  267. b.start()
  268.  
  269. print u"Loading completed !"
  270. print ""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement