Linux日志管理

操作系统内核和程序记录了发生的事件日志,这些日志用于审核系统并解决问题。日志以文本方式保存在/var/log目录中。可以使用普通文本实用程序(如less和tail)检查这些日志。

Linux 内置了基于Syslog协议的标准日志记录系统。许多程序使用此系统记录事件并将其组织到日志文件中。CentOS 7 中systemd-journald和rsyslog服务负责处理syslog消息。

  • systemd-journald 服务,是操作系统事件记录体系结构的核心,收集系统各方面事件消息,包括内核、引导过程早期阶段的输出、守护程序启动和运行时的输出、syslog事件,然后将它们重组为标准格式,并写入结构化的索引系统日志中。
  • rsyslog 服务,读取systemd-journald日志,然后记录到日志文件,或根据自己的配置将日志保存到不同的文件中,以及转发给其他程序。

rsyslog日志配置

rsyslog服务配置

配置文件位置
  • 主配置: /etc/rsyslog.conf。主配置文件中以下配置作用是引入从配置目录中配置文件。

    # Include all config files in /etc/rsyslog.d/
    include(file="/etc/rsyslog.d/*.conf" mode="optional")
    
  • 从配置:/etc/rsyslog.d/*.conf。

日志记录规则

每一条日志消息都可以通过消息类型facility和priority分类,参考rsyslog.conf(5)。

日志记录规则格式: facility+连接符号+priority 处理方式

facility(设备类型)
在这里插入图片描述
priority(优先级)
在这里插入图片描述
连接符
在这里插入图片描述
处理方式

  • 记录到文件
  • 发送到终端
  • 转发给其他服务器
配置文件内容

/etc/rsyslog.conf中部分内容如下:

# rsyslog configuration file

# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html

#### MODULES ####

# The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal
#$ModLoad imklog # reads kernel messages (the same are read from journald)
#$ModLoad immark  # provides --MARK-- message capability

# Provides UDP syslog reception
#$ModLoad imudp
#$UDPServerRun 514

在这里插入图片描述

查看日志内容

[root@server ~ 16:59:00]# tail -f /var/log/messages
Sep 15 16:26:35 server NetworkManager[668]: <info>  [1757924795.1453] device (ens36): state change: disconnected -> prepare (reason 'none', sys-iface-state: 'managed')
Sep 15 16:26:35 server NetworkManager[668]: <info>  [1757924795.1455] device (ens36): state change: prepare -> config (reason 'none', sys-iface-state: 'managed')
Sep 15 16:26:35 server NetworkManager[668]: <info>  [1757924795.1482] device (ens36): state change: config -> ip-config (reason 'none', sys-iface-state: 'managed')
Sep 15 16:26:35 server NetworkManager[668]: <info>  [1757924795.1532] device (ens36): state change: ip-config -> ip-check (reason 'none', sys-iface-state: 'managed')

日志内容说明:

  • Nov 10 10:23:34,代表日志产生时间。
  • centos7,产生日志的主机名。
  • systemd-logind,产生日志的进程。
  • 最后一个区域是日志内容,例如,“Removed session 15.”。
[root@server ~ 16:59:28]# tail -f /var/log/secure
Sep 15 15:53:48 server polkitd[669]: Unregistered Authentication Agent for unix-process:94654:2534119 (system bus name :1.95, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)
Sep 15 15:54:28 server polkitd[669]: Registered Authentication Agent for unix-process:95439:2538128 (system bus name :1.96 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8)

补充

  • 虽然系统提供了日志服务,但并不会记录所有内容。

  • 系统中的应用程序是否使用 rsyslog 服务记录日志,取决于应用程序设计。

    例如:

    • httpd 服务使用自己的日志记录。

    • sshd 服务使用 rsyslog 服务记录登录和退出日志。

[root@server ~ 17:00:40]# grep AUTHPRIV /etc/ssh/sshd_config
SyslogFacility AUTHPRIV
[root@server ~ 17:01:30]# grep ^authpri /etc/rsyslog.conf 
authpriv.*                                              /var/log/secure
[root@server ~ 17:01:37]#  tail -1 /var/log/secure 
Sep 15 16:19:27 server sshd[121107]: pam_unix(sshd:session): session closed for user root

systemd-journald 日志

systemd-journald 日志持久化保存

systemd-journald 配置文件 /etc/systemd/journald.conf

详情参考 journald.conf(5)

Storage参数,更改参数值后需要重启systemd-journald服务。

  • persistent:将日志存储在/var/log/journal目录中,这可在系统重启后持久保留。如果/var/log/journal目录不存在,systemd-journald服务会创建它。
  • volatile:将日志存储在易失性/run/log/journal目录中。因为/run文件系统是临时的,仅存在于运行时内存中,存储在其中的数据(包括系统日志)不会在系统启后持久保留。
  • auto:如果/var/log/journal目录存在,那么rsyslog会使用持久存储,否则使用易失性存储。如果未设置Storage参数,此为默认操作。
[root@server ~ 17:06:21]# cat /etc/systemd/journald.conf 
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.

systemd-journald 日志分析

systemd-journald日志是以二进制方式存储,不能使用常规文本工具查看,查看所有日志条目,默认使用less查看文档

故障模拟

配置文件丢失
[root@server ~ 17:08:47]# mv /etc/ssh/sshd_config .
[root@server ~ 17:10:23]# systemctl restart sshd

处理过程:通过日志发现 /etc/ssh/sshd_config: No such file or directory,文件丢失。

# 重启服务时,动态监控日志
[root@server ~ 17:10:27]# journalctl -f
-- Logs begin at 一 2025-09-15 08:51:26 CST. --
915 17:10:27 server.wyb.cloud sshd[61579]: Received signal 15; terminating.
915 17:10:27 server.wyb.cloud systemd[1]: Stopping OpenSSH server daemon...
915 17:10:27 server.wyb.cloud systemd[1]: Stopped OpenSSH server daemon.
915 17:10:27 server.wyb.cloud systemd[1]: Starting OpenSSH server daemon...
915 17:10:27 server.wyb.cloud sshd[54154]: /etc/ssh/sshd_config: No such file or directory
915 17:10:27 server.wyb.cloud systemd[1]: sshd.service: main process exited, code=exited, status=1/FAILURE
915 17:10:27 server.wyb.cloud systemd[1]: Failed to start OpenSSH server daemon.
915 17:10:27 server.wyb.cloud systemd[1]: Unit sshd.service entered failed state.
915 17:10:27 server.wyb.cloud systemd[1]: sshd.service failed.
915 17:10:27 server.wyb.cloud polkitd[669]: Unregistered Authentication Agent for unix-process:54147:2993967 (system bus name :1.115, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)
# 移动回来,并重启服务

Linux时间管理

系统时间设置

tzselect

[root@server ~ 17:11:24]# tzselect 
Please identify a location so that time zone rules can be set correctly.
Please select a continent or ocean.
 1) Africa
 2) Americas
 3) Antarctica
 4) Arctic Ocean
 5) Asia
 6) Atlantic Ocean
 7) Australia
 8) Europe
 9) Indian Ocean
10) Pacific Ocean
11) none - I want to specify the time zone using the Posix TZ format.
#? 5
Please select a country.
 1) Afghanistan           18) Israel                35) Palestine
 2) Armenia               19) Japan                 36) Philippines
 3) Azerbaijan            20) Jordan                37) Qatar
 4) Bahrain               21) Kazakhstan            38) Russia
 5) Bangladesh            22) Korea (North)         39) Saudi Arabia
 6) Bhutan                23) Korea (South)         40) Singapore
 7) Brunei                24) Kuwait                41) Sri Lanka
 8) Cambodia              25) Kyrgyzstan            42) Syria
 9) China                 26) Laos                  43) Taiwan
10) Cyprus                27) Lebanon               44) Tajikistan
11) East Timor            28) Macau                 45) Thailand
12) Georgia               29) Malaysia              46) Turkmenistan
13) Hong Kong             30) Mongolia              47) United Arab Emirates
14) India                 31) Myanmar (Burma)       48) Uzbekistan
15) Indonesia             32) Nepal                 49) Vietnam
16) Iran                  33) Oman                  50) Yemen
17) Iraq                  34) Pakistan
#? 9
Please select one of the following time zone regions.
1) Beijing Time
2) Xinjiang Time
#? 1

The following information has been given:

        China
        Beijing Time

Therefore TZ='Asia/Shanghai' will be used.
Local time is now:      Mon Sep 15 17:12:53 CST 2025.
Universal Time is now:  Mon Sep 15 09:12:53 UTC 2025.
Is the above information OK?
1) Yes
2) No
#? 1

You can make this change permanent for yourself by appending the line
        TZ='Asia/Shanghai'; export TZ
to the file '.profile' in your home directory; then log out and log in again.

Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Shanghai

自动对时-chronyd服务

# 修改对时服务器
[root@server ~ 17:12:56]# vim /etc/chrony.conf

# 启用并启动chronyd服务
[root@server ~ 17:12:56]# systemctl enable chronyd --now

# 验证对时情况
[root@server ~ 14:02:47]# chronyc sources -v
210 Number of sources = 1

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                  2   6   117    15    -57us[+1354us] +/-   70ms
[root@server ~ 14:03:38]# ping -c 1 ntp.aliyun.com
PING ntp.aliyun.com (203.107.6.88) 56(84) bytes of data.
64 bytes from 203.107.6.88 (203.107.6.88): icmp_seq=1 ttl=128 time=128 ms

部署时间服务器

chrony既可以作为客户端,也可以作为服务端(为客户端提供对时服务)。

服务端
[root@server ~]# vim /etc/chrony.conf
# 最后添加两条记录

# 配置监听地址
bindaddress 192.168.48.104

# 配置允许哪些网段主机同步
allow 192.168.48.0/24

root@server ~]# systemctl restart chronyd

# 停止防火墙服务
[root@server ~]# systemctl stop firewalld.service
客户端
# 修改对时服务器
[root@client ~]# vim /etc/chrony.conf
# 与单个服务器 10.1.8.10 对时
server 192.168.48.104 iburst

[root@server ~ 17:14:43]# chronyc sources -v
210 Number of sources = 1

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                  2   8   377    67    +85us[+2048us] +/-   71ms

Linux网络管理

网络基础回顾

OSI模型

在这里插入图片描述

  1. 物理层:提供为建立、维护和拆除物理链路所需要的机械的、电气的、功能的和规程的特性;有关的物理链路上传输非结构的位流以及故障检测指示。
  2. 数据链路层:在网络层实体间提供数据发送和接收的功能和过程;提供数据链路的流控。
  3. 网络层:控制分组传送系统的操作、路由选择、拥护控制、网络互连等功能,它的作用是将具体的物理传送对高层透明。
  4. 传输层:提供建立、维护和拆除传送连接的功能;选择网络层提供最合适的服务;在系统之间提供可靠的透明的数据传送,提供端到端的错误恢复和流量控制。
  5. 会话层:提供两进程之间建立、维护和结束会话连接的功能;提供交互会话的管理功能,如三种数据流方向的控制,即一路交互、两路交替和两路同时会话模式 。
  6. 表示层:代表应用进程协商数据表示;完成数据转换、格式化和文本压缩。
  7. 应用层:提供OSI用户服务,例如事务处理程序、文件传送协议和网络管理等。

TCP/IP 模型

在这里插入图片描述
在这里插入图片描述

IPV4 地址

在这里插入图片描述
在这里插入图片描述

IPV4 路由

在这里插入图片描述

查看网络配置

网卡信息

网卡名称:

  • 旧名称,eth0 eth1 (Ethernet)
  • 新名称,根据网卡的拓扑类型命名。例如ens192,eno4。

**linux网络接口传统的名称为eth0 eth1 eth2 …ethN。**然而这种机制会引起一些问题,例如网络接口的增加和删除。

在rhel7或者更高版本中,接口命名规则如下

  • 前2个字符:Ethernet 接口以en开头,WLAN接口以wl开头,WWAN接口以ww开头。
  • 下一个字符:o(onboard)代表板载设备,s(slot)代表PCI热插拔,p代表pci接口网卡。
  • 最后N表示index ID或者port。

例如

  • eno1,代表Ethernet 类型、板载设备、端口号是1的网卡。

  • wlp4s0,代表位于PCI总线4上插槽0中的WLAN卡。如果该卡是一个多功能设备(具有多个端口或者具有一些其他功能)。示例,enp0s1f0代表位于PCI总线0上插槽1中的以太网卡的功能0。

  • 如果无法分配固定接口名,将使用传统方式ethN命名。

查看 link,ip,dns,路由

[root@server ~ 17:22:52]# ip -br link 
lo               UNKNOWN        00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP> 
ens33            UP             00:0c:29:ac:e5:e4 <BROADCAST,MULTICAST,UP,LOWER_UP> 
ens36            UP             00:0c:29:ac:e5:ee <BROADCAST,MULTICAST,UP,LOWER_UP> 

[root@server ~ 17:22:59]# ip addr show ens33
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:ac:e5:e4 brd ff:ff:ff:ff:ff:ff
    inet 192.168.48.104/24 brd 192.168.48.255 scope global noprefixroute ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::4384:83fc:2337:4e54/64 scope link tentative noprefixroute dadfailed 
       valid_lft forever preferred_lft forever
    inet6 fe80::c536:ec97:91ef:48fb/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

[root@server ~ 17:23:17]# ip route
default via 192.168.48.2 dev ens33 proto static metric 100 
192.168.48.0/24 dev ens33 proto kernel scope link src 192.168.48.104 metric 100 
192.168.48.0/24 dev ens36 proto kernel scope link src 192.168.48.110 metric 101 

[root@server ~ 17:23:31]# cat /etc/resolv.conf 
# Generated by NetworkManager
search 223.6.6.6 wyb.cloud
nameserver 223.5.5.5

网络连通性测试

ping测试

# ping 测试,选项-c控制ping次数,选项-w控制ping超时时间
[root@server ~ 17:23:43]#  ping baidu.com -c 4 -w 2
PING baidu.com (220.181.7.203) 56(84) bytes of data.
64 bytes from 220.181.7.203 (220.181.7.203): icmp_seq=1 ttl=128 time=122 ms
64 bytes from 220.181.7.203 (220.181.7.203): icmp_seq=2 ttl=128 time=128 ms

--- baidu.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 122.916/125.461/128.007/2.570 ms

mtr路由追踪

server.wyb.cloud (0.0.0.0)                                                  Mon Sep 15 17:26:06 2025
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                                                            Packets               Pings
 Host                                                     Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 192.168.48.2                                           0.0%    18    0.1   0.1   0.1   0.2   0.0
 2. ???

ss工具

/etc/services 文件存储常见端口和服务对应关系。

[root@server ~ 17:26:09]# vim /etc/services
gopher          70/tcp                          # Internet Gopher
gopher          70/udp
netrjs-1        71/tcp                          # Remote Job Service
netrjs-1        71/udp                          # Remote Job Service
netrjs-2        72/tcp                          # Remote Job Service
netrjs-2        72/udp                          # Remote Job Service
netrjs-3        73/tcp                          # Remote Job Service
netrjs-3        73/udp                          # Remote Job Service
netrjs-4        74/tcp                          # Remote Job Service
netrjs-4        74/udp                          # Remote Job Service
finger          79/tcp
finger          79/udp

ss 命令用于查看系统中网络状态信息。

以前使用 **netstat **查看网络状态信息,使用方法等效与 ss 命令

# 默认显示是 ESTAB 状态
[root@server ~ 17:27:16]# ss | grep :ssh
tcp    ESTAB      0      52     192.168.48.104:ssh                  192.168.48.1:55688   
# 只看 LISTEN,包含IPv4和IPv6
[root@server ~ 17:28:25]# ss -l |grep :ssh
tcp    LISTEN     0      128     *:ssh                   *:*                    
tcp    LISTEN     0      128      [::]:ssh                    [::]:*  

模拟环境

[root@server ~ 15:50:29]# systemctl start nginx.service 
[root@server ~ 15:51:00]# cd /usr/share/nginx/html/
[root@server html 15:51:24]#  ls
404.html  50x.html  en-US  icons  img  index.html  nginx-logo.png  poweredby.png
[root@server html 15:51:29]# mv index.html index.html.ori
[root@server html 15:51:45]#  echo "Hello World" > index.html
[root@server html 15:52:09]# curl http://192.168.48.104
Hello World
[root@server html 15:55:40]# systemctl start httpd 
[root@server html 15:56:02]# systemctl status httpd.service 
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since 一 2025-09-15 15:54:38 CST; 1min 48s ago

index.html index.html.ori
[root@server html 15:51:45]# echo “Hello World” > index.html
[root@server html 15:52:09]# curl http://192.168.48.104
Hello World
[root@server html 15:55:40]# systemctl start httpd
[root@server html 15:56:02]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: active (running) since 一 2025-09-15 15:54:38 CST; 1min 48s ago

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