【发布时间】:2021-08-19 13:58:20
【问题描述】:
在 Python 中,有没有办法在不登录特定站点服务器的情况下 ping 交换机、路由器等网络设备?
【问题讨论】:
标签: python python-3.x networking ping
在 Python 中,有没有办法在不登录特定站点服务器的情况下 ping 交换机、路由器等网络设备?
【问题讨论】:
标签: python python-3.x networking ping
是的。在 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)
【讨论】: