【问题标题】:Pinging network devices in python在python中ping网络设备
【发布时间】:2021-08-19 13:58:20
【问题描述】:

在 Python 中,有没有办法在不登录特定站点服务器的情况下 ping 交换机、路由器等网络设备?

【问题讨论】:

标签: python python-3.x networking ping


【解决方案1】:

是的。在 here 的解决方案之上工作。如果您只想“ping”,只需使用函数 ping({ insert IP})

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', '-t','1', host]

    return subprocess.call(command) == 0

#Simple test to see how many IPs are allocated by my router
IPV4_in_router=[f"192.168.86.{x}" for x in range(1,254)]
used=[]
for x in IPV4_in_router:
    y=ping(x)
    if y:
        used.append(x)
print(used)

【讨论】:

  • 您可能需要考虑使用 *.com/a/32684938/2525388,因为 ping() 函数似乎来自那里。
  • @Red,感谢您的回复.. 我知道 ping 功能,但它不适用于私有 IP.. 如果我们需要从本地系统 ping 任何私有 IP 怎么办?跨度>
  • @Jung-suk 私有 IP 有效。子网内的任何东西都应该能够连接。确保您没有连接到 VPN,否则您使用的 IP 与物理路由器不同。
最近更新 更多