IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau/Web Python Discussion :

Vérification de la présence d'un proxy ?


Sujet :

Réseau/Web Python

  1. #1
    Expert confirmé Avatar de PauseKawa
    Homme Profil pro
    Technicien Help Desk, maintenance, réseau, système et +
    Inscrit en
    Juin 2006
    Messages
    2 725
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Technicien Help Desk, maintenance, réseau, système et +
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2006
    Messages : 2 725
    Points : 4 005
    Points
    4 005
    Par défaut Vérification de la présence d'un proxy ?
    Bonjour,

    J'utilise un script pour mettre à jour un programme via un site web.
    Ce script vérifie la présence ou non du proxy de ma boite (utilisation intra/extranet).
    Le souci c'est que j'ai sans doute fais une bourde dans mon code car après une mise à jour si je le relance celui ci semble tourner dans le vide...

    Voici le code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    #!/usr/bin/env python
    # -*- coding: ISO8859-1 -*-
    #
    # Imports et variables de base
    #
    import shutil, urllib2, tarfile, os.path, socket, struct, select, time
    from subprocess import Popen, PIPE
    from Tkinter import *
    from WsbPrefs import PrefUtil
    from signal import SIGQUIT
    ICMP_ECHO_REQUEST = 8
     
     
    # Classe MajProg_tk
    class MajProg_tk(Tk):
        def checksum(self, source_string):
            sum = 0
            countTo = (len(source_string)/2)*2
            count = 0
            while count<countTo:
                thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
                sum = sum + thisVal
                sum = sum & 0xffffffff
                count = count + 2
            if countTo<len(source_string):
                sum = sum + ord(source_string[len(source_string) - 1])
                sum = sum & 0xffffffff
            sum = (sum >> 16)  +  (sum & 0xffff)
            sum = sum + (sum >> 16)
            answer = ~sum
            answer = answer & 0xffff
            answer = answer >> 8 | (answer << 8 & 0xff00)
            return answer
     
        def recevoir_un_ping(self, mon_socket, ID, timeout):
            timeLeft = timeout
            while True:
                startedSelect = time.clock()
                whatReady = select.select([mon_socket], [], [], timeLeft)
                howLongInSelect = (time.clock() - startedSelect)
                if whatReady[0] == []: return
                timeReceived = time.clock()
                recPacket, addr = mon_socket.recvfrom(1024)
                icmpHeader = recPacket[20:28]
                type, code, checksum, packetID, sequence = struct.unpack("bbHHh", icmpHeader)
                if packetID == ID:
                    bytesInDouble = struct.calcsize("d")
                    timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
                    return timeReceived - timeSent
                timeLeft = timeLeft - howLongInSelect
                if timeLeft <= 0: return
     
        def envoyer_un_ping(self, mon_socket, dest_addr, ID):
            dest_addr  =  socket.gethostbyname(dest_addr)
            mon_checksum = 0
            header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, mon_checksum, ID, 1)
            bytesInDouble = struct.calcsize("d")
            data = (192 - bytesInDouble) * "Q"
            data = struct.pack("d", time.clock()) + data
            mon_checksum = self.checksum(header + data)
            header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(mon_checksum), ID, 1)
            packet = header + data
            mon_socket.sendto(packet, (dest_addr, 1))
     
        def do_one(self, dest_addr, timeout):
            icmp = socket.getprotobyname("icmp")
            try:
                mon_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
            except socket.error, (errno, msg):
                if errno == 1:
                    return
                    raise socket.error(msg)
                raise
            mon_ID = os.getpid() & 0xFFFF
            self.envoyer_un_ping(mon_socket, dest_addr, mon_ID)
            delay = self.recevoir_un_ping(mon_socket, mon_ID, timeout)
            mon_socket.close()
            return delay
     
        def verbose_ping(self, dest_addr, timeout = 2, count = 1):
            for i in xrange(count):
                try:
                    delay  =  self.do_one(dest_addr, timeout)
                except socket.gaierror, e:
                    return
                    break
                if delay is None: return False
                else: return True
     
        def UrlRecup(self, Source, Dest):
            try:
                src = urllib2.urlopen(Source)
            except urllib2.HTTPError: print 'Url non accessible'
            else:
                dst = open(Dest, 'w');
                shutil.copyfileobj(src, dst)
     
        def Extraire(self, Fichier):
            try:
                tar = tarfile.open(Fichier)
                tar.extractall()
                tar.close()
            except: print 'Erreur d\'extraction'
     
        def LanceProg(self):
            p = Popen('python ' + PathWasabi + 'wsbfm.py', shell=True)
            sts = os.waitpid(p.pid, 1)
            exit
     
        def LanceMaj(self):
            self.wiMajDispo.withdraw()
            MaCommande = 'python ' + PathWasabi + 'barrebleu.py ' + str(os.getpid())
            LaBarre = Popen(MaCommande, shell=True)
            sts = os.waitpid(LaBarre.pid, 1)
            try: os.remove('/tmp/revision.txt')
            except: pass
            self.UrlRecup('http://monsite/ressources/scripts/wasabi.tar.gz', 'wasabi.tar.gz')
            if os.path.isfile('/tmp/wasabi.tar.gz'):
                self.Extraire('/tmp/wasabi.tar.gz')
                os.remove('/tmp/wasabi.tar.gz')
            if os.path.isdir('/tmp/wasabi'):
                shutil.move('/tmp/wasabi/wasabi.py', '/tmp/wasabi.py')
                shutil.rmtree(PathWasabi)
                shutil.move('/tmp/wasabi', PathWasabi)
            self.LanceProg()
            exit()
     
        def QuitterMaj(self):
            try: os.remove('/tmp/revision.txt')
            except: pass
            self.LanceProg()
            exit()
     
        def Intercepte(self):
            try: os.remove('/tmp/revision.txt')
            except: pass
            app.destroy()
     
        def __init__(self, parent):
            Tk.__init__(self, parent)
            self.withdraw()
            self.parent = parent
            if os.path.isfile('/tmp/wasabi.tar.gz'):
                os.remove('/tmp/wasabi.tar.gz')
            if os.path.isfile('/tmp/wasabi.py'):
                os.remove('/tmp/wasabi.py')
            if os.path.isfile('/tmp/revision.txt'):
                os.remove('/tmp/revision.txt')
            if os.path.isdir('/tmp/wasabi'):
                shutil.rmtree('/tmp/wasabi')
            os.chdir('/tmp')
            self.initialize()
     
        def initialize(self):
            if self.verbose_ping("monproxy.com"):
                proxy_support = urllib2.ProxyHandler({"http":"monproxy.com:3128"})
                opener = urllib2.build_opener(proxy_support)
                urllib2.install_opener(opener)
            try: self.UrlRecup('http://monsite/ressources/scripts/revision.txt', 'revision.txt')
            except:
                ligneRev = 'Information maj non optenue'
                print LigneRev
            if os.path.isfile('/tmp/revision.txt'):
                RevRead = open('/tmp/revision.txt','rb')
                ligneRev = RevRead.readlines()[0][0:-2]
                RevRead.close()
            InstallRead = open(PathWasabi + 'wsbfm.py','rb')
            for items in (ligne for ligne in InstallRead.readlines() if ligne[:9] == '# Version'):
                LigneInstall = items[:15]
                break
            InstallRead.close()
            if ligneRev and ligneRev != LigneInstall and ligneRev[:9] == '# Version':
                self.wiMajDispo = Toplevel()
                self.wiMajDispo.protocol("WM_DELETE_WINDOW", self.Intercepte)
                self.wiMajDispo.title(u'Information de mise à jour')
                self.wiMajDispo.geometry("%dx%d+%d+%d" % (370,250, (self.wiMajDispo.winfo_screenwidth()-370)/2, (self.wiMajDispo.winfo_screenheight()-250)/2 ) )
                self.wiMajDispo.resizable(False,False)
                Label(self.wiMajDispo, fg="red", text= os.linesep + u'Une mise à jour est disponible sur le serveur.').pack(side=TOP)
                Label(self.wiMajDispo, fg="red", text=u'Souhaitez vous l\'installer ? (Recommandé)' + os.linesep).pack(side=TOP)
                Frame(self.wiMajDispo, height=2, bd=1, relief=SUNKEN).pack(side=TOP, fill=X, padx=5, pady=5)
                Label(self.wiMajDispo, fg="dark slate blue", text= os.linesep + u'Information de mise à jour :' + os.linesep).pack(side=TOP)
                Label(self.wiMajDispo, fg="dark slate blue", text=u'Version du programme actuellement installé : ' + LigneInstall[-13:]).pack(side=TOP)
                Label(self.wiMajDispo, fg="dark slate blue", text='Version disponible : ' + ligneRev[-13:] + os.linesep).pack(side=TOP)
                Frame(self.wiMajDispo, height=2, bd=1, relief=SUNKEN).pack(side=TOP, fill=X, padx=5, pady=10)
                Button(self.wiMajDispo, text="Installer", fg='red', activebackground='white', activeforeground='#2a7aff', command = self.LanceMaj).pack(side=LEFT, padx=8, pady=5)
                Button(self.wiMajDispo, text="Annuler", fg='dark slate blue', activebackground='white', activeforeground='#2a7aff', command = self.QuitterMaj).pack(side=RIGHT, padx=8, pady=5)
                self.wiMajDispo.bind('<Escape>', self.QuitterMaj)
            else:
                self.QuitterMaj()
     
    if __name__ == "__main__":
        UtilPref = PrefUtil()
        DicoAppliPref = UtilPref.Verif_Pref()
        PathWasabi = DicoAppliPref['10']
        app = MajProg_tk(None)
        app.mainloop()
    Si vous avez une idée...

    Merci d'avance
    Merci d'utiliser le forum pour les questions techniques.

  2. #2
    Membre éclairé
    Profil pro
    Ingénieur sécurité
    Inscrit en
    Février 2007
    Messages
    574
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : Ingénieur sécurité
    Secteur : Industrie

    Informations forums :
    Inscription : Février 2007
    Messages : 574
    Points : 751
    Points
    751
    Par défaut
    Salut,
    j'ai regardé en diagonale, mais ta méthode recevoir_un_ping n'est pas lancé dans un thread par la méthode do_one. Tu restes donc dans la boucle infinie while True.

    [Edit] En fait j'avais pas fait gaffe au timeout . Post A oublier donc.

Discussions similaires

  1. Vérification de la présence d'un exe
    Par Lechette dans le forum VB.NET
    Réponses: 2
    Dernier message: 21/11/2008, 10h43
  2. vérification auto de présence commit/rollback
    Par dinobogan dans le forum Adaptive Server Enterprise
    Réponses: 3
    Dernier message: 19/06/2008, 10h52
  3. [MySQL] Vérification de la présence d'une donnée déficiente
    Par sanaa16 dans le forum PHP & Base de données
    Réponses: 3
    Dernier message: 08/06/2008, 01h17
  4. Réponses: 9
    Dernier message: 08/01/2008, 13h58
  5. [MySQL] Vérification de la présence d'enregistrement avant insertion
    Par Odilon dans le forum PHP & Base de données
    Réponses: 7
    Dernier message: 28/09/2005, 15h30

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo