系统管理员的 20 个 Linux 命令

Linux 系统管理常用命令详解

Linux 系统提供了大量的指令和实用工具,它们可以帮助您高效地执行系统管理任务。

系统管理员的职责包括软件的安装与运行、访问控制、监控、确保系统可用性、数据备份与恢复,当然还有紧急情况处理。 😉

本文将回顾 Linux 系统管理员在日常工作中经常用到的一些命令。

系统信息 (uname)

使用带有 -a 参数的 uname 命令可以显示系统信息。该命令会输出内核名称、内核版本、内核发行版、主机名、处理器类型以及硬件平台等信息。

[email protected]:~$ uname -a
Linux ubuntu18 5.3.0-1028-azure #29~18.04.1-Ubuntu SMP Fri Jun 5 14:32:34 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

输出内容解释如下:

kernel name: Linux
hostname: ubuntu18
kernel release: 5.3.0-1028-azure
kernel version: #29~18.04.1-Ubuntu SMP Fri Jun 5 14:32:34 UTC 2020
machine hardware name: x86_64
processor: x86_64
hardware-platform: x86_64
operating system: GNU/Linux

磁盘空间 (df)

使用 df 命令可以查看文件系统的大小和可用空间。默认情况下,该命令会以 1KB 为单位显示输出。

[email protected]:~$ df
Filesystem     1K-blocks    Used Available Use% Mounted on
udev              437208       0    437208   0% /dev
tmpfs              91100     692     90408   1% /run
/dev/sda1       30309264 2383952  27908928   8% /
....

使用 -h 参数可以以更易读的格式显示输出,如 MB 和 GB。

[email protected]:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            427M     0  427M   0% /dev
tmpfs            89M  692K   89M   1% /run
/dev/sda1        29G  2.3G   27G   8% /
tmpfs           445M     0  445M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           445M     0  445M   0% /sys/fs/cgroup
/dev/sda15      105M  3.6M  101M   4% /boot/efi
/dev/sdb1       3.9G   16M  3.7G   1% /mnt
tmpfs            89M     0   89M   0% /run/user/1001

要忽略某些文件系统,例如 tmpfs,以便使输出更简洁,可以使用 -x 参数。

[email protected]:~$ df -h -x tmpfs
Filesystem      Size  Used Avail Use% Mounted on
udev            427M     0  427M   0% /dev
/dev/sda1        29G  2.3G   27G   8% /
/dev/sda15      105M  3.6M  101M   4% /boot/efi
/dev/sdb1       3.9G   16M  3.7G   1% /mnt

要只列出特定的文件系统类型,可以使用 -t 参数。例如,只查看 ext4 文件系统:

[email protected]:~$ df -h -t ext4
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        29G  2.3G   27G   8% /
/dev/sdb1       3.9G   16M  3.7G   1% /mnt

使用 --total 参数可以添加一行显示总计:

[email protected]:~$ df -h -t ext4 --total
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        29G  2.3G   27G   8% /
/dev/sdb1       3.9G   16M  3.7G   1% /mnt
total            33G  2.3G   31G   8% -

目录空间占用 (du)

要查看目录的磁盘空间使用情况,可以使用 du 命令。例如,查看 /var/log 目录的磁盘空间使用情况。使用 -h 参数可以以人类可读的格式显示输出。

[email protected]:~$ sudo du -h /var/log
24K    /var/log/Microsoft/Azure/NetworkWatcherAgent/Logs
28K    /var/log/Microsoft/Azure/NetworkWatcherAgent
32K    /var/log/Microsoft/Azure
36K    /var/log/Microsoft
60K    /var/log/apt
4.0K    /var/log/samba
177M    /var/log/journal/0f4f926f583b4691af7de11025b19ff6
177M    /var/log/journal
...
204M    /var/log

要只查看总使用量,可以使用 -s (摘要)参数。

[email protected]:~$ sudo du -hs /var/log
204M    /var/log

内存信息 (free)

使用 free 命令可以查看系统的总内存、已用内存和可用内存。使用 -h 参数可以以人类可读的格式显示输出。

[email protected]:~$ free -h
              total        used        free      shared  buff/cache   available
Mem:           889M        272M        100M        712K        517M        443M
Swap:            0B          0B          0B
total - 总安装内存 (memtotal + swaptotal)
used - 已使用内存
free - 未使用内存 (memfree + swapfree)
buffers - 内核缓冲区使用的内存
cache - 页面缓存使用的内存
buff/cache - 缓冲区和缓存的总和
available - 估计可用于启动新应用程序的内存,无需交换

