import os
import time
import platform
import argparse
from datetime import datetime
import subprocess
def parse_arguments():
"""解析命令行参数"""
parser = argparse.ArgumentParser(description='Python实现的Ping工具')
parser.add_argument('host', help='要ping的目标地址')
parser.add_argument('-n', '--count', type=int, default=4,
help='ping的次数 (默认: 4)')
parser.add_argument('-t', '--continuous', action='store_true',
help='持续ping直到手动停止')
parser.add_argument('-w', '--timeout', type=int, default=2000,
help='超时时间(毫秒)')
return parser.parse_args()
def ping(host, count=4, timeout=2000):
"""执行ping命令"""
param = '-n' if platform.system().lower() == 'windows' else '-c'
timeout_param = '-w' if platform.system().lower() == 'windows' else '-W'
timeout_val = str(timeout // 1000) if platform.system().lower() == 'windows' else str(timeout / 1000)
command = ['ping', param, str(count), timeout_param, timeout_val, host]
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode('gbk')
except subprocess.CalledProcessError as e:
output = e.output.decode('gbk')
return output
def format_output_line(line, host):
"""格式化单行输出"""
line = line.replace('Reply from', '来自').replace('bytes=', '字节=')
line = line.replace('time=', '时间').replace('TTL=', 'TTL=')
line = line.replace('来自 {}'.format(host), '来自 {}'.format(host))
return line.strip()
def write_log(log_file, content):
"""写入日志文件"""
with open(log_file, 'a', encoding='utf-8') as f:
f.write(content + '\n')
def main():
args = parse_arguments()
script_dir = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_dir, 'ping_log.log')
print(f"开始ping测试 {args.host}")
print(f"日志文件: {log_file}")
print("按Ctrl+C停止...\n")
try:
if args.continuous:
while True:
output = ping(args.host, count=1, timeout=args.timeout)
for line in output.split('\n'):
if '来自' in line or 'Reply from' in line:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
formatted_line = format_output_line(line, args.host)
result = f"{timestamp}:{formatted_line}"
print(result)
write_log(log_file, result)
time.sleep(1)
else:
output = ping(args.host, count=args.count, timeout=args.timeout)
for line in output.split('\n'):
if '来自' in line or 'Reply from' in line:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
formatted_line = format_output_line(line, args.host)
result = f"{timestamp}:{formatted_line}"
print(result)
write_log(log_file, result)
except KeyboardInterrupt:
print("\nPing测试已停止")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == '__main__':
main()

zbj0916
- 粉丝: 0
最新资源
- 2025年铁路通信工技能竞赛理论知识题库和答案.docx
- 2025年团课考试题库与答案.docx
- 2025年特种设备安全管理人员安全考核考试题库(含答案).docx
- 2025年铁路通信工技能竞赛理论知识题库及答案.docx
- 2025年社工考试题附含答案.docx
- 2025年特种设备安全管理人员安全考核考试题库及答案.docx
- 2025年水处理基础知识考试试题(附含答案).docx
- 2025年铁路线路工技能竞赛考试题库 (附含答案).docx
- 2025年社会工作者考试真题库及答案.docx
- 2025年铁路监理工程师网络继续教育考试题(附答案).docx
- 2025年团员考试题库与参考答案.docx
- 2025年铁路线路工技能竞赛考试题库 (含答案).docx
- 2025年软件资格考试软件评测师(中级)(基础知识、应用技术)合卷试卷和答案.docx
- 2025年司法局招聘司法所协理员历年考试试题与答案.docx
- 2025年软件资格考试软件评测师(中级)(基础知识、应用技术)合卷试卷与答案.docx
- 2025年上海浦东区高三一模数学试卷和答案.docx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


