Lors de la réalisation d’un script, vous pouvez avoir besoin de tester la connexion à un site, voici une petite fonction pour le faire.
Lors de la réalisation d’un script en python, j’ai eu besoin de tester la connexion à un site web avant de continuer la suite de mon script.
Importer la bibliothèque socket
Commencer votre script par importer la bibliothèque nécessaire :
#!/usr/bin/python3 # -*-coding:Utf-8 -* import socket
Réalisation de la fonction pour tester la connexion
Voici le script python :
def is_connected(REMOTE_SERVER): try: # see if we can resolve the host name -- tells us if there is a DNS listening host = socket.gethostbyname(REMOTE_SERVER) # connect to the host -- tells us if the host is actually reachable s = socket.create_connection((host, 80), 2) return True except: pass return False
Appel de la fonction de test de connexion
Dans votre script, saisir :
site = 'www.google.fr' if is_connected(site): print "Site disponible" else: print "Site indisponible"
Le code complet :
#!/usr/bin/python3 # -*-coding:Utf-8 -* import socket def is_connected(REMOTE_SERVER): try: # see if we can resolve the host name -- tells us if there is a DNS listening host = socket.gethostbyname(REMOTE_SERVER) # connect to the host -- tells us if the host is actually reachable s = socket.create_connection((host, 80), 2) return True except: pass return False site = 'www.google.fr' if is_connected(site): print "Site disponible" else: print "Site indisponible"
Pour le reste bon script.