Python实现批量Ping检测终端在线状态

沈亦白
沈亦白
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍使用Python脚本在Linux环境下批量检测指定网段内终端在线状态的方法。通过遍历IP地址并执行ping命令,解析返回结果判断连通性,最终将时间与状态信息写入文本文件。该方法适用于简单的网络可用性检查,代码逻辑清晰但执行效率受限于串行处理。

本文分享一个在Linux环境下运行的Python示例,虽然代码结构较为简单,但具备实际可用性。

主要实现流程如下:

首先,将目标网段内的所有IP地址存储至数组中(也可通过for循环直接逐个处理)。

接着,遍历该数组,对每个IP地址依次执行ping操作。

根据ping命令返回的字符串内容,判断目标主机是否连通。

最后,将检测结果保存至txt文件中。

以下是具体代码实现(此处未进行代码简化处理)。

#!/usr/bin/env python
# coding: utf8
 
import time
import subprocess
import codecs
import os
import re
 
# telnet host
def pingComputer(host, statusFile):
	status1 = 'ping success'
	status2 = 'ping faild'
	errorStr = 'Destination'
	for ipAdd in host:
		print ("get: " +ipAdd + " status")
		# get now time
		nowTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		p = os.popen("ping -q -c 2 -r " + ipAdd)
		line = p.read()
		
		# judge errorstr in line if
		if errorStr in line:
			writeToText(nowTime, ipAdd, status2, statusFile)
		else:
			writeToText(nowTime, ipAdd, status1, statusFile)
 
		
# write status information to txt
def writeToText(nowTime, ipAdd, status, statusFile):
	s_text = 'TIME:' + nowTime + '\t' + 'IP:' + ipAdd + '\t' + 'STATUS:' + status + '\r\n'
	
	if '0' == judgeFile(statusFile):
		with open(statusFile, 'a') as f:
			f.write(s_text)
			f.close()
	if '1' == judgeFile(statusFile):
		with open(statusFile, 'w') as f:
			f.write(s_text)
			f.close()
		
		
			
# Determine whether statusFile exists 
# 0: exists
# 1: no exists
def judgeFile(statusFile):
	if os.path.exists(statusFile):
		return '0'
	else:
		return '1'
			
if __name__ == "__main__":
	IpFirst = '192.168.1.'
	# ip:1~254
	host = []
	for j in range(254):
 		host.append(IpFirst + str(j + 1))
	# write file
	statusFile = '/root/UpStatus.txt'
	pingComputer(host, statusFile)

该方式采用串行逐个ping的策略,判断过程相对耗时。

以上即为Python检查ping终端的完整方法,供读者参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表