进程状态 (ps)

使用 ps 命令可以显示系统上运行的进程的状态信息。要查看用户 ubuntu 拥有的所有进程,可以使用 -u 参数和用户名:

[email protected]:~$ ps -u ubuntu
   PID TTY          TIME CMD
  7804 ?        00:00:00 systemd
  7805 ?        00:00:00 (sd-pam)
  7940 ?        00:00:00 sshd
  7941 pts/0    00:00:00 bash
  8111 ?        00:00:00 sshd
  8112 pts/1    00:00:00 bash
 13868 ?        00:00:00 sshd
 13869 pts/2    00:00:00 bash
 13885 pts/0    00:00:00 man
 13895 pts/0    00:00:00 pager
 18111 pts/2    00:00:00 man
 18121 pts/2    00:00:00 pager
 18485 pts/1    00:00:00 ps

要查看所有进程,可以使用 aux 参数运行 ps:

[email protected]:~$ ps aux
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          1  0.0  0.7 160076  7020 ?        Ss   Jun29   0:34 /sbin/init
root          2  0.0  0.0      0     0 ?        S    Jun29   0:00 [kthreadd]
root          3  0.0  0.0      0     0 ?        I<   Jun29   0:00 [rcu_gp]
root          4  0.0  0.0      0     0 ?        I<   Jun29   0:00 [rcu_par_gp]
root          6  0.0  0.0      0     0 ?        I<   Jun29   0:00 [kworker/0:0H-kb]
....

输出内容含义:

标题 意义
PID 进程标识号
%CPU 进程使用的 CPU 时间百分比
%MEM 进程正在使用的 RAM 百分比
VSZ 正在使用的虚拟内存 (KB)
RSS 进程正在使用的物理内存 (KB)
TTY 与进程关联的终端
STAT 进程状态。 R – 运行或准备运行, S – 睡眠, I – 空闲, T – 停止, Z – 僵尸, D – 等待磁盘 I/O, X – 死机, W – 换出, N – 低优先级进程, < –高优先级进程

动态进程 (top)

ps 命令显示进程状态的快照,而 top 则显示不断更新的系统进程列表(默认每三秒更新一次)。它按照进程的 CPU 活动排序。

top 命令的输出由两部分组成:顶部的系统摘要和按 CPU 活动排序的进程表。

top - 14:25:32 up 44 days, 11:37,  1 user,  load average: 0.00, 0.00, 0.00
Tasks: 114 total,   1 running,  59 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.3 us,  0.0 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :   910992 total,   101208 free,   274712 used,   535072 buff/cache
KiB Swap:        0 total,        0 free,        0 used.   458492 avail Mem

   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
 50497 ubuntu    20   0   44528   3944   3368 R  0.7  0.4   0:00.15 top
     1 root      20   0  160076   7020   4400 S  0.0  0.8   0:34.85 systemd
     2 root      20   0       0      0      0 S  0.0  0.0   0:00.08 kthreadd
     3 root       0 -20       0      0      0 I  0.0  0.0   0:00.00 rcu_gp
     4 root       0 -20       0      0      0 I  0.0  0.0   0:00.00 rcu_par_gp
     6 root       0 -20       0      0      0 I  0.0  0.0   0:00.00 kworker/0:+
     9 root       0 -20       0      0      0 I  0.0  0.0   0:00.00 mm_percpu_+

系统摘要中的一些字段解释:

up – 正常运行时间。 自计算机上次启动以来的时间。
load average – 平均负载是指等待运行的进程数,小于 1.0 表示机器不忙。有3个值。 第一个是过去 60 秒的平均值,第二个是过去 5 分钟的平均值,第三个是过去 15 分钟的平均值。
%CPU(s) – CPU 活动描述。
0.3 us,用户: 0.3% 的 CPU 用于用户进程。
0.0 sy, 系统: 0.0% CPU 正用于系统进程。
0.0 ni,不错: 低优先级(好)进程正在使用 0.0% CPU
99.7 id,空闲: 99.7% CPU 空闲
0.0 wa,IO 等待: 0.0% CPU 正在等待 I/O
0.0 hi: 花在硬件中断上的时间
0.0 si: 花在软件中断上的时间
0.0 st: 虚拟机管理程序从此 VM 获取时间石

