温馨提示×

Debian日志中如何追踪网络连接

小樊
47
2025-03-02 06:29:38
栏目: 智能运维
Debian服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Debian系统中,可以使用多种工具和方法来追踪网络连接。以下是一些常用的方法:

使用 journalctl 查询系统日志

journalctl 是Debian系统中用于查询系统日志的工具。你可以使用以下命令来查看与网络连接相关的日志:

journalctl -xe

这将显示系统的所有日志,包括网络连接相关的信息。

使用 netstat 显示网络状态

netstat 命令用于显示网络连接、路由表和网络接口等信息。它可以帮助你了解系统当前的网络状态。例如,使用以下命令可以列出所有的网络连接:

netstat -tulns

使用 tcpdump 捕获网络数据包

tcpdump 是一款强大的网络抓包工具,可以在网络接口上捕获网络数据包,并根据用户定义的规则进行过滤和分析。例如,要捕获所有通过TCP端口23(Telnet默认端口)的数据包,可以使用以下命令:

sudo tcpdump -i any port 23

要停止捕获,请按 Ctrl+C

使用 iptables 记录连接日志

你可以使用 iptablessyslog-ng 来记录连接日志。首先,确保你的系统已经安装了 iptablessyslog-ng。如果没有安装,可以使用以下命令进行安装:

sudo apt-get update
sudo apt-get install iptables syslog-ng

接下来,配置 syslog-ng 以记录连接日志。编辑 /etc/syslog-ng/syslog-ng.conf 文件,添加以下内容:

# Load the default configuration files
source /etc/syslog-ng/syslog-ng.conf.default;

# Define a new source for connection logging
log_format connection 'remote_addr - remote_user [time] "request" ' 'status body_bytes_sent "http_referer" ' '"http_user_agent"';

# Define a destination for connection log
destination connection {
    file("/var/log/connections.log" mode "append");
    create_directory("/var/log");
    rotate(52);
    compress();
};

# Include the connection logging configuration in the default configuration
include "/etc/syslog-ng/connection.conf";

创建一个新的配置文件 /etc/syslog-ng/connection.conf,包含以下内容:

# Use the connection log format
define connection 'format';

# Match the connection logging format
filter connection /(?remote_addr\S) - (?remote_user\S) \[(?time\Srequest\Sstatus\d) (?body_bytes_sent\d) "(?http_referer\Shttp_user_agent\S)"/;

重启 syslog-ng 服务以应用更改:

sudo systemctl restart syslog-ng

使用 iptables 记录连接日志。你需要将 INPUT 链的默认策略设置为 DROP,以便只允许已建立的连接通过。编辑 /etc/iptables/rules.v4 文件,添加以下内容:

*filter:
    INPUT DROP
    [0:0]:FORWARD ACCEPT
    [0:0]:OUTPUT ACCEPT
    [0:0]-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    -A INPUT -p icmp -j ACCEPT
    -A INPUT -i lo -j ACCEPT
    -A INPUT -p tcp --dport 22 -j ACCEPT
    -A INPUT -p tcp --dport 80 -j ACCEPT
    -A INPUT -p tcp --dport 443 -j ACCEPT
    -A INPUT -j REJECT --reject-with icmp-host-prohibited
*nat:
    filter:
        -A PREROUTING -m state --state NEW -m tcp --dport 23 -j DNAT --to-destination 127.0.0.1:23
        -A POSTROUTING -j MASQUERADE
*mangle:
    -A PREROUTING -t nat -j MARK --set-mark 1
*raw:
    -A PREROUTING -m state --state NEW -p tcp --dport 23 -j MARK --set-mark 1
*security:
    filter:
        -A INPUT -m state --state NEW -m mark --mark 1 -j ACCEPT
*log:
    -A INPUT -m mark --mark 1 -j LOG --log-prefix "Connection attempt: " --log-level info

重启 iptables 服务以应用更改:

sudo systemctl restart netfilter-persistent

现在,Debian系统的 iptablessyslog-ng 应该已经配置好了,可以记录连接日志。连接日志将保存在 /var/log/connections.log 文件中。

通过这些方法,你可以有效地追踪和分析Debian系统中的网络连接情况。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Debian日志中如何识别网络连接问题

0