{"id":194,"date":"2020-06-27T20:35:33","date_gmt":"2020-06-27T18:35:33","guid":{"rendered":"https:\/\/www.pythonparatodo.com\/?p=194"},"modified":"2020-06-28T11:51:32","modified_gmt":"2020-06-28T09:51:32","slug":"ping-con-python","status":"publish","type":"post","link":"https:\/\/www.pythonparatodo.com\/?p=194","title":{"rendered":"Ping con Python"},"content":{"rendered":"\n<p>Vamos a hacer ping a otras computadoras con Python3 y la librer\u00eda ping3.<\/p>\n\n\n\n<p>Lo primero es instalarla en nuestro sistema para ello hacemos uso del administrador de paquetes pip.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">pip install ping3<\/code><\/pre>\n\n\n\n<p>Hay que tener en cuenta que esta librer\u00eda necesita permisos de root para ejecutarse por lo que si queremos probar su funcionamiento desde el interprete interactivo de Python, deberemos de ejecutarlo como administrador. En el caso de Linux ser\u00eda as\u00ed:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">$ sudo python3<\/code><\/pre>\n\n\n\n<p>Dentro del interprete lo primero es importar el m\u00f3dulo, concretamente los m\u00e9todos a usar que son <strong>ping<\/strong> y <strong>verbose_ping<\/strong>.<\/p>\n\n\n\n<p>El primer m\u00e9todo hace un <strong>ping<\/strong> y devuelve el tiempo que se demora en responder la m\u00e1quina remota, en segundos. El segundo hace 4 intentos y muestra algo m\u00e1s de informaci\u00f3n.<\/p>\n\n\n\n<p>El c\u00f3digo en el interprete interactivo de Python 3 quedar\u00eda as\u00ed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">$ sudo python3\nPython 3.8.3 (v3.8.3:6f8c8320e9, May 13 2020, 16:29:34) \n[Clang 6.0 (clang-600.0.57)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from ping3 import ping , verbose_ping\n>>> ping('www.google.com')\n0.011239290237426758\n>>> verbose_ping('www.google.com')\nping 'www.google.com' ... 10ms\nping 'www.google.com' ... 11ms\nping 'www.google.com' ... 10ms\nping 'www.google.com' ... 10ms\n>>> <\/code><\/pre>\n\n\n\n<p>Si quisi\u00e9ramos ejecutar directamente el <strong>ping<\/strong> podr\u00edamos usar el m\u00f3dulo <strong>ping3<\/strong> directamente desde <strong>Python 3<\/strong> de la siguiente manera:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">$ sudo python3 -m ping3 'www.google.com'\nping 'www.google.com' ... 11ms\nping 'www.google.com' ... 10ms\nping 'www.google.com' ... 11ms\nping 'www.google.com' ... 11ms<\/code><\/pre>\n\n\n\n<p>Es posible pasar argumentos con nombre como <strong>timeout<\/strong> para especificar el tiempo de espera antes de indicar que no se alcanza el host o el <strong>ttl<\/strong> (time to live) que ser\u00e1 el tiempo durante el que circular\u00e1n los datos. Adem\u00e1s el m\u00e9todo devolver\u00e1 <strong>False<\/strong> si no puede resolver el nombre del host o <strong>None<\/strong> si no puede alcanzarlo o se acaba el tiempo.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">>>> print(ping3.ping('www.googlessss.com'))\nFalse\n>>> print(ping3.ping('192.168.0.23'))\nNone\n>>> print(ping3.ping('www.google.com'))\n0.011266946792602539\n>>> print(ping3.ping('www.google.es',timeout=1))\n0.01219320297241211\n>>> print(ping3.ping('www.google.com',timeout=0.0001))\nNone\n>>> \n>>> print(ping3.ping('www.google.es',ttl=5))\nNone\n>>> print(ping3.ping('www.google.es',ttl=10))\n0.012539863586425781\n>>> <\/code><\/pre>\n\n\n\n<p>Las excepciones est\u00e1n deshabilitadas por defecto, por lo que no se deber\u00eda producir ning\u00fan error en caso de timeout o host desconocido. Para habilitarlas y poder tratarlas hay que establecer el valor del par\u00e1metro <strong>EXCEPTIONS<\/strong> a True y gestionar las excepciones: <strong>Timeout<\/strong>, <strong>HostUnknown<\/strong> y <strong>TimeToLiveExpired<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">>>> import ping3\n>>> ping3.EXCEPTIONS = True\n>>> ping3.ping('192.168.0.240')\n    raise errors.DestinationUnreachable()\nerrors.DestinationUnreachable<\/code><\/pre>\n\n\n\n<p>Tambi\u00e9n podemos ver la ayuda de la librer\u00eda de la siguiente manera:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">$ sudo python3 -m ping3 --help\nusage: ping3 [-h] [-v] [-c COUNT] [-w TIMEOUT] [-i INTERVAL] [-I INTERFACE]\n             [-t TTL] [-l SIZE] [--debug] [--exceptions]\n             [DEST_ADDR [DEST_ADDR ...]]\n\nA pure python3 version of ICMP ping implementation using raw socket.\n\npositional arguments:\n  DEST_ADDR             The destination address, can be an IP address or a\n                        domain name. Ex. 192.168.1.1\/example.com.\n\noptional arguments:\n  -h, --help            show this help message and exit\n  -v, --version         show program's version number and exit\n  -c COUNT, --count COUNT\n                        How many pings should be sent. Default is 4.\n  -w TIMEOUT, --wait TIMEOUT\n                        Time to wait for a response, in seconds. Default is 4.\n  -i INTERVAL, --interval INTERVAL\n                        Time to wait between each packet, in seconds. Default\n                        is 0.\n  -I INTERFACE, --interface INTERFACE\n                        LINUX ONLY. The gateway network interface to ping\n                        from. Default is None.\n  -t TTL, --ttl TTL     The Time-To-Live of the outgoing packet. Default is\n                        64.\n  -l SIZE, --load SIZE  The ICMP packet payload size in bytes. Default is 56.\n  --debug               Turn on DEBUG mode.\n  --exceptions          Turn on EXCEPTIONS mode.\n\n!!Note: ICMP messages can only be sent from processes running as root.<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Vamos a hacer ping a otras computadoras con Python3 y la librer\u00eda ping3. Lo primero es instalarla en nuestro sistema &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[21,4],"tags":[22,86,6],"class_list":["post-194","post","type-post","status-publish","format-standard","hentry","category-networking","category-python","tag-networking","tag-ping3","tag-python3"],"_links":{"self":[{"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/posts\/194","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=194"}],"version-history":[{"count":4,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/posts\/194\/revisions"}],"predecessor-version":[{"id":199,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=\/wp\/v2\/posts\/194\/revisions\/199"}],"wp:attachment":[{"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=194"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=194"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonparatodo.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=194"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}