【实时监控主机与某个IP的网络连接情况】

Python脚本

写个脚本监控主机与某几个IP的连接情况,发现存在这种连接的,记录连接起始时间、源IP源、端口、目的IP、目的端口等信息

python 复制代码
import os
import time
import subprocess
from typing import List

# 目标IP列表
TARGET_IPS = ["192.168.1.1", "192.168.1.2", "192.168.1.3"]

# 输出文件名
OUTPUT_FILE = "connection_log.txt"

# 监控间隔(秒)
INTERVAL = 5

def get_connections(target_ips: List[str]) -> List[str]:
    connections = []
    netstat_output = subprocess.check_output("netstat -an", shell=True).decode("utf-8")
    for line in netstat_output.split("\n"):
        for ip in target_ips:
            if ip in line:
                connections.append(line)
    return connections

def get_process(port: str) -> str:
    try:
        process_output = subprocess.check_output(f"lsof -i :{port}", shell=True).decode("utf-8")
        return process_output.split("\n")[1].split()[0]
    except subprocess.CalledProcessError:
        return ""

# 清空输出文件
with open(OUTPUT_FILE, "w") as f:
    pass

# 实时监控
while True:
    with open(OUTPUT_FILE, "a") as f:
        connections = get_connections(TARGET_IPS)
        for conn in connections:
            parts = conn.split()
            src_ip, src_port = parts[3].rsplit(":", 1)
            dst_ip, dst_port = parts[4].rsplit(":", 1)
            process = get_process(src_port)

            if process:
                log_entry = f"源IP: {src_ip}, 源端口: {src_port}, 目的IP: {dst_ip}, 目的端口: {dst_port}, 进程: {process}"
                f.write(log_entry + "\n")
                print(log_entry)
    time.sleep(INTERVAL)

这个Python脚本与之前的bash脚本功能相同,会实时监控网络连接,并将源IP、源端口、目的IP、目的端口和使用源端口的进程记录到文件中。请注意,这个脚本在Linux系统上运行,可能需要使用root权限。with open(OUTPUT_FILE, "a") as f:语句在while True:循环的开始处,这意味着在每次循环开始时,文件都会被打开,并在循环结束时关闭。这样,无论是否检测到新的连接,都会在每次循环结束时保存文件。

Bash脚本

bash 复制代码
#!/bin/bash

# 目标IP列表,使用空格分隔
TARGET_IPS=("192.168.1.1" "192.168.1.2" "192.168.1.3")

# 输出文件名
OUTPUT_FILE="connection_log.txt"

# 监控间隔(秒)
INTERVAL=5

# 清空输出文件
> $OUTPUT_FILE

# 无限循环以实现实时监控
while true
do
  # 打开文件并追加日志
  exec 3>>$OUTPUT_FILE

  # 循环检查每个IP
  for ip in "${TARGET_IPS[@]}"
  do
    # 使用netstat找到与目标IP的连接
    connections=$(netstat -an | grep $ip)

    # 如果有连接,打印详细信息
    if [ ! -z "$connections" ]; then
      # 找到使用源端口的进程
      for conn in $connections
      do
        # 分割字符串以获取源IP、源端口和目的端口
        src_ip=$(echo $conn | awk '{print $4}' | cut -d ':' -f 1)
        src_port=$(echo $conn | awk '{print $4}' | cut -d ':' -f 2)
        dst_port=$(echo $conn | awk '{print $5}' | cut -d ':' -f 2)

        # 使用lsof找到使用该端口的进程
        process=$(lsof -i :$src_port | awk '{print $1}')

        # 输出到文件
        if [ ! -z "$process" ]; then
          log_entry="源IP: $src_ip, 源端口: $src_port, 目的IP: $ip, 目的端口: $dst_port, 进程: $process"
          echo $log_entry >&3
          echo $log_entry
        fi
      done
    fi
  done

  # 关闭文件
  exec 3>&-

  # 等待一段时间再检查
  sleep $INTERVAL
done

这个bash脚本会在每次检测到新的连接时,立即将连接信息写入到文件中。这是通过使用文件描述符3来打开文件并追加新的日志条目实现的。在每次循环开始时,文件会被打开,并在循环结束时关闭。这样,无论是否检测到新的连接,都会在每次循环结束时保存文件。

相关推荐
_AaronWong1 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
cxxcode1 小时前
I/O 多路复用:从浏览器到 Linux 内核
前端
用户5433081441941 小时前
AI 时代,前端逆向的门槛已经低到离谱 — 以 Upwork 为例
前端
JarvanMo1 小时前
Flutter 版本的 material_ui 已经上架 pub.dev 啦!快来抢先体验吧。
前端
恋猫de小郭2 小时前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
哀木2 小时前
给自己整一个 claude code,解锁编程新姿势
前端
程序员鱼皮2 小时前
GitHub 关注突破 2w,我总结了 10 个涨星涨粉技巧!
前端·后端·github
UrbanJazzerati2 小时前
Vue3 父子组件通信完全指南
前端·面试
是一碗螺丝粉2 小时前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
wuhen_n2 小时前
双端 Diff 算法详解
前端·javascript·vue.js