Python and ping
代码由 AI 生成。
1. 无法直接浏览器 ping ?试试这个!
适用:无法利用路由器的手机端等。
import subprocess
import platform
while True:
ip = input("\n请输入IP地址(输入q退出):").strip()
if ip.lower() == 'q':
break
if not ip:
continue
param = '-n' if platform.system().lower() == 'windows' else '-c'
print(f"正在测试 {ip} ...")
try:
result = subprocess.run(['ping', param, '1', ip],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
print(f"✅ {ip} 在线")
else:
print(f"❌ {ip} 离线或超时")
except Exception as e:
print(f"❌ 出错: {e}")
2.可以用?那就这个!
适用:可以使用浏览器的设备及环境。
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess
import platform
import urllib.parse
class PingHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith('/ping'):
# 解析URL参数
parsed = urllib.parse.urlparse(self.path)
params = urllib.parse.parse_qs(parsed.query)
ip = params.get('ip', [''])[0]
# 简单校验IP格式(防注入)
if not ip or not ip.replace('.','').replace(':','').isalnum():
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<h3>错误:无效IP地址</h3>'.encode('utf-8'))
return
# 执行ping命令
param = '-n' if platform.system().lower() == 'windows' else '-c'
try:
result = subprocess.run(['ping', param, '4', ip],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
status = f'✅ {ip} 在线'
detail = result.stdout
else:
status = f'❌ {ip} 离线或超时'
detail = result.stderr or result.stdout
except Exception as e:
status = '❌ 执行出错'
detail = str(e)
# 返回HTML结果
html = f'''
<html>
<body>
<h2>{status}</h2>
<pre>{detail}</pre>
<a href="/">← 返回</a>
</body>
</html>
'''
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html.encode('utf-8'))
else:
# 返回输入界面
html = '''
<html>
<body>
<h2>Ping工具</h2>
<form action="/ping" method="get">
<input type="text" name="ip" placeholder="输入IP地址,如 192.168.1.1">
<button type="submit">Ping</button>
</form>
</body>
</html>
'''
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html.encode('utf-8'))
if __name__ == '__main__':
print('服务器启动在 http://localhost:8000')
server = HTTPServer(('', 8000), PingHandler)
server.serve_forever()
posted on 2026-04-02 22:38 lkjy-coding 阅读(2) 评论(0) 收藏 举报
浙公网安备 33010602011771号