进程表字段解释:

PID 进程标识号
USER 进程所有者
PR 优先
NI 不错的价值
VIRT 进程使用的虚拟内存 (KB)
RES 进程使用的物理内存
SHR 进程使用的共享内存
S 进程状态。R – 运行,S – 睡眠,I – 空闲,T – 停止,Z – 僵尸,D – 等待磁盘 I/O,W- 换出,X – 死机
%CPU 进程使用的 CPU 时间百分比
%MEM 物理内存进程正在使用
TIME+ 进程使用的总 CPU 时间
COMMAND 程序名称

top 运行时,您可以发出许多命令。 按 h? 查看可以在 top 运行时运行的命令。 按 k 杀死一个进程。 按 q 退出 top

DNS 查询 (dig)

dig 是一个强大的 DNS 查询工具。它的使用格式如下:

dig <DNS server> <domain> <query-type>

解释:

  • <DNS server> 是您要查询的 DNS 服务器名称
  • <domain> 是您要查询的域名
  • <query-type> 是您想知道的记录的类型——A、MX、NS、SOA 等。

要抑制详细输出,可以使用 +short 参数。

要查看 google.com 的 A 记录,可以使用:

[email protected]:~$ dig google.com +short
172.217.164.174

要查看 google.com 的 MX 记录,可以使用:

[email protected]:~$ dig google.com MX  +short
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
20 alt1.aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
30 alt2.aspmx.l.google.com.

如果需要在 Internet 上查询 DNS 记录,可以使用 DNS 查询工具。

已登录用户 (who & w)

who 命令显示已登录的用户。

[email protected]:~$ who
ubuntu   pts/0        2020-08-14 17:28 (183.83.211.129)
ubuntu   pts/1        2020-08-14 17:58 (183.83.211.129)

w 命令显示当前登录的用户及其进程。 标题显示当前时间、系统正常运行时间、登录用户数和系统平均负载。

[email protected]:~$ w
 18:07:33 up 46 days, 15:19,  2 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN    IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    183.83.211.129   17:28    2.00s  0.10s  0.00s w
ubuntu   pts/1    183.83.211.129   17:58    9:07   0.05s  0.01s vi

下一部分显示用户名、终端和他们登录的远程 IP、登录时间、空闲时间、JCPU、PCPU 和他们正在运行的程序。 JCPU 是连接到 tty 的所有进程使用的时间,而 PCPU 是当前进程使用的时间。

文件归档 (tar)

使用 GNU tar 可以将多个文件归档到一个文件中。

例如,在 myfiles 目录中创建一个目录 myfiles 和三个文件 a.txtb.txtc.txt

[email protected]:~$ mkdir myfiles ; touch myfiles/{a.txt,b.txt,c.txt}

现在创建一个名为 allfiles.tar 的归档文件,其中包含 myfiles 目录中的所有文件:

[email protected]:~$ tar -cvf allfiles.tar myfiles
myfiles/
myfiles/c.txt
myfiles/a.txt
myfiles/b.txt

列出当前目录中的所有文件。您可以看到 myfiles 目录和 allfiles.tar 归档文件:

[email protected]:~$ ls
allfiles.tar  myfiles

可以使用 -x 参数解压缩归档文件。 因此,解压 allfiles.tar

[email protected]:~$ tar -xvf allfiles.tar
myfiles/
myfiles/c.txt
myfiles/a.txt
myfiles/b.txt

您也可以使用 -z 参数压缩归档文件。这将创建一个用 gzip 压缩的归档文件。

[email protected]:~$ tar -zcvf allfiles.tar.gz myfiles
myfiles/
myfiles/c.txt
myfiles/a.txt
myfiles/b.txt
[email protected]:~$ ls
allfiles.tar.gz  myfiles

要解压缩压缩的归档文件,请使用 -z-x 参数。

[email protected]:~$ tar -zxvf allfiles.tar.gz
myfiles/
myfiles/c.txt
myfiles/a.txt
myfiles/b.txt

文本搜索 (grep)

grep 用于在一个文件或一组文件中搜索模式。 它会打印与该模式匹配的所有行。例如,要在 /etc/apache2/apache2.conf 中搜索包含 “ServerRoot” 的行:

[email protected]:~$ grep ServerRoot /etc/apache2/apache2.conf
# ServerRoot: The top of the directory tree under which the server's
#ServerRoot "/etc/apache2"

