0

0

我要求DeepSeek编码我的python,这是没有人制作的

心靈之曲

心靈之曲

发布时间:2025-01-31 19:32:14

|

585人浏览过

|

来源于dev.to

转载

高级python脚本:带有实时可视化的ai驱动网络异常检测器

此脚本组合:

使用scapy的实时网络流量分析。

使用scikit-learn。

基于机器学习的异常检测。 使用matplotlib和plotly。

使用大熊猫和电子邮件库的自动报告。>

脚本监视网络流量,检测异常(例如,不寻常的流量模式),并生成实时可视化和电子邮件警报。

import time
import pandas as pd
import numpy as np
from scapy.all import sniff, IP, TCP
from sklearn.ensemble import IsolationForest
import matplotlib.pyplot as plt
import plotly.express as px
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from threading import Thread

# Global variables
network_data = []
anomalies = []
model = IsolationForest(contamination=0.01)  # Anomaly detection model

# Email configuration
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USER = 'your_email@gmail.com'
EMAIL_PASSWORD = 'your_password'
ALERT_EMAIL = 'recipient_email@example.com'

def capture_traffic(packet):
    """
    Capture network traffic and extract features.
    """
    if IP in packet:
        src_ip = packet[IP].src
        dst_ip = packet[IP].dst
        protocol = packet[IP].proto
        length = len(packet)
        timestamp = time.time()

        # Append to network data
        network_data.append([timestamp, src_ip, dst_ip, protocol, length])

def detect_anomalies():
    """
    Detect anomalies in network traffic using Isolation Forest.
    """
    global network_data, anomalies
    while True:
        if len(network_data) > 100:  # Wait for enough data
            df = pd.DataFrame(network_data, columns=['timestamp', 'src_ip', 'dst_ip', 'protocol', 'length'])
            X = df[['protocol', 'length']].values

            # Train the model and predict anomalies
            model.fit(X)
            preds = model.predict(X)
            df['anomaly'] = preds

            # Extract anomalies
            anomalies = df[df['anomaly'] == -1]
            if not anomalies.empty:
                print("Anomalies detected:")
                print(anomalies)
                send_alert_email(anomalies)
                visualize_anomalies(anomalies)

            # Clear old data
            network_data = network_data[-100:]  # Keep last 100 entries
        time.sleep(10)  # Check for anomalies every 10 seconds

def visualize_anomalies(anomalies):
    """
    Visualize anomalies using Plotly.
    """
    fig = px.scatter(anomalies, x='timestamp', y='length', color='protocol',
                     title='Network Anomalies Detected')
    fig.show()

def send_alert_email(anomalies):
    """
    Send an email alert with detected anomalies.
    """
    msg = MIMEMultipart()
    msg['From'] = EMAIL_USER
    msg['To'] = ALERT_EMAIL
    msg['Subject'] = 'Network Anomaly Alert'

    body = "The following network anomalies were detected:\n\n"
    body += anomalies.to_string()
    msg.attach(MIMEText(body, 'plain'))

    try:
        server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
        server.starttls()
        server.login(EMAIL_USER, EMAIL_PASSWORD)
        server.sendmail(EMAIL_USER, ALERT_EMAIL, msg.as_string())
        server.quit()
        print("Alert email sent.")
    except Exception as e:
        print(f"Failed to send email: {e}")

def start_capture():
    """
    Start capturing network traffic.
    """
    print("Starting network traffic capture...")
    sniff(prn=capture_traffic, store=False)

if __name__ == "__main__":
    # Start traffic capture in a separate thread
    capture_thread = Thread(target=start_capture)
    capture_thread.daemon = True
    capture_thread.start()

    # Start anomaly detection
    detect_anomalies()

它的工作原理

网络流量捕获:


>脚本使用scapy捕获实时网络流量并提取源ip,目标ip,协议和数据包长度等功能。

>异常检测:


>它使用scikit-learn的隔离森林算法来检测网络流量中的异常模式。

实时可视化:

使用plotly实时可视化检测到的异常。

>

电子邮件警报:

如果检测到异常,则脚本将发送带有详细信息的电子邮件警报。

多线程:

Beyond商城 2008修改版
Beyond商城 2008修改版

感谢广大歌迷长期以来对网站的支持和帮助,很多朋友曾经问我要过这个商城程序,当时由于工作比较忙,一直没空整理,现在好啦,已全部整理好了,在这里提供给有需要的朋友,没有任何功能限制,完全可以使用的,只是有些商品的广告需自己修改一下,后台没有办法修改,需要有HTML基础才可以修改,另外,哪位朋友在使用的时候,发现了BUG请与我们联系,大家共同改进,谢谢!后台管理地址:http://你的域名/admin/

下载

流量捕获和异常检测在单独的线程中运行以提高效率。>

相关专题

更多
python开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

715

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

625

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

739

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

617

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1235

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

547

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

575

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

698

2023.08.11

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号