Ping在Python的网站?

发布于 2025-01-23 04:34:03 字数 30 浏览 4 评论 0原文

如何使用Python ping网站或IP地址?

How do I ping a website or IP address with Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

亽野灬性zι浪 2025-01-30 04:34:03

请参阅此 matthew dixon cowles Jens Diemer 。另外,请记住,Python需要root才能在Linux中产生ICMP(IE ping)插座。

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

源代码本身很容易读取,请参阅verbose_pingping.do的实现。

See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

The source code itself is easy to read, see the implementations of verbose_ping and of Ping.do for inspiration.

故事↓在人 2025-01-30 04:34:03

根据您想实现的目标,您可能最容易调用系统ping命令。.

使用子过程模块是这样做的最佳方法,尽管您必须记住在不同的操作系统上ping命令有所不同!

import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out

您不必担心壳式字符。例如..

host = "google.com; `echo test`

..将不会 执行回声命令。

现在,要获得PING结果,您可以解析OUT变量。示例输出:

round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms

示例REGEX:

import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')

再次,请记住输出会根据操作系统(甚至是ping的版本)而变化。这不是理想的,但是在许多情况下都可以正常工作(您知道脚本将运行的机器)

Depending on what you want to achieve, you are probably easiest calling the system ping command..

Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!

import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out

You don't need to worry about shell-escape characters. For example..

host = "google.com; `echo test`

..will not execute the echo command.

Now, to get the ping results, you could parse the out variable. Example output:

round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms

Example regex:

import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')

Again, remember the output will vary depending on the operating system (and even the version of ping). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)

夜雨飘雪 2025-01-30 04:34:03

您可能会发现 noah礼物的演示使用python创建敏捷命令行工具。在其中,他结合了子过程,队列和线程,以开发能够同时启动主机并加快过程的解决方案。以下是基本版本,然后他添加命令行解析和其他一些功能。可以找到此版本的代码

#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret = subprocess.call("ping -c 1 %s" % ip,
            shell=True,
            stdout=open('/dev/null', 'w'),
            stderr=subprocess.STDOUT)
        if ret == 0:
            print "%s: is alive" % ip
        else:
            print "%s: did not respond" % ip
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for ip in ips:
    queue.put(ip)
#Wait until worker threads are done to exit    
queue.join()

这里 =“ noreferrer”> python for Unix和linux系统管理

href =“ https://rads.stackoverflow.com/amzn/click/com/0596515820” rel .com/amzn/click/com/0596515820" rel="noreferrer">http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret = subprocess.call("ping -c 1 %s" % ip,
            shell=True,
            stdout=open('/dev/null', 'w'),
            stderr=subprocess.STDOUT)
        if ret == 0:
            print "%s: is alive" % ip
        else:
            print "%s: did not respond" % ip
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for ip in ips:
    queue.put(ip)
#Wait until worker threads are done to exit    
queue.join()

He is also author of: Python for Unix and Linux System Administration

http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

歌入人心 2025-01-30 04:34:03

很难说您的问题是什么,但是有一些选择。

如果您的意思是使用ICMP PING协议从字面上执行请求,则可以获取ICMP库并直接执行Ping请求。 Google“ python icmp”查找类似的东西 icmplib 。您可能想查看 scapy 也是如此。

这将比使用os.System(“ ping” + ip)要快得多。

如果您的意思是一般“ ping”一个框以查看是否已经启动,则可以使用端口7上的回声协议。

对于Echo,您可以使用套接字库库打开IP地址和端口7。 \ n“ ),然后阅读答复。

如果您的意思是“ ping”网站以查看网站是否正在运行,则必须在端口80上使用HTTP协议。

对于或正确检查Web服务器,您可以使用 urllib2 打开特定的URL。 (/index.html总是很流行的)并阅读响应。

“ ping”(包括“ Traceroute”和“手指”)还有更多的潜在含义。

It's hard to say what your question is, but there are some alternatives.

If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.

This will be much faster than using os.system("ping " + ip ).

If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.

For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n") and then read the reply.

If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.

For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html is always popular) and read the response.

There are still more potential meaning of "ping" including "traceroute" and "finger".

狼亦尘 2025-01-30 04:34:03

最简单的答案是:

import os
os.system("ping google.com") 

Most simple answer is:

import os
os.system("ping google.com") 
温柔戏命师 2025-01-30 04:34:03

我以这种方式做了类似的事情,这是一种灵感:

import urllib
import threading
import time

def pinger_urllib(host):
  """
  helper function timing the retrival of index.html 
  TODO: should there be a 1MB bogus file?
  """
  t1 = time.time()
  urllib.urlopen(host + '/index.html').read()
  return (time.time() - t1) * 1000.0


def task(m):
  """
  the actual task
  """
  delay = float(pinger_urllib(m))
  print '%-30s %5.0f [ms]' % (m, delay)

# parallelization
tasks = []
URLs = ['google.com', 'wikipedia.org']
for m in URLs:
  t = threading.Thread(target=task, args=(m,))
  t.start()
  tasks.append(t)

# synchronization point
for t in tasks:
  t.join()

I did something similar this way, as an inspiration:

import urllib
import threading
import time

def pinger_urllib(host):
  """
  helper function timing the retrival of index.html 
  TODO: should there be a 1MB bogus file?
  """
  t1 = time.time()
  urllib.urlopen(host + '/index.html').read()
  return (time.time() - t1) * 1000.0


def task(m):
  """
  the actual task
  """
  delay = float(pinger_urllib(m))
  print '%-30s %5.0f [ms]' % (m, delay)

# parallelization
tasks = []
URLs = ['google.com', 'wikipedia.org']
for m in URLs:
  t = threading.Thread(target=task, args=(m,))
  t.start()
  tasks.append(t)

# synchronization point
for t in tasks:
  t.join()
草莓味的萝莉 2025-01-30 04:34:03

这是使用subprocess的简短片段。 check_call方法要么返回0以取得成功,要么提出异常。这样,我不必解析ping的输出。我正在使用shlex来拆分命令行参数。

  import subprocess
  import shlex

  command_line = "ping -c 1 www.google.comsldjkflksj"
  args = shlex.split(command_line)
  try:
      subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
      print "Website is there."
  except subprocess.CalledProcessError:
      print "Couldn't get a ping."

Here's a short snippet using subprocess. The check_call method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using shlex to split the command line arguments.

  import subprocess
  import shlex

  command_line = "ping -c 1 www.google.comsldjkflksj"
  args = shlex.split(command_line)
  try:
      subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
      print "Website is there."
  except subprocess.CalledProcessError:
      print "Couldn't get a ping."
私野 2025-01-30 04:34:03

我开发了一个我认为可以为您提供帮助的图书馆。它称为ICMPLIB(与Internet上可以找到的同名其他任何代码无关),并且是Python中ICMP协议的纯粹实现。

它完全面向对象,并具有简单的功能,例如经典的ping,乘法和示踪剂,以及对于那些想要基于ICMP协议开发应用程序的人的低级类和插座。

以下是其他一些亮点:

  • 可以在没有根特权的情况下运行。
  • 您可以自定义许多参数,例如ICMP数据包的有效载荷和流量类(QoS)。
  • 跨平台:在Linux,MacOS和Windows上测试。
  • 快速,几乎不需要CPU / RAM资源,与子过程进行的呼叫不同。
  • 轻巧,不依赖任何其他依赖项。

要安装它(需要Python 3.6+):

pip3 install icmplib

这是ping函数的一个简单示例:

host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)

if host.is_alive:
    print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
else:
    print(f'{host.address} is dead')

如果您想使用库中的库中,则将“特权”参数设置为false。

您可以在项目页面上找到完整的文档:
https://github.com/valentinbelyn/icmplib

希望您能找到这个库。

I develop a library that I think could help you. It is called icmplib (unrelated to any other code of the same name that can be found on the Internet) and is a pure implementation of the ICMP protocol in Python.

It is completely object oriented and has simple functions such as the classic ping, multiping and traceroute, as well as low level classes and sockets for those who want to develop applications based on the ICMP protocol.

Here are some other highlights:

  • Can be run without root privileges.
  • You can customize many parameters such as the payload of ICMP packets and the traffic class (QoS).
  • Cross-platform: tested on Linux, macOS and Windows.
  • Fast and requires few CPU / RAM resources unlike calls made with subprocess.
  • Lightweight and does not rely on any additional dependencies.

To install it (Python 3.6+ required):

pip3 install icmplib

Here is a simple example of the ping function:

host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)

if host.is_alive:
    print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
else:
    print(f'{host.address} is dead')

Set the "privileged" parameter to False if you want to use the library without root privileges.

You can find the complete documentation on the project page:
https://github.com/ValentinBELYN/icmplib

Hope you will find this library useful.

听不够的曲调 2025-01-30 04:34:03

读取文件名,文件包含每行的一个URL,如以下:

http://www.poolsaboveground.com/apache/hadoop/core/
http://mirrors.sonic.net/apache/hadoop/core/

use命令:

python url.py urls.txt

获取结果:

Round Trip Time: 253 ms - mirrors.sonic.net
Round Trip Time: 245 ms - www.globalish.com
Round Trip Time: 327 ms - www.poolsaboveground.com

源代码(url.py):

import re
import sys
import urlparse
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            hostname = urlparse.urlparse(host).hostname
            if hostname:
                pa = PingAgent(hostname)
                pa.start()
            else:
                continue

class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self)        
        self.host = host

    def run(self):
        p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
        m = re.search('Average = (.*)ms', p.stdout.read())
        if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
        else: print 'Error: Invalid Response -', self.host


if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        content = f.readlines() 
    Pinger(content)

read a file name, the file contain the one url per line, like this:

http://www.poolsaboveground.com/apache/hadoop/core/
http://mirrors.sonic.net/apache/hadoop/core/

use command:

python url.py urls.txt

get the result:

Round Trip Time: 253 ms - mirrors.sonic.net
Round Trip Time: 245 ms - www.globalish.com
Round Trip Time: 327 ms - www.poolsaboveground.com

source code(url.py):

import re
import sys
import urlparse
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            hostname = urlparse.urlparse(host).hostname
            if hostname:
                pa = PingAgent(hostname)
                pa.start()
            else:
                continue

class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self)        
        self.host = host

    def run(self):
        p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
        m = re.search('Average = (.*)ms', p.stdout.read())
        if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
        else: print 'Error: Invalid Response -', self.host


if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        content = f.readlines() 
    Pinger(content)
雨轻弹 2025-01-30 04:34:03
import subprocess as s
ip=raw_input("Enter the IP/Domain name:")
if(s.call(["ping",ip])==0):
    print "your IP is alive"
else:
    print "Check ur IP"
import subprocess as s
ip=raw_input("Enter the IP/Domain name:")
if(s.call(["ping",ip])==0):
    print "your IP is alive"
else:
    print "Check ur IP"
坦然微笑 2025-01-30 04:34:03

如果您想在Python中真正玩一些东西,可以使用Scapy:

from scapy.all import *
request = IP(dst="www.google.com")/ICMP()
answer = sr1(request)

在我看来,这比某些时髦的子过程要好得多(并且完全跨平台)。另外,您可以像拥有数据包一样拥有有关答案(序列ID .....)的更多信息(序列ID .....)。

If you want something actually in Python, that you can play with, have a look at Scapy:

from scapy.all import *
request = IP(dst="www.google.com")/ICMP()
answer = sr1(request)

That's in my opinion much better (and fully cross-platform), than some funky subprocess calls. Also you can have as much information about the answer (sequence ID.....) as you want, as you have the packet itself.

爺獨霸怡葒院 2025-01-30 04:34:03

在Python 3上,您可以使用 ping3

from ping3 import ping, verbose_ping
ip-host = '8.8.8.8'
if not ping(ip-host):
    raise ValueError('{} is not available.'.format(ip-host))

On python 3 you can use ping3.

from ping3 import ping, verbose_ping
ip-host = '8.8.8.8'
if not ping(ip-host):
    raise ValueError('{} is not available.'.format(ip-host))
萝莉病 2025-01-30 04:34:03

使用系统ping命令ping ping osth of主机:

import re
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            pa = PingAgent(host)
            pa.start()

class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self)        
        self.host = host

    def run(self):
        p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
        m = re.search('Average = (.*)ms', p.stdout.read())
        if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
        else: print 'Error: Invalid Response -', self.host


if __name__ == '__main__':
    hosts = [
        'www.pylot.org',
        'www.goldb.org',
        'www.google.com',
        'www.yahoo.com',
        'www.techcrunch.com',
        'www.this_one_wont_work.com'
       ]
    Pinger(hosts)