要搜索目录中的所有文件,请使用 *。要在子目录中包含搜索,请使用 -r (递归)参数。因此,要在 /etc/apache2 的所有文件中搜索包含模式 “VirtualHost” 的所有行:

[email protected]:~$ cd /etc/apache2
[email protected]:/etc/apache2$ grep -r VirtualHost *
apache2.conf:# If you do not specify an ErrorLog directive within a <VirtualHost>
apache2.conf:# logged here.  If you *do* define an error logfile for a <VirtualHost>
conf-available/localized-error-pages.conf:# even on a per-VirtualHost basis.  If you include the Alias in the global server
conf-available/other-vhosts-access-log.conf:# Define an access log for VirtualHosts that don't define their own logfile
ports.conf:# have to change the VirtualHost statement in
sites-available/000-default.conf:<VirtualHost *:80>
...

文件同步 (rsync)

rsync 是一个快速的命令行工具,用于在两个位置之间同步文件和目录。 可用于本地和远程复制,速度很快,因为它只发送源文件和目标中现有文件之间的差异。

它广泛用于备份和作为日常使用的改进复制命令。

这是一个例子:

要将 myfiles 目录中的所有文件复制/rsync 到 /backups 目录:

[email protected]:~$ rsync -avh myfiles/ /backups
sending incremental file list
./
a.txt
b.txt
c.txt

sent 218 bytes  received 76 bytes  588.00 bytes/sec
total size is 0  speedup is 0.00

要将 myfiles 目录中的所有文件同步到远程主机上的备份目录,请在目标名称中包含 remote_user@remote_host。因此,要将 myfiles 文件夹同步到 IP 为 10.0.0.50 的远程主机:

[email protected]:~$ rsync -avh myfiles/ [email protected]:/home/vagrant
[email protected]'s password:
sending incremental file list
./
a.txt
b.txt
c.txt

sent 230 bytes  received 76 bytes  47.08 bytes/sec
total size is 0  speedup is 0.00

套接字统计 (ss)

ss 命令用于显示套接字统计信息,类似于传统的 netstat 实用程序。要显示 TCP 套接字,请使用 -t 参数。

[email protected]:~$ ss -t
State       Recv-Q        Send-Q                 Local Address:Port                     Peer Address:Port
ESTAB       0             0                           10.0.0.4:53852                   168.63.129.16:8037
ESTAB       0             0                           10.0.0.4:ssh                    183.83.211.129:64118
ESTAB       0             0                           10.0.0.4:33256                 169.254.169.254:http
ESTAB       0             1080                        10.0.0.4:ssh                     222.186.30.35:11527
ESTAB       0             0                           10.0.0.4:ssh                    183.83.211.129:63049

这不会显示正在侦听的套接字。要同时包含监听和非监听套接字,请使用 -t-a 参数。

[email protected]:~$ ss -t -a
State        Recv-Q        Send-Q                Local Address:Port                     Peer Address:Port
LISTEN       0             128                         0.0.0.0:ssh                           0.0.0.0:*
LISTEN       0             80                        127.0.0.1:mysql                         0.0.0.0:*
LISTEN       0             128                   127.0.0.53%lo:domain                        0.0.0.0:*
ESTAB        0             0                          10.0.0.4:53852                   168.63.129.16:8037
ESTAB        0             0                          10.0.0.4:ssh                    183.83.211.129:64118
ESTAB        0             0                          10.0.0.4:33256                 169.254.169.254:http
ESTAB        0             1080                       10.0.0.4:ssh                     222.186.30.35:11527
ESTAB        0             120                        10.0.0.4:ssh                    183.83.211.129:63049
LISTEN       0             128                            [::]:ssh                              [::]:*
LISTEN       0             128                               *:http                                *:*

快速文件定位 (locate)

locate 命令使用数据库来搜索文件,速度比 find 命令快得多。 它使用起来非常简单,可以搜索一个文件,比如 apache2.conf

[email protected]:~$ locate apache2.conf
/etc/apache2/apache2.conf
/var/lib/dpkg/info/apache2.conffiles

如果您只想要与搜索模式匹配的文件数,则可以使用 -c 参数。

[email protected]:~$ locate -c apache2.conf
2

有时,您可能需要刷新 locate 使用的数据库,即 mlocate。 要更新数据库,请使用 updatedb 命令。这需要超级用户权限。

[email protected]:~$ sudo updatedb

高级文件查找 (find)

