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

相关推荐
CaptainDrake6 分钟前
Vue:指令
前端·javascript·vue.js
软件技术NINI10 分钟前
HTML——基本标签
前端·javascript·html
qq_4165602015 分钟前
fmql之ubuntu添加dhcp服务
网络
卡兰芙的微笑34 分钟前
get_property --Cmakelist之中
前端·数据库·编辑器
覆水难收呀36 分钟前
三、(JS)JS中常见的表单事件
开发语言·前端·javascript
猿来如此呀44 分钟前
运行npm install 时,卡在sill idealTree buildDeps没有反应
前端·npm·node.js
hw_happy1 小时前
解决 npm ERR! node-sass 和 gyp ERR! node-gyp 报错问题
前端·npm·sass
小狮子安度因1 小时前
边缘智能-大模型架构初探
linux·网络
FHKHH1 小时前
计算机网络第二章:作业 1: Web 服务器
服务器·前端·计算机网络
视觉小鸟1 小时前
【JVM安装MinIO】
前端·jvm·chrome