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

Python脚本

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

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脚本

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

相关推荐

  1. 实时监控主机某个IP网络连接情况

    2024-04-04 17:40:02       21 阅读
  2. 网卡情况下如何获取连接ip地址c++

    2024-04-04 17:40:02       22 阅读
  3. 修改uboot连接主机ip地址

    2024-04-04 17:40:02       23 阅读
  4. 前端监听页面中某些异常情况

    2024-04-04 17:40:02       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-04 17:40:02       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-04 17:40:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-04 17:40:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-04 17:40:02       18 阅读

热门阅读

  1. 在Go语言中如何调试

    2024-04-04 17:40:02       17 阅读
  2. C语言——字符函数和字符串函数(下)

    2024-04-04 17:40:02       18 阅读
  3. springboot实现七牛云的文件上传下载

    2024-04-04 17:40:02       16 阅读
  4. Linux常见命令简介

    2024-04-04 17:40:02       14 阅读
  5. 探索Django REST框架构建强大的API

    2024-04-04 17:40:02       17 阅读
  6. redis-乐观锁Watch使用方法

    2024-04-04 17:40:02       18 阅读