using system ping command to ping a list of hosts:

import re
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            pa = PingAgent(host)
            pa.start()

class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self)        
        self.host = host

    def run(self):
        p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
        m = re.search('Average = (.*)ms', p.stdout.read())
        if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
        else: print 'Error: Invalid Response -', self.host


if __name__ == '__main__':
    hosts = [
        'www.pylot.org',
        'www.goldb.org',
        'www.google.com',
        'www.yahoo.com',
        'www.techcrunch.com',
        'www.this_one_wont_work.com'
       ]
    Pinger(hosts)
女皇必胜 2025-01-30 04:34:03

您可以在Windows和Linux 在这里

You can find an updated version of the mentioned script that works on both Windows and Linux here

中性美 2025-01-30 04:34:03

使用子过程ping命令将其解码,因为响应是二进制的:

import subprocess
ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
result = ping_response.decode('utf-8')
print(result)

using subprocess ping command to ping decode it because the response is binary:

import subprocess
ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
result = ping_response.decode('utf-8')
print(result)
彻夜缠绵 2025-01-30 04:34:03

您可以尝试使用插座以获取网站的IP,并使用scrapy将ICMP ping授予IP。

import gevent
from gevent import monkey
# monkey.patch_all() should be executed before any library that will
# standard library
monkey.patch_all()

import socket
from scapy.all import IP, ICMP, sr1


def ping_site(fqdn):
    ip = socket.gethostbyaddr(fqdn)[-1][0]
    print(fqdn, ip, '\n')
    icmp = IP(dst=ip)/ICMP()
    resp = sr1(icmp, timeout=10)
    if resp:
        return (fqdn, False)
    else:
        return (fqdn, True)


sites = ['www.google.com', 'www.baidu.com', 'www.bing.com']
jobs = [gevent.spawn(ping_site, fqdn) for fqdn in sites]
gevent.joinall(jobs)
print([job.value for job in jobs])

you might try socket to get ip of the site and use scrapy to excute icmp ping to the ip.

import gevent
from gevent import monkey
# monkey.patch_all() should be executed before any library that will
# standard library
monkey.patch_all()

import socket
from scapy.all import IP, ICMP, sr1


def ping_site(fqdn):
    ip = socket.gethostbyaddr(fqdn)[-1][0]
    print(fqdn, ip, '\n')
    icmp = IP(dst=ip)/ICMP()
    resp = sr1(icmp, timeout=10)
    if resp:
        return (fqdn, False)
    else:
        return (fqdn, True)


sites = ['www.google.com', 'www.baidu.com', 'www.bing.com']
jobs = [gevent.spawn(ping_site, fqdn) for fqdn in sites]
gevent.joinall(jobs)
print([job.value for job in jobs])
杀手六號 2025-01-30 04:34:03

如果您只想检查IP上的机器是否处于活动状态,则只能使用Python插座。

import socket
s = socket.socket()
try:
    s.connect(("192.168.1.123", 1234)) # You can use any port number here
except Exception as e:
    print(e.errno, e)

现在,根据显示的错误消息(或错误号码),您可以确定机器是否活动。

If you only want to check whether a machine on an IP is active or not, you can just use python sockets.

import socket
s = socket.socket()
try:
    s.connect(("192.168.1.123", 1234)) # You can use any port number here
except Exception as e:
    print(e.errno, e)

Now, according to the error message displayed (or the error number), you can determine whether the machine is active or not.

十二 2025-01-30 04:34:03

使用此功能已在Python 2.7上进行了测试,并且可以正常工作,如果成功并在失败时返回False,则以毫秒为单位返回PING时间。

import platform,subproccess,re
def Ping(hostname,timeout):
    if platform.system() == "Windows":
        command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
    else:
        command="ping -i "+str(timeout)+" -c 1 " + hostname
    proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
    matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
    if matches:
        return matches.group(1)
    else: 
        return False

Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.

import platform,subproccess,re
def Ping(hostname,timeout):
    if platform.system() == "Windows":
        command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
    else:
        command="ping -i "+str(timeout)+" -c 1 " + hostname
    proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
    matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
    if matches:
        return matches.group(1)
    else: 
        return False
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文