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

相关推荐
weiwx834 分钟前
Nginx location 和 proxy_pass 配置详解
服务器·网络·nginx
陈天伟教授26 分钟前
人工智能应用- 预测新冠病毒传染性:04. 中国:强力措施遏制疫情
前端·人工智能·安全·xss·csrf
zayzy1 小时前
前端八股总结
开发语言·前端·javascript
今天减肥吗1 小时前
前端面试题
开发语言·前端·javascript
Rabbit_QL1 小时前
【前端UI行话】前端 UI 术语速查表
前端·ui·状态模式
小码哥_常1 小时前
一文带你吃透Android BLE蓝牙开发全流程
前端
小码哥_常1 小时前
从“新老交锋”看Retrofit与Ktor
前端
小J听不清2 小时前
CSS 外边距(margin)全解析:取值规则 + 实战用法
前端·javascript·css·html·css3
还是大剑师兰特2 小时前
Stats.js 插件详解及示例(完全攻略)
前端·大剑师·stats
前端小超超2 小时前
Vue计算属性computed:可写与只读的区别
前端·javascript·vue.js