Foro de elhacker.net

Programación => Scripting => Mensaje iniciado por: zagk en 29 Junio 2017, 22:46 pm



Título: Problema con python, multi-hilos y mysql
Publicado por: zagk en 29 Junio 2017, 22:46 pm
Hola a todos, la verdad es que estoy iniciando con MySQL, Python y ,más importante, estoy aún novato con la programación multi-hilos en python, tengo un gran problema que no sé cual es el error, he visto la descripción de los errores que genera python y a veces me suelta un error que me dice que se ha perdido la conexión, supongo que será porque hago muchas peticiones; y a veces me salta otro error que dice algo como que no pudo analizar la información de la tabla.

Aquí les dejo una foto de los 2 errores que me da el script:
http://imgur.com/a/OPhpF

Intenté solucionar lo anterior buscando a ver como se podía hacer que MySQL trabajara con distintos puertos, para asignarle a cada hilo un puerto pero no he conseguido nada.

De todas formas aquí les dejo el código, solo vean el contexto de como aplico el procesamiento multi-hilo, si pueden entenderlo, mejor, así me dicen en qué me equivoco. Por cierto, he verificado que todo está bien: los nombres de los campos y tablas coinciden correctamente, así que por ese lado no ocurre algún error.

Antiguamente cuando no utilizaba el multi-hilos (que tenía el código con menos funciones) todo iba a la perfección, los problemas llegaron con eso y supongo que estoy haciendo varias cosas mal de las que no me doy cuenta. Aquí se los dejo:

Código
  1. # -*- coding: utf-8 -*-
  2.  
  3. import threading
  4. import mysql.connector
  5. import win32con
  6. import sys, os
  7. import struct
  8. import time
  9. from win32api import *
  10. from win32gui import *
  11. from mysql.connector import Error
  12. from threading import Thread
  13.  
  14. cnx = mysql.connector.connect(host="localhost",
  15.                              user="root",
  16.                              password="1234",
  17.                              database="gammu")
  18. cnx2 = mysql.connector.connect(host="localhost",
  19.                              user="root",
  20.                              password="1234",
  21.                              database="gammu")
  22. cnx3 = mysql.connector.connect(host="localhost",
  23.                              user="root",
  24.                              password="1234",
  25.                              database="gammu")
  26.  
  27. cursor = cnx.cursor()
  28. cursor2 = cnx.cursor()
  29. cursor3 = cnx.cursor()
  30.  
  31. global errKey
  32. global errHash
  33.  
  34. class WindowsBalloonTip:
  35.    def __init__(self, title, msg):
  36.        message_map= {
  37.            win32con.WM_DESTROY: self.OnDestroy,
  38.        }
  39.  
  40.        wc = WNDCLASS()
  41.        hinst = wc.hInstance = GetModuleHandle(None)
  42.        wc.lpszClassName = "NotificationTaskR"
  43.        wc.lpfnWndProc = message_map
  44.        classAtom = RegisterClass(wc)
  45.  
  46.        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
  47.        self.hwnd = CreateWindow(classAtom, "Taskbar", style, 0, 0, \
  48.                                 wind32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
  49.                                 0, 0, hinst, None)
  50.        UpdateWindw(self.hwnd)
  51.        iconPathName = os.path.abspath(os.path.join(sys.path[0], 'balloontip.ico'))
  52.        icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
  53.        try:
  54.            hicon = LoadImage(hinst, iconPathName, win32con.IMAGE_ICON, 0,0, icon_flags)
  55.        except:
  56.            hicon = LoadIcon(0, win32con.IDI_APPLICATION)
  57.        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
  58.        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "New message received")
  59.        Shell_NotifyIcon(NIM_ADD, nid)
  60.        Shell_NotifyIcon(NIM_MODIFY, (self.hwnd, 0, NIF_INFO, win32con.WIM_USER+20, \
  61.                                      hicon, "Balloon tooltip", msg, 200, title))
  62.  
  63.        time.sleep(3)
  64.        DestroyWindow(self.hwnd)
  65.        classAtom = UnregisterClass(classAtom, hinst)
  66.    def OnDestroy(self, hwnd, msg, wparam, lparam):
  67.        nid = (self.hwnd, 0)
  68.        Shell_NotifyIcon(NIM_DELETE, nid)
  69.        PostQuitMessage(0)
  70.  
  71. def balloon_tip(title, msg):
  72.    w = WindowsBalloonTip(title, msg)
  73.  
  74. def newWh():
  75.    while True:
  76.        cnx.connect()
  77.        lastRquery = ("select UpdatedInDB, AES_DECRYPT(TextDecoded, (select AES_DECRYPT(cryptkey, '373630303a3a3') from decryptkey)), "
  78.                      "AES_DECRYPT(SenderNumber, (select AES_DECRYPT(cryptkey, '373630303a3a3') from decryptkey)), ID from inboxencrypt where "
  79.                      "chck=0 order by UpdatedInDB asc limit 1")
  80.        cursor.execute(lastRquery)
  81.        regL = cursor.fetchall()
  82.        if not regL:
  83.            cnx.close()
  84.            import time
  85.            time.sleep(3)
  86.            continue
  87.        else:
  88.            for row in regL:
  89.                time = row[0]
  90.                timeC = str(time)
  91.                timeO = timeC[10:]
  92.                message = row[1]
  93.                telephone = row[2]
  94.                toUR = row[3]
  95.                lengM = len(message)
  96.            smsDetect = message[27:]
  97.            procMR = message.split()
  98.            if procMR[0] == "\send":
  99.                #Detect first command
  100.                cnx.close()
  101.                cnx.connect()
  102.                queryAuth = ("SELECT privkey FROM transferauth WHERE "
  103.                             "privkey=sha(%s)", procMR[1])
  104.                cursor.execute(queryAuth)
  105.                authStorage = cursor.fetchall()
  106.                for row in authStorage:
  107.                    key = authStorage[0]
  108.                if procMR[1] == key:
  109.                    #Detect authentication key
  110.                    if procMR[2] == "\a":
  111.                        #Detect command to send multiple messages to all contact list
  112.                        print("Ok")
  113.                    elif len(procMR[2]) == 13:
  114.                        #Send message to specific contact
  115.                        if telpComm[0] == "+" and telpComm [1:3] == "58":
  116.                            #Verifying international code
  117.                            telpComm == procMR[2]
  118.                            if len(smsDetect) > 3:
  119.                                #Verifying minimum message length
  120.                                if smsDetect[-1] == '"' and smsDetect[0] == '"':
  121.                                    #Verifying message format and sending message
  122.                                    msgToSend = smsDetetct[1:-1]
  123.                                    cnx.close()
  124.                                    cnx.connect()
  125.                                    sendQuerExt = ("insert into outbox(DestinationNumber, "
  126.                                                   "TextDecoded, CreatorID) values "
  127.                                                   "('%s','%s','PwC')" % (telpComm, msgToSend))
  128.                                    cursor.execute(sendQuerExt)
  129.                                    cnx.commit()
  130.                                    cnx.close()
  131.                                    #Reconnecting to database and ipdating message status
  132.                                    cnx.connect()
  133.                                    updateRquery = ("update inbox set chck=1 where "
  134.                                                    "ID=%s" % toUR)
  135.                                    cursor.execute(updateRquery)
  136.                                    cnx.commit()
  137.                                    cnx.close()
  138.                                    #Wait for re-establish loop
  139.                                    import time
  140.                                    time.sleep(3)
  141.                                    print("~~~Send message is required for: "+telephone)
  142.                                    print("~~~Send message in required for: "+telpComm+"\n\n")
  143.                                    continue
  144.                                else:
  145.                                    #Invalid message format => ERR_FORMATSMS_INVALID
  146.                                    cnx.connect()
  147.                                    srcErrorSource = ("select errordesc, hexcode from transfererrors "
  148.                                                      "where cause='ERR_FORMATSMS_INVALID'")
  149.                                    cursor.execute(srcErrorSource)
  150.                                    errStorageA = cursor.fetchall()
  151.                                    for row in errStorageA:
  152.                                        errKey = row[0]
  153.                                        errHash = row[1]
  154.                                        cnx.close()
  155.                                    cnx.connect()
  156.                                    recQueryErrorNumb = ("insert into outbox(Text, DestinationNumber, "
  157.                                                         "TextDecoded, CreatorID) values "
  158.                                                         "('%s','%s','%s','PwC')" % (errHash, telephone, errKey))
  159.                                    cursor.execute(recQueryErrorNumb)
  160.                                    cnx.commit()
  161.                                    cnx.close()
  162.                                    #Reconnecting to database and updating message status
  163.                                    cnx.connect()
  164.                                    updateRquery = ("update inbox set chck=1 where "
  165.                                                    "ID=%s" % toUR)
  166.                                    cursor.execute(updateRquery)
  167.                                    cnx.commit()
  168.                                    cnx.close()
  169.                                    #Wait for re-establish loop
  170.                                    import time
  171.                                    time.sleep(3)
  172.                                    continue
  173.                            else:
  174.                                #Minimum message length required => ERR_LENGTHSMS_INVALID
  175.                                srcErrorSource = ("select errordesc, hexcode from transferrors "
  176.                                                      "where cause='ERR_LENGTH_INVALID'")
  177.                                cursor.execute(srcErrorSource)
  178.                                errStorageA = cursor.fetchall()
  179.                                for row in errStorageA:
  180.                                    errKey = row[0]
  181.                                    errHash = row[1]
  182.                                    cnx.close()
  183.                                cnx.connect()
  184.                                recQueryErrorNumb = ("insert into outbox(Text, DestinationNumber, "
  185.                                                         "TextDecoded, CreatorID) values "
  186.                                                         "('%s','%s','%s','PwC')" % (errHash, telephone, errKey))
  187.                                cursor.execute(recQueryErrorNumb)
  188.                                cnx.commit()
  189.                                cnx.close()
  190.                                #Reconnecting to database and updating message status
  191.                                cnx.connect()
  192.                                updateRquery = ("update inbox set chck=1 where "
  193.                                                    "ID=%s" % toUR)
  194.                                cursor.execute(updateRquery)
  195.                                cnx.commit()
  196.                                cnx.close()
  197.                                #Wait for re-establish loop
  198.                                import time
  199.                                time.sleep(3)
  200.                                continue
  201.                        else:
  202.                            #Wrong international telephone format => ERR_FORMATNUMBER_INVALID
  203.                            srcErrorSource = ("select errordesc, hexcode from transfererrors "
  204.                                              "where cause='ERR_FORMATNUMBER_INVALID'")
  205.                            cursor.execute(srcErrorSource)
  206.                            errStorageA = cursor.fetchall()
  207.                            for row in errStorageA:
  208.                                errKey = row[0]
  209.                                errHash = row[1]
  210.                            cnx.connect()
  211.                            recQueryErrorNumb = ("insert into outbox(Text, DestinationNumber, "
  212.                                                 "TextDecoded, CreatorID) values "
  213.                                                 "('%s','%s','%s','PwC')" % (errHash, telephone, errKey))
  214.                            cursor.execute(recQueryErrorNumb)
  215.                            cnx.commit()
  216.                            cnx.close()
  217.                            #Reconnecting to database and updating message status
  218.                            cnx.connect()
  219.                            updateRquery = ("update inbox set chck=1 where "
  220.                                            "ID=%s" % toUR)
  221.                            cursor.execute(updateRquery)
  222.                            cnx.commit()
  223.                            cnx.close()
  224.                            #Wait for re-establish loop
  225.                            import time
  226.                            time.sleep(3)
  227.                            continue
  228.                    else:
  229.                        #Unknown message or command => ERR_TLPNUMBER_INVALID
  230.                        srcErrorSource = ("select errordesc, hexcode from transfererrors "
  231.                                                      "where cause='ERR_TLPNUMBER_INVALID'")
  232.                        cursor.execute(srcErrorSource)
  233.                        errStorageA = cursor.fetchall()
  234.                        for row in errStorageA:
  235.                            errKey = row[0]
  236.                            errHash = row[1]
  237.                            cnx.close()
  238.                        cnx.connect()
  239.                        recQueryErrorNumb = ("insert into outbox(Text, DestinationNumber, "
  240.                                                         "TextDecoded, CreatorID) values "
  241.                                                         "('%s','%s','%s','PwC')" % (errHash, telephone, errKey))
  242.                        cursor.execute(recQueryErrorNumb)
  243.                        cnx.commit()
  244.                        cnx.close()
  245.                        #Reconnecting to database and updating message status
  246.                        cnx.connect()
  247.                        updateRquery = ("update inbox set chck=1 where "
  248.                                                    "ID=%s" % toUR)
  249.                        cursor.execute(updateRquery)
  250.                        cnx.commit()
  251.                        cnx.close()
  252.                        #Wait for re-establish loop
  253.                        import time
  254.                        time.sleep()
  255.                        continue
  256.                else:
  257.                    #Authetication error, wron key => ERR_AUTHKEY_INVALID
  258.                    srcErrorSource = ("select errordesc, hexcode from transfererrors "
  259.                                                      "where cause='ERR_AUTHKEY_INVALID'")
  260.                    cursor.execute(srcErrorSource)
  261.                    errStorageA = cursor.fetchall()
  262.                    for row in errStorageA:
  263.                        errKey = row[0]
  264.                        errHash = row[1]
  265.                        cnx.close()
  266.                    cnx.connect()
  267.                    recQueryErrorNumb = ("insert into outbox(Text, DestinationNumber, "
  268.                                                         "TextDecoded, CreatorID) values "
  269.                                                         "('%s','%s','%s','PwC')" % (errHash, telephone, errKey))
  270.                    cursor.execute(recQueryErrorNumb)
  271.                    cnx.commit()
  272.                    cnx.close()
  273.                    #Reconnecting to database and updating message status
  274.                    cnx.connect()
  275.                    recQueryErrorNumb = ("update inbox set chck=1 where "
  276.                                                         "ID=%s" % toUR)
  277.                    cursor.execute(updateRquery)
  278.                    cnx.commit()
  279.                    cnx.close()
  280.                    #Wait for re-establish loop
  281.                    import time
  282.                    time.sleep()
  283.                    continue
  284.            else:
  285.                print("|| "+telephone+"\t\t"+timeO)
  286.                print("|| "+message+"\n\n")
  287.                balloon_tip("Mensaje recibido",message+"\nDe: "+telephone+"\t"+timeO)
  288.                file = open("smscenter.log","a")
  289.                file.write("Message was received at: "+timeO+"\n")
  290.                file.write("----------------------------------------\n")
  291.                file.write("|| "+telephone+"\n")
  292.                file.write("|| "+message.encode("utf8")+"\n")
  293.                file.write("-----Length of sms: "+str(lengM)+"\n")
  294.                file.write("-----Recognize: \n\n\n")
  295.                file.close()
  296.                cnx.close()
  297.                cnx.connect()
  298.                updateRquery = ("update inbox set chck=1 where ID=%s" % toUR)
  299.                cursor.execute(updateRquery)
  300.                cnx.commit()
  301.                cnx.close()
  302.                import time
  303.                time.sleep(3)
  304.                continue            
  305.  
  306. def readWh():
  307.    while True:
  308.        cnx2.connect()
  309.        lastRquery2 = ("select UpdatedInDB, TextDecoded, SenderNumber, ID from inbox where "
  310.                       "chck=0 order by UpdatedInDB asc limit 1")
  311.        cursor2.execute(lastRquery2)
  312.        regL2 = cursor2.fetchall()
  313.        if not regL2:
  314.            cnx2.close()
  315.            cnx2.connect()
  316.            queryTrunc = ("delete from inbox where chck=1")
  317.            cursor2.execute(queryTrunc)
  318.            cnx2.commit()
  319.            cnx2.close()
  320.            import time
  321.            time.sleep(3)
  322.            continue
  323.        else:
  324.            for row in regL2:
  325.                timeReceived = row[0]
  326.                timeReceivedC = str(timeReceived)
  327.                timeReceivedO = timeReceivedC[10:]
  328.                messageRec = row[1]
  329.                telephoneRec = row[2]
  330.                idRec = row[3]
  331.                cnx2.close()
  332.            print("Hola menor")
  333.            cnx2.connect()
  334.            queryA = ("insert into inboxencrypt(id, UpdatedInDB, TextDecoded, SenderNumber) "
  335.                      "values (%s, %s, AES_ENCRYPT('%s', (select AES_DECRYPT(cryptkey, '373630303a3a3') from decrypkey)), "
  336.                      "AES_ENCRYPT('%s', (select AES_DECRYPT(cryptkey, '373630303a3a3') from decrypkey)))")
  337.            cursor2.execute(queryA)
  338.            cnx2.commit()
  339.            cnx2.close()
  340.            #Drop message
  341.            cnx2.connect()
  342.            queryB = ("update inbox set chck=1 where "
  343.                      "ID=%s" % idRec)
  344.            cursor2.execute(queryB)
  345.            cnx2.commit()
  346.            cnx2.close()
  347.            cnx2.connect()
  348.            queryC = ("delete from inbox where chck=1")
  349.            cursor2.execute(queryC)
  350.            cnx2.commit()
  351.            cnx2.close()
  352.            continue
  353.  
  354. def sentWh():
  355.    while True:
  356.        cnx3.connect()
  357.        lastRquery3 = ("select UpdatedInDB, InsertIntoDB, SendingDateTime, DestinationNumber, "
  358.                       "TextDecoded, ID, Status, CreatorID from sentitems where chck=0 order by UpdatedInDB asc limit 1")
  359.        cursor3.execute(lastRquery3)
  360.        regL3= cursor3.fetchall()
  361.        if not regLr:
  362.            cnx3.close()
  363.            cnx3.connect()
  364.            queryTrunc1 = ("delete from sentitems where chck=1")
  365.            cursor3.execute(queryTrunc1)
  366.            cnx3.commit()
  367.            cnx3.close()
  368.            import time
  369.            time.sleep(3)
  370.            print("Hola menor")
  371.            continue
  372.        else:
  373.            for row in regL3:
  374.                timeUpdated = row[0]
  375.                timeInsert = row[1]
  376.                timeSent = row[2]
  377.                telephoneSent = row[3]
  378.                messageSent = row[4]
  379.                idSent = row[5]
  380.                status = row[6]
  381.                creator = row[7]
  382.                cnx3.close()
  383.            cnx3.connect()
  384.            print("Hola menor")
  385.            queryD = ("insert into sentencrypt(id, UpdatedInDB, InsertIntoDB, SendingDateTime, "
  386.                      "DestinationNumber, TextDecoded, Status, CreatorID) values "
  387.                      "(%s, '%s', '%s', '%s', "
  388.                      "AES_ENCRYPT('%s', (select AES_DECRYPT(cryptkey, '373630303a3a3') from decrypkey)), "
  389.                      "AES_ENCRYPT('%s', (select AES_DECRYPT(cryptkey, '373630303a3a3') from decrypkey)), "
  390.                      "'%s', AES_ENCRYPT('%s', (select AES_DECRYPT(cryptkey, '373630303a3a3') from decrypkey)))"
  391.                      % (idSent, timeUpdated, timeInsert, timeSent, telephoneSent, messageSent, status, creator))
  392.            cursor3.execute(queryD)
  393.            cnx3.commit()
  394.            cnx3.close()
  395.            #Drop message
  396.            cnx3.connect()
  397.            queryZ = ("update sentitems set chck=1 where "
  398.                      "ID=%s" % idSent)
  399.            cursor3.execute(queryZ)
  400.            cnx3.commit()
  401.            cnx3.close()
  402.            cnx3.connect()
  403.            queryE = ("delete from sentitems where chck=1")
  404.            cursor.execute(queryE)
  405.            cnx3.commit()
  406.            cnx3.close()
  407.            import time
  408.            time.sleep(3)
  409.            continue
  410.  
  411.  
  412. if __name__ == '__main__':
  413.    print("Be sure you have Windows pop-ups notifications enabled.\n\n")
  414.    print("SMS Center will show pop-ups notifications when message is being received."
  415.          "\nThis window need to be open at anytime.")
  416.    Thread(target = newWh).start()
  417.    Thread(target = readWh).start()
  418.    Thread(target = sentWh).start()
  419.