# -*- coding: utf-8 -*- """usage : tps.py fichier_config Si le nom du fichier config est absent, c'est 'tps.cfg' qui est pris. TPS gère 5 évènements : - Tâches, d'après le fichier Taches.txt - TCP/IP, d'après les requêtes codées, sur le port 22222 par défaut - e-Mail (Melpondeur), sur les messages reçus dans le compte 'bot' de pasram.py - Clipboard, avec une surveillance du contenu du presse-papier, toutes les X secondes - Passerelle par interrogation d'un autre TPS 5 parties gèrent ces évènements par des threads Dans le code, les 5 parties commencent par #*** """ GlobalPVersion='4.0' import socket,string import os,os.path,sys import cStringIO import formatter import re import time,datetime import shutil import threading import poplib import email import htmllib import quopri import urllib import locale from win32com.client import Dispatch cponx = Dispatch('ponx.Mci') dponx = Dispatch('ponxd.Mci') from email.Header import Header,decode_header """Valeurs par défaut conseillées : PORT = 22222 HOST = '127.0.0.1' HOST = socket.gethostbyname(socket.gethostname()) #adr.TCP/IP du POSTE courant MELDELAI = 0 #en minutes ; 0 désactive le MelPondeur CLIPDELAI = 0 # en secondes PASSERELLEDELAI = 0 # en minutes ; 0 désactive la passerelle PASSERELLEIP = 'Claveau.dnsalias.net' PASSERELLEPORT = PORT Verbeux="NON" Verbeux="OUI" IDENTIFIANT="XXX" # Nom UNIQUE du poste """ os.chdir(os.path.dirname(__file__)) if len(sys.argv)>1: if os.path.isfile(sys.argv[1]): execfile(sys.argv[1],globals(),globals()) else: execfile(os.path.dirname(__file__)+"\\tps.cfg",globals(),globals()) try: print "Adresse IP du poste :",string.upper(HOST) print if string.upper(HOST)=='LOCAL': HOST = '127.0.0.1' if string.upper(HOST)=='HOST' or string.upper(HOST)=='SERVEUR' or string.upper(HOST)=='SERVER': HOST = socket.gethostbyname(socket.gethostname()) except: pass GlobalMelPondeurIntervalle=MELDELAI*60.0 # intervalle, en secs, entre vérifications successives de présence de messages GlobalSTOP=False CodingParDefaut=locale.getpreferredencoding() conn = None adr = None persist_dict={} persist_typ={} persist_secur={} #-chargement (load) des APS try: persist_aps=open("tps.aps","rb").read() except: persist_aps="" for i in persist_aps.split('|'): if i!="": try: import shelve tmp=shelve.open(i+".tps.save") persist_dict[i]=tmp['1'] persist_typ[i]=None persist_secur[i]="" tmp.close() except: print error pass #------------------------- def vifi(chaine): print(chaine), def PVersion(): return GlobalPVersion def u1252(chu): try: if type(chu) is unicode: return chu.encode('cp1252','replace') else: return chu except: return repr(chu) #***-----------------------------Début de la partie 'Taches'------------------------------ def testdeclench(lhor='08:01 09:01 10:01 11:01 12:01 14:01 16:01 18:01 20:01', ljour='lundi mardi mercredi jeudi vendredi',lquant='',borned='01.01.2006',bornef='31.12.2016'): import time,calendar,locale,datetime locale.setlocale(locale.LC_ALL, "") dat=time.time() jourdhui=time.strftime("%d.%m.%Y") jour=time.strftime("%A") #string quantieme=time.strftime("%d") #string moisnum=(time.strftime("%m")) #entier maintenant=time.strftime("%H:%M") #string annee=int(time.strftime("%Y")) #entier """ print "aujourd'hui:",jourdhui print "jour",jour #mardi print "quantième",quantieme #19 print "mois",time.strftime("%B") #septembre print "annee",time.strftime("%Y") #2006 print "maintenant",maintenant #15:29 """ if maintenant in lhor: flag=True else: flag=False if flag: if jour in ljour or ljour=='': pass else: flag=False if flag: if quantieme in lquant or lquant=='': pass else: #print "False" flag=False if flag: def sdate(sd): j,m,a=sd.split('.') return datetime.date(int(a),int(m),int(j)) datcourante=datetime.date.fromtimestamp(dat) dd=sdate(borned) df=sdate(bornef) if datcourante>=dd and datcourante<=df: pass else: flag=False #print "maintenant",maintenant,flag return flag def tacheslist(): #for txt='' for ntache in deftaches: txt += '\r\n' + ('-'*55) txt=txt+'\r\nnom: '+ntache txt=txt+'\r\nheures: '+deftaches[ntache][0] txt=txt+'\r\njours: '+deftaches[ntache][1] txt=txt+'\r\nquant.: '+deftaches[ntache][2] txt=txt+'\r\ndateMini '+deftaches[ntache][3] txt=txt+'\r\ndateMaxi '+deftaches[ntache][4] txt=txt+'\r\ntype '+deftaches[ntache][5] txt=txt+'\r\njournal '+deftaches[ntache][7] txt=txt+'\r\ncommande '+deftaches[ntache][6] return txt def texe(): #détermine les taches à exécuter (planifiées), et les lance asuppr=[] for ntache in deftaches: lhor=deftaches[ntache][0] ljour=deftaches[ntache][1] lquant=deftaches[ntache][2] borned=deftaches[ntache][3] bornef=deftaches[ntache][4] if testdeclench(lhor,ljour,lquant,borned,bornef): try: if deftaches[ntache][5]=='python': #print deftaches[ntache][6],"-"*44 print time.strftime("%d.%m.%Y %H:%M:%S"),' (python) ',ntache exec(deftaches[ntache][6],globals(),globals()) else: #print deftaches[ntache][6] print time.strftime("%d.%m.%Y %H:%M:%S"),' ',ntache except: print "Erreur dans l'exécution de ",ntache pass if deftaches[ntache][7]=='OUI': try: f=open('TchJrnl.txt','aw') f.write(ntache+' lancé à '+str(datetime.datetime.today())+'\n') f.close() except: pass def tinit(): deftaches={} execfile(os.path.dirname(__file__)+'\\deftaches.py',globals(),globals()) #print deftaches #sys.exit(0) def ttache(): #boucle de lancement des taches while(1): for i in xrange(8): if GlobalSTOP==True: try: TCPcoupe() except: pass print"FIN Tâches" return else: time.sleep(TACHEDELAI/8) texe() #------------------------------Fin de la partie 'Taches'-------------------------------- #***-------------------------Début de la partie 'DPERSIST'------------------------------ def DPersist(commande, param=None, long=0, objet=None, typ=None, secur=None): global persist_dict,persist_typ,persist_secur,persist_aps,GlobalSTOP,cponx,dponx if Verbeux=="OUI": print print "280 commande:",commande," ",secur,SECURAUT if not(SECURAUT is None): if not secur in SECURAUT: print "Not secure." return None if commande=="SET": if Verbeux=="OUI": print "SET",param,secur print ' len:',len(objet) try: print 293,'len:',len(objet) persist_dict[param]=objet persist_typ[param]=typ persist_secur[param]=secur if Verbeux=="OUI": print "Nb items, apres SET",len(persist_dict) return("OK") except: return("Erreur.") if commande=="APP": #ajoute (APPend) au dictionnaire persistant if Verbeux=="OUI": print "APP",param,secur print ' len:',len(objet) try: if persist_dict.has_key(param): persist_dict[param]+=objet else: persist_dict[param]=objet persist_typ[param]=typ persist_secur[param]=secur if Verbeux=="OUI": print "Nb items, apres APP",len(persist_dict) return("OK") except: return("Erreur.") if commande=="APS": #comme APP, mais sauvegarde, en plus, l'objet if Verbeux=="OUI": print "APS",param,secur print ' len:',len(objet) try: if persist_dict.has_key(param): persist_dict[param]+=objet else: persist_dict[param]=objet persist_typ[param]=typ persist_secur[param]=secur try: import shelve tmp=shelve.open(param+".tps.save") tmp["1"]=persist_dict[param] tmp.close() except: pass tmpparam=param+'|' if persist_aps.find(tmpparam)<0: persist_aps+=tmpparam open("tps.aps","wb").write(persist_aps) if Verbeux=="OUI": print "Nb items, apres APS",len(persist_dict) return("OK") except: return("Erreur.") if commande=="PPAW": if Verbeux=="OUI": print "PPAW",param,secur print ' len:',len(objet) try: f=open('D:\\home\\site\\static\\static\\'+param,'wb') f.write(objet) f.close() if Verbeux=="OUI": print 'D:\\home\\site\\static\\static\\'+param,len(persist_dict) return("OK") except: return("Erreur.") if commande=="DEL": try: del persist_dict[param] return("OK") except: return("Erreur.") if commande=="GET": if Verbeux=="OUI": print "371 GET",param,secur try: sflag=True try: if param in persist_secur: if persist_secur[param]<>secur and (persist_secur[param] is not None) and persist_secur[param]!='': sflag=False except: pass if sflag: try: toto=persist_dict[param] return toto #print"Prépar ",len(persist_dict[param]) except: return('') else: return('') except: return('') if commande=="SAV": try: import shelve tmp=shelve.open(param) tmp["1"]=persist_dict tmp.close() return('OK.') except: return("Erreur.") if commande=="LIT": try: import shelve tmp=shelve.open(param) persist_dict=tmp["1"] tmp.close() return("OK.") except: return("Erreur.") if commande=="LST": try: st='' for item in persist_dict.keys(): if Verbeux=="OUI": print item,len(persist_dict[item]) if persist_secur[item]==secur or (persist_secur[item] is None) or persist_secur[item]=='': #'\t'+str(len(persist_dict.keys[item]))+ st=st+item+'\r\n' return(st) except: return("LST Erreur.") if commande=="ELT": # retourne un élément # TACHES = listes des tâches planifiées if Verbeux=="OUI": print 'ELT',param try: if upper(param)=="TACHES": st=tacheslist() if Verbeux=="OUI": print st return(st) except: return("ELT Erreur.") if commande=="PEX": if Verbeux=="OUI": print "PEX",param,secur,persist_dict[param] if persist_secur[param]<>secur and (not(persist_secur[param] is None)) and persist_secur[param]!='': return("Erreur.") else: try: st=persist_dict[param] chaineretour=cponx.PRun(st) return(u1252(chaineretour)) except: return("Erreur.") if commande=="CEX": if Verbeux=="OUI": print "CEX.SET",param,secur try: persist_dict[param]=objet persist_typ[param]=typ persist_secur[param]=secur if Verbeux=="OUI": print "Nb items, apres CEX.SET",len(persist_dict) except: pass if persist_secur[param]<>secur and (not(persist_secur[param] is None)) and persist_secur[param]!='': return("Erreur.") if Verbeux=="OUI": print "GET",param,secur,persist_dict[param] try: st=persist_dict[param] chaineretour=cponx.PRun(st) return(u1252(chaineretour)) except: return("Erreur.") if commande=="FIN": GlobalSTOP=True print"FIN Dpersist" time.sleep(0.250) #sys.exit() #-------------------------------Fin de la partie 'DPERSIST'-------------------------------- #***-----------------------------Début de la partie 'TCP'---------------------------------- def TCPreception(buffer,connection): commande=buffer[:3] if len(buffer)<54: buffer+=' '*54 try: param1=buffer[4:24] # Nom (ou code) (20 caractères) param1=string.strip(param1) param2=buffer[24:34] # longueur (10 caractères) param2=int('0'+string.strip(param2)) param3=buffer[34:44] # type (10 caractères) param3=string.strip(param3) #param3=int('0'+string.strip(param3)) param4=buffer[44:54] # securite (10 caractères) param4=string.strip(param4) #param4=int('0'+string.strip(param4)) except: return if param2>len(buffer)-54: data=connection.recv(param2-(len(buffer)-54)) buffer += data #print param2,len(buffer)-54,"*"*44 if Verbeux=='OUI': print "commande:","*"+commande+"*",param1,param2,param3,param4 if commande==' ': print "cde espaces" if commande=="FIN": print "FIN reçue ; arrêt en cours... " GlobalSTOP=True DPersist("FIN",secur=param4) if commande=="SET": try: DPersist("SET", param=param1, long=param2, typ=param3, secur=param4, objet=buffer[54:param2+54]) except: pass #conn.close() if commande=="APP": try: DPersist("APP", param=param1, long=param2, typ=param3, secur=param4, objet=buffer[54:param2+54]) except: pass #conn.close() if commande=="APS": try: DPersist("APS", param=param1, long=param2, typ=param3, secur=param4, objet=buffer[54:param2+54]) except: pass #conn.close() if commande=="PPA": #print"PPA",param1,param2," len",len(buffer[54:param2+54]) try: DPersist("PPAW", param=param1, long=param2, typ=param3, secur=param4, objet=buffer[54:param2+54]) except: pass #conn.close() if commande=="DEL": DPersist("DEL", param1) #conn.close() if commande=="GET": try: strt=DPersist("GET", param1, long=0, typ=param3, secur=param4) connection.sendall(strt) except: pass if Verbeux=="OUI": print "Send." #conn.close() if commande=="LST": connection.sendall(DPersist("LST",param='', long=0, typ=param3, secur=param4)) #conn.close() if commande=="ELT": # retourne un élément # TACHES = listes des tâches planifiées if Verbeux=="OUI": print 'ELT',param1 try: if param1=="TACHES": st=tacheslist() if Verbeux=="OUI": print 579, #st print connection.sendall(st) except: return("ELT Erreur.") if commande=="SAV": connection.sendall(DPersist("SAV", param1)) #conn.close() if commande=="LIT": try: connection.sendall(DPersist("LIT", param1)) except: connection.sendall("Erreur.") #conn.close() if commande=="PEX": toto=DPersist("PEX", param1, long=0, typ=param3, secur=param4) connection.sendall(toto) #conn.close() if commande=="CEX": toto=DPersist("CEX", param=param1, long=param2, typ=param3, secur=param4, objet=buffer[54:param2+54]) connection.sendall(toto) #conn.close() return(commande) def TCPboucle(connection): buffer="" connection.settimeout(None) #connection.settimeout(0.001) while True: data=connection.recv(4096) buffer=data while len(data)==4096: data=connection.recv(4096) buffer+=data if buffer: if buffer.startswith("FIN"): print "Fin" os._exit(0) else: TCPreception(buffer,connection) else: break connection.close() #-----------------------------Fin de la partie 'TCP'-------------------------------- #***-----------------------------Début de la partie 'CLIP'---------------------------------- """ Le presse-papier (clipboard) en mode "Texte" (CF_TEXT) doit commencer de la sorte : "TPS:IDENTIFIANT GET NOM type (non utilisé) SECURITE " et être suivi du corps """ def CLIPreception(): global persist_dict,nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalSTOP import ponx buffer=ponx.clipboardtxt() ponx.clipboardtxt(buffer) if buffer.startswith('TPS:'+IDENTIFIANT): buffer=buffer[4:] else: return #if Verbeux=='OUI': # print buffer[:30] if buffer.find('\r\n')>-1: ltmp=string.split(buffer,'\r\n') else: ltmp=string.split(buffer,'\n') commande = '' if len(ltmp)>3: commande = ltmp[1] param1 = nom = ltmp[2] param3 = typ = ltmp[3] param4 = securite = ltmp[4] #ponx.msginfo("CLIP",commande) if len(ltmp)>4: param5 = corps = string.join(ltmp[5:],'\n') param2 = len(param5) if commande=='': return if Verbeux=='OUI': print commande,param1,param2,param3,param4 if commande=="FIN": GlobalSTOP=True DPersist("FIN") try: TCPcoupe() except: pass if commande=="SET": ponx.clipboardtxt('TPS vide') try: DPersist("SET", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "SET OK" except: if Verbeux=="OUI": print "SET Erreur" pass if commande=="APP": ponx.clipboardtxt('TPS vide') try: DPersist("APP", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APP OK" except: if Verbeux=="OUI": print "APP Erreur" pass if commande=="APS": ponx.clipboardtxt('TPS vide') try: DPersist("APS", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APS OK" except: if Verbeux=="OUI": print "APP Erreur" pass if commande=="DEL": ponx.clipboardtxt('TPS vide') try: DPersist("DEL", param1) ponx.clipboardtxt(buffer) if Verbeux=="OUI": print "DEL OK,"+param1 except: if Verbeux=="OUI": print "DEL Erreur" pass if commande=="GET": try: buffer=DPersist("GET", param1, long=0, typ=param3, secur=param4) ponx.clipboardtxt(buffer) if Verbeux=="OUI": print "GET OK, send."+buffer except: if Verbeux=="OUI": print "GET Erreur" pass if commande=="LST": ponx.clipboardtxt(DPersist("LST",param='', long=0, typ=param3, secur=param4)) if commande=="SAV": ponx.clipboardtxt(DPersist("SAV", param1)) if commande=="LIT": try: ponx.clipboardtxt(DPersist("LIT", param1)) except: ponx.clipboardtxt("Erreur.") conn.close() if commande=="PEX": try: ponx.clipboardtxt('TPS vide') toto=DPersist("PEX", param1, long=0, typ=param3, secur=param4) ponx.clipboardtxt(toto) if Verbeux=="OUI": print "PEX OK" except: if Verbeux=="OUI": print "PEX Erreur" pass if commande=="CEX": try: ponx.clipboardtxt('TPS vide') toto=DPersist("CEX", param=param1, long=param2, typ=param3, secur=param4, objet=param5) ponx.clipboardtxt(toto) if Verbeux=="OUI": print "CEX OK" except: if Verbeux=="OUI": print "CEX Erreur" pass return(commande) def CLIPboucle(): #boucle de lancement des taches print "CLIPersistServer est lancé" while(1): time.sleep(CLIPDELAI) if CLIPreception()=="FIN" or GlobalSTOP==True: print"FIN CLIP" break #-----------------------------Fin de la partie 'CLIP'-------------------------------- #***-----------------------Début de la partie 'PASSERELLE TCP'---------------------------- """ La passerelle utilise une gestion similaire au presse-papier (clipboard) en mode "Texte". Seule particularité, le code (l'ID) utilisé est IDENTIFIANT, il remplace le début du presse-papier. """ def PASSreception(): global persist_dict,nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalSTOP import ponx if Verbeux=="OUI": print"Passerelle réception", try: buffer=ponx.TCPersistgettxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) except: buffer="" #if Verbeux=="OUI": # print buffer if len(buffer)==0: return #à partir de là, traitement presque identique au CLIP if buffer.find('\r\n')>-1: ltmp=string.split(buffer,'\r\n') else: ltmp=string.split(buffer,'\n') commande = '' if len(ltmp)>3: commande = ltmp[0] param1 = nom = ltmp[1] param3 = typ = ltmp[2] param4 = securite = ltmp[3] #ponx.msginfo("PASSERELLE",commande) if len(ltmp)>3: param5 = corps = string.join(ltmp[4:],'\n') param2 = len(param5) if commande=='': return if Verbeux=='OUI': print "Passerelle:",commande,param1,param2,param3,param4 if commande=="FIN": GlobalSTOP=True DPersist("FIN") try: TCPcoupe() except: pass if commande=="SET": try: DPersist("SET", param=param1, long=param2, typ=param3, secur=param4, objet=param5) ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) if Verbeux=="OUI": print "P-SET OK"+param1 except: if Verbeux=="OUI": print "P-SET Erreur" pass if commande=="APP": try: DPersist("APP", param=param1, long=param2, typ=param3, secur=param4, objet=param5) ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) if Verbeux=="OUI": print "P-APP OK"+param1 except: if Verbeux=="OUI": print "P-APP Erreur" pass if commande=="APS": try: DPersist("APS", param=param1, long=param2, typ=param3, secur=param4, objet=param5) ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) if Verbeux=="OUI": print "P-APS OK"+param1 except: if Verbeux=="OUI": print "P-APS Erreur" pass if commande=="DEL": ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) DPersist("DEL", param1) if commande=="GET": #sans objet pass if commande=="LST": #sans objet pass if commande=="SAV": st=DPersist("SAV", param1) ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) if commande=="LIT": ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) try: st=DPersist("LIT", param1) except: #erreur pass if commande=="PEX": try: ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) st=DPersist("PEX", param1, long=0, typ=param3, secur=param4) if Verbeux=="OUI": print "P-PEX OK"+param1 except: if Verbeux=="OUI": print "P-PEX Erreur" pass if commande=="CEX": try: ponx.TCPersistdeltxtUnit(IDENTIFIANT, '', '', PASSERELLEIP, PASSERELLEPORT) st=DPersist("CEX", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "P-CEX OK"+param1 except: if Verbeux=="OUI": print "P-CEX Erreur" pass return(commande) def PASSboucle(): #boucle de lancement des taches iboucle=0 while(1): if GlobalSTOP==True: return time.sleep(1) iboucle+=1 if iboucle>=PASSERELLEDELAI*60/1: #if Verbeux=="OUI": # print "Passerelle" iboucle=0 if PASSreception()=="FIN" or GlobalSTOP==True: print"FIN PASSERELLE" break #-------------------------Fin de la partie 'PASSERELLE TCP'---------------------------- #***-----------------------Début de la partie 'MXCHANGE'------------------------------- """ Cette partie utilise mxmap pour échanger les strings. L'ID du mxmap est dans la config Le reste du code est dérivé de la gestion par Clipboard. En retour, les 15 premiers caractères contiennent: TPS=00000000000 (où les 0 indiquent la longueur de la chaîne retournée) """ def MXCHANGEreception(mxmap): global persist_dict,nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalSTOP mxmap.seek(0) buffer=mxmap.read(12) if buffer[:4]=='TPS:': i=buffer.find('\r\n') j=i+2 if i<0: i=buffer.find('\n') j=i+1 longueur=int(buffer[4:i]) mxmap.seek(0) buffer=mxmap.read(j) buffer=mxmap.read(longueur) else: return if Verbeux=='OUI': print buffer if buffer.find('\r\n')>-1: ltmp=string.split(buffer,'\r\n') else: ltmp=string.split(buffer,'\n') commande = '' if len(ltmp)>3: commande = ltmp[0] param1 = nom = ltmp[1] param3 = typ = ltmp[2] param4 = securite = ltmp[3] #ponx.msginfo("MXCHANGE",commande) if len(ltmp)>3: param5 = corps = string.join(ltmp[4:],'\n') param2 = len(param5) if commande=='': return if Verbeux=='OUI': print commande,param1,param2,param3,param4 if commande=="FIN": GlobalSTOP=True DPersist("FIN") try: TCPcoupe() except: pass if commande=="SET": mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() try: DPersist("SET", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "SET OK" except: if Verbeux=="OUI": print "SET Erreur" pass if commande=="APP": mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() try: DPersist("APP", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APP OK" except: if Verbeux=="OUI": print "APP Erreur" pass if commande=="APS": mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() try: DPersist("APS", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APS OK" except: if Verbeux=="OUI": print "APS Erreur" pass if commande=="DEL": mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() try: DPersist("DEL", param1) mxmap.seek(0) mxmap.write("DEL "+param1+" OK") mxmap.flush() if Verbeux=="OUI": print "DEL OK,"+param1 except: if Verbeux=="OUI": print "DEL Erreur" pass if commande=="GET": try: buffer=DPersist("GET", param1, long=0, typ=param3, secur=param4) mxmap.seek(0) mxmap.write("TPS="+str(len(buffer)).ljust(11)+buffer) mxmap.flush() if Verbeux=="OUI": print "GET OK, send."+buffer except: mxmap.seek(0) mxmap.write("TPS=GET.Erreur") mxmap.flush() if Verbeux=="OUI": print "GET Erreur" pass if commande=="LST": buffer=DPersist("LST",param='', long=0, typ=param3, secur=param4) mxmap.seek(0) mxmap.write("TPS="+buffer) mxmap.flush() if commande=="SAV": buffer=DPersist("SAV", param1) mxmap.seek(0) mxmap.write("TPS="+buffer) mxmap.flush() if commande=="LIT": try: buffer=DPersist("LIT", param1) mxmap.seek(0) mxmap.write(buffer) mxmap.flush() except: mxmap.seek(0) mxmap.write("Erreur") mxmap.flush() conn.close() if commande=="PEX": try: mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() toto=DPersist("PEX", param1, long=0, typ=param3, secur=param4) mxmap.seek(0) mxmap.write("TPS="+toto) mxmap.flush() if Verbeux=="OUI": print "PEX OK" except: if Verbeux=="OUI": print "PEX Erreur" pass if commande=="CEX": try: mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() toto=DPersist("CEX", param=param1, long=param2, typ=param3, secur=param4, objet=param5) mxmap.seek(0) mxmap.write("TPS="+toto) mxmap.flush() if Verbeux=="OUI": print "CEX OK" except: if Verbeux=="OUI": print "CEX Erreur" pass if commande=="DEX": try: mxmap.seek(0) mxmap.write('TPS vide. ') mxmap.flush() ccod=compile(param5,'TPS:DEX','exec') exec(ccod,globals(),globals()) if Verbeux=="OUI": print "DEX OK" except: if Verbeux=="OUI": print "DEX Erreur" pass return(commande) def MXCHANGEboucle(): mxmap=mmap.mmap(0,MXCHANGETAILLE,MXCHANGEID) while(1): time.sleep(MXCHANGEDELAI) if MXCHANGEreception(mxmap)=="FIN" or GlobalSTOP==True: print"FIN MXCHANGE" try: mxmap.close() except: pass break #---------------------------Fin de la partie 'MXCHANGE'------------------------------ #***-----------------------Début de la partie 'FICHIERPRDXNET'------------------------------- """ Cette partie utilise un fichier pour échange. Le fichier est dans le répertoire NETDIR. Son nom est l'IDENTIFIANT + ".TPS" Le reste du code est dérivé de la gestion de MXCHANGE En retour, les 15 premiers caractères contiennent: TPS=00000000000 (où les 0 indiquent la longueur de la chaîne retournée) """ def PRDXNETreception(): global persist_dict,nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalSTOP if not os.path.isfile(NETDIR+IDENTIFIANT+".TPS"): return f=open(NETDIR+IDENTIFIANT+".TPS") buffer=f.read() f.close() if buffer[:4]=='TPS:': buffer=buffer[4:] else: return if Verbeux=='OUI': print buffer if buffer.find('\r\n')>-1: ltmp=string.split(buffer,'\r\n') else: ltmp=string.split(buffer,'\n') commande = '' if len(ltmp)>3: commande = ltmp[0] param1 = nom = ltmp[1] param3 = typ = ltmp[2] param4 = securite = ltmp[3] #ponx.msginfo("PRDXNET",commande) if len(ltmp)>3: param5 = corps = string.join(ltmp[4:],'\n') param2 = len(param5) if commande=='': return if Verbeux=='OUI': print commande,param1,param2,param3,param4 if commande=="FIN": GlobalSTOP=True DPersist("FIN") try: TCPcoupe() except: pass if commande=="SET": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: DPersist("SET", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "SET OK" except: if Verbeux=="OUI": print "SET Erreur" pass if commande=="APP": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: DPersist("APP", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APP OK" except: if Verbeux=="OUI": print "APP Erreur" pass if commande=="APS": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: DPersist("APS", param=param1, long=param2, typ=param3, secur=param4, objet=param5) if Verbeux=="OUI": print "APS OK" except: if Verbeux=="OUI": print "APS Erreur" pass if commande=="DEL": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: DPersist("DEL", param1) if Verbeux=="OUI": print "DEL OK,"+param1 except: if Verbeux=="OUI": print "DEL Erreur" pass if commande=="GET": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: buffer=DPersist("GET", param1, long=0, typ=param3, secur=param4) f=open(NETDIR+IDENTIFIANT+".TPS","wb") f.write("TPS="+str(len(buffer)).ljust(11)+buffer) f.close() if Verbeux=="OUI": print "GET OK, send."+buffer except: if Verbeux=="OUI": print "GET Erreur" pass if commande=="LST": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass buffer=DPersist("LST",param='', long=0, typ=param3, secur=param4) f=open(NETDIR+IDENTIFIANT+".TPS","wb") f.write(buffer) f.close() if commande=="SAV": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass buffer=DPersist("SAV", param1) f=open(NETDIR+IDENTIFIANT+".TPS","wb") f.write(buffer) f.close() if commande=="LIT": try: buffer=DPersist("LIT", param1) os.remove(NETDIR+IDENTIFIANT+".TPS") except: os.remove(NETDIR+IDENTIFIANT+".TPS") conn.close() if commande=="PEX": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: toto=DPersist("PEX", param1, long=0, typ=param3, secur=param4) f=open(NETDIR+IDENTIFIANT+".TPS","wb") f.write("TPS="+str(len(toto)).ljust(11)+toto) f.close() if Verbeux=="OUI": print "PEX OK" except: if Verbeux=="OUI": print "PEX Erreur" pass if commande=="CEX": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: toto=DPersist("CEX", param=param1, long=param2, typ=param3, secur=param4, objet=param5) f=open(NETDIR+IDENTIFIANT+".TPS","wb") f.write("TPS="+str(len(toto)).ljust(11)+toto) f.close() if Verbeux=="OUI": print "CEX OK" except: if Verbeux=="OUI": print "CEX Erreur" pass if commande=="DEX": try: os.remove(NETDIR+IDENTIFIANT+".TPS") except: pass try: ccod=compile(param5,'TPS:DEX','exec') exec(ccod,globals(),globals()) if Verbeux=="OUI": print "DEX OK" except: if Verbeux=="OUI": print "DEX Erreur" pass return(commande) def PRDXNETboucle(): iboucle=0 while(1): if GlobalSTOP==True: return time.sleep(PRDXNETDELAI/10) iboucle+=1 #print iboucle,PRDXNETDELAI/10 if iboucle>=PRDXNETDELAI/10: iboucle=0 if PRDXNETreception()=="FIN" or GlobalSTOP==True: print"FIN FICHIERPRDXNET" break #---------------------------Fin de la partie 'FICHIERPRDXNET'------------------------------ #----------------------------Début de la partie 'MEL'-------------------------------- import pasram """ Structure des messages (en mode texte) GET BLAGUE NUMxxx où un nombre entre 001 et 999 TPS.SET dans le body, l'ID ; en attachment, la valeur TPS.GET dans le body, l'ID TPS.PEX dans le body, l'ID a exécuter TPS.CEX dans le body, l'ID ; en attachment, le code à exécuter (et stocker) """ globalsmtpserv = pasram.smtp['bot']['serveur'] globalexpediteur = pasram.smtp['bot']['expdefaut'] CRLF = '\r\n' nfichier='.NONE.' chaineretour='' BLK_SIZE = 1024 # Message block size. def composemsghtml(lbody): st='
'\ +string.join(lbody,'
')+\ '
' return st def envoimessage(stdestinataire, stmsg='Message vide.', lstpie = []): import ponx,pasram stsmtpserv=pasram.smtp['bot']['serveur'] #serveur smtp stsmtputl=pasram.smtp['bot']['utilisateur'] # utilisateur si authentification stsmtppasse=pasram.smtp['bot']['password'] # mot de passe si authentification stexpediteur=pasram.smtp['bot']['expdefaut'] # nom de l'expéditeur ponx.mailfiles(sender=stexpediteur, destinataire=(stdestinataire,), lstpjointes=lstpie, subject='TPS.MelPondeur', message=stmsg, smtpserveur=stsmtpserv) def melpondeurtraite(exp, tete, msg): exped = exp print 'Expéditeur:',exped print 'Tete :',tete print 'Message l.:',str(len(msg)) cmds=string.upper(tete) messagetexte=None fattachment=None msgparts=ponx.msgextract(msg) #msgparts=ponx.msgextract(msg,'c:\\msg') #print ponx.chaineretour for num,nom,codage,fichier,attachment in msgparts: #vifi(str(num)+'\t'+nom+'\t'+codage+'\t'+str(len(fichier))+'\tattachment: '+str(attachment)+'\r\n') if nom=='message_texte': messagetexte=fichier #print messagetexte if attachment==True: fattachment=fichier messagecourt=string.split(messagetexte)[0] if string.find(cmds,'GET')>-1 and string.find(cmds,'BLAGUE')>-1 and string.find(cmds,'NUM')>-1: i=string.find(cmds,'NUM') try: snum=string.join(re.findall('\d',cmds[i+3:]),'') nnn=string.atoi(snum) except: snum='000' nnn=0 print"Blague num.",nnn f=open('C:\\blagues\\'+str(nnn)+'.txt','r') msg=f.read() f.close() stmsg = string.upper(tete)+'\n\n'+msg envoimessage(exped, stmsg, lstpie = []) #stmsg=composemsghtml([msg+'\n\nBlague-image num.'+snum,]) #envoimessage(exped, stmsg, lstpie = []) elif string.find(cmds,'TPS.SET')>-1 : print "SET",messagecourt,len(fattachment) DPersist("SET", param=messagecourt, long=len(fattachment), objet=fattachment) elif string.find(cmds,'TPS.APP')>-1 : print "APP",messagecourt,len(fattachment) DPersist("APP", param=messagecourt, long=len(fattachment), objet=fattachment) elif string.find(cmds,'TPS.APS')>-1 : print "APS",messagecourt,len(fattachment) DPersist("APS", param=messagecourt, long=len(fattachment), objet=fattachment) elif string.find(cmds,'TPS.GET')>-1 : print(DPersist("LST")) f=open("C:\\OBJ.TPS","wb") print "GET",messagecourt tpsobj = DPersist("GET", messagecourt) if tpsobj is None: f.write('None') else: f.write(DPersist("GET", messagecourt)) f.close() stmsg = "Reponse de TPS"+'\n\n'+'pour '+messagecourt envoimessage(exped, stmsg, lstpie = ['c:\\OBJ.TPS']) os.remove('c:\\OBJ.TPS') elif string.find(cmds,'TPS.PEX')>-1 : print "PEX",messagecourt,len(fattachment) DPersist("PEX", param=messagecourt) elif string.find(cmds,'TPS.CEX')>-1 : print "CEX",messagecourt,len(fattachment) DPersist("CEX", param=messagecourt, long=len(fattachment), objet=fattachment) def selnumeric(chaine): ret='' for c in chaine: if c>='1' and c<='9': ret=ret+c else: break return ret def cherchemel(comptemel): ponx.chaineretour="" #buffer=cponx.PRun("cpoplit(comptemel,mode='TOUT')") ponx.cpoplit(comptemel,mode='TOUT') buffer=ponx.chaineretour if len(buffer)>5: SEPARITEMSERIAL='\t' SEPARLIGSERIAL=chr(255) lmsg=buffer.split(SEPARLIGSERIAL) numm=0 for item in lmsg: msg=item[item.find('|'):] if msg[0]=='|': cmsg=msg.split('\t') if len(cmsg)>3: num=int(cmsg[0][1:]) taille=int(cmsg[1]) exped=cmsg[2] suje=cmsg[3] dat=cmsg[4] typ=cmsg[5] msgcomplet=cponx.PxR(numm) body=ponx.msgextract(str(msgcomplet),'c:\\msg')[1][3] print'Message',num,'\nExpediteur:',exped,'\nDate:',dat,'\nSujet:',suje,'\n','Body:',body,'\n' #print str(msgcomplet) melpondeurtraite(exped, suje, str(msgcomplet)) try: print"Suppression",comptemel,[numm+1] ponx.cpopdestroy(comptemel,[numm+1]) # <----------------- Suppression except: pass numm+=1 def MelPondeur(): import pasram #boucle de lecture des e-mails du robot iboucle=0 while(1): if GlobalSTOP==True: return time.sleep(1) iboucle+=1 if iboucle>=MELDELAI*60/1: iboucle=0 cherchemel('bot') #-----------------------------Fin de la partie 'MEL'---------------------------------- if __name__ == '__main__': #-----------------------------Lancement-Taches---------------------------------------- if TACHEDELAI!=0: taches=[] tinit() idTACHE = threading.Thread(target=ttache,name="Taches") idTACHE.start() print"Serv.Tâches lancé" #-----------------------------Lancement--CLIP----------------------------------------- if CLIPDELAI!=0: import ponx print"CLIP lancé ; délai:",CLIPDELAI,"secondes" idCLIP = threading.Thread(target=CLIPboucle,name="CLIPersist") idCLIP.start() ponx.clipboardtxt('TPS-Clip prêt') #ponx.msginfo("CLIP","Lancé") #-----------------------------Lancement--PASSERELLE----------------------------------- if PASSERELLEDELAI!=0: import ponx print"PASSErelle lancé ; délai:",PASSERELLEDELAI,"minutes" idPASS = threading.Thread(target=PASSboucle,name="PASSPersist") idPASS.start() #-----------------------------Lancement--MXCHANGE------------------------------------- if MXCHANGEDELAI!=0: import mmap print"MXCHANGE lancé ; délai:",MXCHANGEDELAI,"secondes" idMXCHANGE = threading.Thread(target=MXCHANGEboucle,name="MXCHANGEPersist") idMXCHANGE.start() #-----------------------------Lancement--FICHIERPRDXNET------------------------------------- if PRDXNETDELAI!=0: import mmap print"FICHIERPRDXNET lancé ; délai:",PRDXNETDELAI,"secondes" idPRDXNET = threading.Thread(target=PRDXNETboucle,name="PRDXNETPersist") idPRDXNET.start() #-----------------------------Lancement--MEL------------------------------------------ if MELDELAI!=0: import ponx print"MelPondeur lancé ; délai:",MELDELAI,"minutes" idMELPONDEUR = threading.Thread(target=MelPondeur,name="TCPersist") idMELPONDEUR.start() #-----------------------------Lancement--TCP------------------------------------------ if FLAGTCP==True: #HOST = '127.0.0.1' #PORT = 22222 sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockobj.bind((HOST,PORT)) sockobj.listen(2) while True: time.sleep(0.1) connection,address = sockobj.accept() print "Serveur connected by",address print "at",time.ctime() conn=threading.Thread(target=TCPboucle,name="TCP_serveur",args=(connection,)) #conn.setDaemon(True) conn.start()