find 是 Linux 上最常用的命令之一。使用它可以根据文件名、权限、用户 ID、组 ID、大小、文件类型以及其他条件搜索文件。

要在当前目录中按名称搜索文件,请使用 -name 参数,后跟要搜索的文件名:

[email protected]:~$ find . -name a.txt
./myfiles/a.txt

要搜索目录,请使用 -type d 参数:

[email protected]:~$ find . -type d
.
./.ssh
./myfiles
./.cache
./.gnupg
./.gnupg/private-keys-v1.d
./docker

要按大小搜索文件,比如大于 20MB 的文件,请使用 -size 参数:

[email protected]:~$ find . -size +20M
./docker/docker-ce-cli_5%3a19.03.12~3-0~ubuntu-bionic_amd64.deb
./docker/docker-ce_5%3a19.03.12~3-0~ubuntu-bionic_amd64.deb

服务控制 (systemctl)

现在 systemd 已经取代了大多数 Linux 发行版中的 SysV init 进程,使用 systemctl 命令来管理 systemd 服务和单元。

启动一个服务,例如 apache2

[email protected]:~$ sudo systemctl start apache2.service

您可以留下服务后缀。

停止服务:

[email protected]:~$ sudo systemctl stop apache2

要查看服务状态,请使用 systemctl status 命令。 以下示例显示 apache2 运行时的状态:

[email protected]:~$ sudo systemctl status apache2
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since Wed 2020-08-19 11:34:04 UTC; 2s ago
  Process: 25346 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS)
  Process: 18202 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)
  Process: 25536 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
 Main PID: 25555 (apache2)
    Tasks: 55 (limit: 1024)
   CGroup: /system.slice/apache2.service
           ├─25555 /usr/sbin/apache2 -k start
           ├─25558 /usr/sbin/apache2 -k start
           └─25559 /usr/sbin/apache2 -k start

Aug 19 11:34:04 ubuntu18 systemd[1]: Starting The Apache HTTP Server...
Aug 19 11:34:04 ubuntu18 systemd[1]: Started The Apache HTTP Server.

防火墙管理 (ufw)

UFW (简单的防火墙) 是一个易于使用的 iptables 前端。 默认情况下,它在基于 Ubuntu 的发行版上可用。 在 CentOS 上,您可以从 EPEL 存储库安装 ufw

要启用 ufw:

$ sudo ufw enable

使用 ufw status 检查防火墙状态:

$ sudo ufw status
Status: active

默认 UFW 策略允许所有传出流量并阻止所有传入流量。

以下命令允许 HTTP 端口上的传入流量:

$ sudo ufw allow http
Rule added
Rule added (v6)

您可以拒绝任何端口上的流量。这是一个阻止端口 21 上的流量的示例:

$ sudo ufw deny 21
Rule added
Rule added (v6)

日志查看 (journalctl)

使用 journalctl 查看 systemd 收集的日志。 systemd 以二进制格式在中心位置收集日志。要查看这些日志:

[email protected]:~$ sudo journalctl
-- Logs begin at Mon 2020-06-29 02:48:31 UTC, end at Wed 2020-08-19 15:07:59 UTC. --
Jun 29 02:48:31 ubuntu kernel: Linux version 5.3.0-1028-azure ([email protected]) (gcc version 7.5.0 (Ubuntu
Jun 29 02:48:31 ubuntu kernel: Command line: BOOT_IMAGE=/boot/vmlinuz-5.3.0-1028-azure root=UUID=b0dd9d06-536e-41
Jun 29 02:48:31 ubuntu kernel: KERNEL supported cpus:
Jun 29 02:48:31 ubuntu kernel:   Intel GenuineIntel
...

大多数情况下,您希望以相反的顺序查看日志,即最先查看最新日志:

[email protected]:~$ sudo journalctl -r
-- Logs begin at Mon 2020-06-29 02:48:31 UTC, end at Wed 2020-08-19 15:10:16 UTC. --
Aug 19 15:10:16 ubuntu18 sudo[31263]: pam_unix(sudo:session): session opened for user root by ubuntu(uid=0)
Aug 19 15:10:16 ubuntu18 sudo[31263]:   ubuntu : TTY=pts/1 ; PWD=/home/ubuntu ; USER=root ; COMMAND=/bin/journalc
Aug 19 15:10:11 ubuntu18 sudo[31213]: pam_unix(sudo:session): session closed for user root
Aug 19 15:07