【实时监控主机与某个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来打开文件并追加新的日志条目实现的。在每次循环开始时,文件会被打开,并在循环结束时关闭。这样,无论是否检测到新的连接,都会在每次循环结束时保存文件。

相关推荐
cws200401几秒前
智能化弱电工程桥架、支吊架、线管、线盒安装要求-2
运维·网络·桥架
NEXT0611 分钟前
数组转树与树转数组
前端·数据结构·面试
We་ct14 分钟前
浏览器 Reflow(重排)与Repaint(重绘)全解析
前端·面试·edge·edge浏览器
笨笨狗吞噬者16 分钟前
【uniapp】小程序端解决分包的uni_modules打包后产物进入主包中的问题
前端·微信小程序·uni-app
WebInfra16 分钟前
Modern.js 3.0 发布:聚焦 Web 框架,拥抱生态发展
前端·javascript·前端框架
lannyjay23 分钟前
Windows 批处理脚本引用WinSCP指令,去指定服务器下载文件到本地。
网络·winscp·windows批处理
AngelPP24 分钟前
OpenClaw Memory 模块完整分析
前端·aigc·ai编程
grrrr_126 分钟前
【Linux】内网穿透 FTP 终极复现手册 (2026 版)--cpolar
linux·网络·内网穿透·ftp·cpolar
G皮T29 分钟前
【计算机网络】网络时间协议 NTP(二):X-Request-Start
网络·计算机网络·时钟同步·ntp·网络时间协议
ID_1800790547329 分钟前
淘宝商品详情 API 接口 item_get: 高效获取商品数据的技术方案
java·前端·数据库