python ping 连接_用Python ping服务器

博客探讨在Python中通过ICMP协议ping服务器的方法。给出一个适用于多操作系统、Python 2和3的函数,用subprocess.call替代os.system避免安全漏洞,通过构建ping命令并执行系统调用,根据返回值判断服务器是否响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?

解决方案

This function works in any OS (Unix, Linux, macOS, and Windows)

Python 2 and Python 3

EDITS:

By @radato os.system was replaced by subprocess.call. This avoids shell injection vulnerability in cases where your hostname string might not be validated.

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', host]

return subprocess.call(command) == 0

Note that, according to @ikrase on Windows this function will still return True if you get a Destination Host Unreachable error.

Explanation

The command is ping in both Windows and Unix-like systems.

The option -n (Windows) or -c (Unix) controls the number of packets which in this example was set to 1.

platform.system() returns the platform name. Ex. 'Darwin' on macOS.

subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l']).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值