python写的学校上网检测程序

磊落不羁 by:磊落不羁 分类:办公自动化 时间:7个月前 阅读:30 评论:0
import platform
import subprocess
import webbrowser
import socket
import os
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
import html
import sys

# HTML模板内置
HTML_TEMPLATE = '''<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        body {{ font-family: 'Microsoft YaHei', Arial, sans-serif; text-align: center; background-color: #f5f5f5; margin: 0; padding: 0; height: 100vh; display: flex; flex-direction: column; justify-content: space-between; }}
        .header {{ background-color: #1e88e5; color: white; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }}
        .header h2 {{ margin: 0; font-size: 24px; font-weight: normal; }}
        .container {{ flex-grow: 1; display: flex; flex-direction: column; justify-content: center; padding: 20px; }}
        .status-box {{ background-color: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 30px; margin: 20px auto; max-width: 600px; }}
        h1 {{ margin: 0; padding: 20px; font-size: 24px; }}
        .icon {{ font-size: 48px; margin-bottom: 20px; }}
        .footer {{ background-color: #333; color: #fff; padding: 15px; font-size: 14px; }}
        .loading {{ display: none; }}
        .loading.show {{ display: block; }}
        .loading .dots {{ display: inline-block; animation: dots 1.5s infinite; }}
        @keyframes dots {{ 
            0%, 20% {{ content: '.'; }}
            40% {{ content: '..'; }}
            60% {{ content: '...'; }}
            80%, 100% {{ content: ''; }}
        }}
    </style>
    {refresh}
    <script>
        window.onload = function() {{
            document.querySelector('.loading').classList.add('show');
        }};
        window.onbeforeunload = function() {{
            fetch('/exit').then(() => {{
                window.onbeforeunload = null;
            }});
        }};
    </script>
</head>
<body>
    <div class="header">
        <h2>东海县实验中学网络连接检测程序</h2>
    </div>
    <div class="container">
        <div class="status-box">
            <div class="icon">{icon}</div>
            <h1 style="color: {color};">{message}</h1>
            
        </div>
    </div>
    <div class="footer">
        <p>© 2024 东海县实验中学信息中心 版权所有</p>
    </div>
</body>
</html>'''

def check_network():
    """
    检查网络连接状态
    步骤:
    1. 首先ping内网服务器(192.168.104.62)检查本地网络
    2. 如果本地网络正常,再ping百度检查外网连接
    
    返回值: (是否可以连接外网, 是否有本地网络)
    - (True, True): 外网和本地网络都正常
    - (False, True): 只有本地网络正常,需要认证
    - (False, False): 本地网络异常
    """
    # 检查本地网络(通过ping内网服务器)
    try:
        param = '-n' if platform.system().lower() == 'windows' else '-c'
        local_command = ['ping', param, '1', '192.168.104.62']
        subprocess.check_output(local_command, stderr=subprocess.STDOUT)
        # 如果能ping通本地服务器,再检查外网
        try:
            internet_command = ['ping', param, '1', 'www.baidu.com']
            subprocess.check_output(internet_command, stderr=subprocess.STDOUT)
            return True, True  # 外网和本地网络都正常
        except subprocess.CalledProcessError:
            return False, True  # 只有本地网络正常
    except subprocess.CalledProcessError:
        return False, False  # 本地网络也不正常

class NetworkStatusHandler(SimpleHTTPRequestHandler):
    """
    处理网络状态检测和页面显示的HTTP请求处理器
    功能:
    1. 响应网络状态检查请求
    2. 显示检测结果页面
    3. 处理程序退出请求
    """
    def do_GET(self):
        # 处理退出请求
        if self.path == '/exit':
            # 当收到退出请求时,关闭服务器并退出程序
            self.send_response(200)
            self.end_headers()
            # 使用线程来关闭服务器,避免死锁
            threading.Thread(target=self.server.shutdown).start()
            # 使用线程来退出程序
            threading.Thread(target=lambda: os._exit(0)).start()
            return
           
        # 处理正常页面请求
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()

        # 执行网络检测
        internet_ok, local_ok = check_network()
       
        # 根据检测结果设置显示内容
        if internet_ok:
            # 网络完全正常
            message = "这位老师,你的网络连接正常"
            color = "#2ecc71"  # 绿色
            icon = "✅"
            refresh = ""
        elif local_ok:
            # 需要认证
            message = "本地网络正常,正在跳转到认证页面..."
            color = "#f39c12"  # 橙色
            icon = "⚠️"
            refresh = '<meta http-equiv="refresh" content="3;url=http://www.baidu.com/">'
        else:
            # 本地网络异常
            message = "请检查网络连接\n(网线是否插好、网卡是否启用)"
            color = "#e74c3c"  # 红色
            icon = "❌"
            refresh = ""

        # 发送响应页面
        self.wfile.write(
            HTML_TEMPLATE.format(
                message=html.escape(message),
                color=color,
                icon=icon,
                refresh=refresh
            ).encode('utf-8')
        )

def main():
    """
    主程序入口
    功能:
    1. 启动HTTP服务器
    2. 打开浏览器显示检测页面
    3. 处理程序退出
    """
    # 创建并启动服务器
    server = HTTPServer(('localhost', 8000), NetworkStatusHandler)
    print("服务器已启动,正在打开浏览器...")
   
    # 在默认浏览器中打开检测页面
    webbrowser.open('http://localhost:8000')
   
    try:
        # 保持服务器运行
        server.serve_forever()
    except KeyboardInterrupt:
        # 处理Ctrl+C退出
        print("\n正在关闭服务器...")
        server.shutdown()
        server.server_close()
        sys.exit(0)

# 程序入口
if __name__ == "__main__":
    main()


非特殊说明,本文版权归原作者所有,转载请注明出处

本文地址:http://php.liulei.com.cn/?type=acticle&id=97

评论列表

发表评论

  • 昵称(必填)
  • 邮箱
  • 网址

TOP