31-35.玩转Linux操作系统.md

31-35.玩转Linux操作系统.md

Cosmos 852 2022-06-13

----. 1 root root 541 Aug 3 2017 anacrontab
drwxr-xr-x. 2 root root 4096 Mar 27 11:56 cron.d
drwxr-xr-x. 2 root root 4096 Mar 27 11:51 cron.daily
-rw-------. 1 root root 0 Aug 3 2017 cron.deny
drwxr-xr-x. 2 root root 4096 Mar 27 11:50 cron.hourly
drwxr-xr-x. 2 root root 4096 Jun 10 2014 cron.monthly
-rw-r--r-- 1 root root 493 Jun 23 15:09 crontab
drwxr-xr-x. 2 root root 4096 Jun 10 2014 cron.weekly
[root etc]# vim crontab
1 SHELL=/bin/bash
2 PATH=/sbin:/bin:/usr/sbin:/usr/bin
3 MAILTO=root
4
5 # For details see man 4 crontabs
6
7 # Example of job definition:
8 # .---------------- minute (0 - 59)
9 # | .------------- hour (0 - 23)
10 # | | .---------- day of month (1 - 31)
11 # | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
12 # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
13 # | | | | |
14 # * * * * * user-name command to be executed



### 网络访问和管理

1. 安全远程连接 - **ssh**。

 ```Shell
 [root ~]$ ssh root@120.77.222.217
 The authenticity of host '120.77.222.217 (120.77.222.217)' can't be established.
 ECDSA key fingerprint is SHA256:BhUhykv+FvnIL03I9cLRpWpaCxI91m9n7zBWrcXRa8w.
 ECDSA key fingerprint is MD5:cc:85:e9:f0:d7:07:1a:26:41:92:77:6b:7f:a0:92:65.
 Are you sure you want to continue connecting (yes/no)? yes
 Warning: Permanently added '120.77.222.217' (ECDSA) to the list of known hosts.
 root@120.77.222.217's password: 
 ```

2. 通过网络获取资源 - **wget**。

- -b 后台下载模式
- -O 下载到指定的目录
- -r 递归下载

3. 发送和接收邮件 - **mail**。

4. 网络配置工具(旧) - **ifconfig**。

```Shell
[root ~]# ifconfig eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.18.61.250  netmask 255.255.240.0  broadcast 172.18.63.255
        ether 00:16:3e:02:b6:46  txqueuelen 1000  (Ethernet)
        RX packets 1067841  bytes 1296732947 (1.2 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 409912  bytes 43569163 (41.5 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 
  1. 网络配置工具(新) - ip

    [root ~]# ip address
    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
        inet 127.0.0.1/8 scope host lo
           valid_lft forever preferred_lft forever
    2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        link/ether 00:16:3e:02:b6:46 brd ff:ff:ff:ff:ff:ff
        inet 172.18.61.250/20 brd 172.18.63.255 scope global eth0
           valid_lft forever preferred_lft forever
    
  2. 网络可达性检查 - ping

    [root ~]# ping www.baidu.com -c 3
    PING www.a.shifen.com (220.181.111.188) 56(84) bytes of data.
    64 bytes from 220.181.111.188 (220.181.111.188): icmp_seq=1 ttl=51 time=36.3 ms
    64 bytes from 220.181.111.188 (220.181.111.188): icmp_seq=2 ttl=51 time=36.4 ms
    64 bytes from 220.181.111.188 (220.181.111.188): icmp_seq=3 ttl=51 time=36.4 ms
    --- www.a.shifen.com ping statistics ---
    3 packets transmitted, 3 received, 0% packet loss, time 2002ms
    rtt min/avg/max/mdev = 36.392/36.406/36.427/0.156 ms
    
  3. 显示或管理路由表 - route

  4. 查看网络服务和端口 - netstat / ss

    [root ~]# netstat -nap | grep nginx
    
  5. 网络监听抓包 - tcpdump

  6. 安全文件拷贝 - scp

[root ~]# scp root@1.2.3.4:/root/guido.jpg hellokitty@4.3.2.1:/home/hellokitty/pic.jpg
  1. 文件同步工具 - rsync

    说明:使用rsync可以实现文件的自动同步,这个对于文件服务器来说相当重要。关于这个命令的用法,我们在后面讲项目部署的时候为大家详细说明。

  2. 安全文件传输 - sftp

    [root ~]# sftp root@1.2.3.4
    root@1.2.3.4's password:
    Connected to 1.2.3.4.
    sftp>
    
    • help:显示帮助信息。

    • ls/lls:显示远端/本地目录列表。

    • cd/lcd:切换远端/本地路径。

    • mkdir/lmkdir:创建远端/本地目录。

    • pwd/lpwd:显示远端/本地当前工作目录。

    • get:下载文件。

    • put:上传文件。

    • rm:删除远端文件。

    • bye/exit/quit:退出sftp。

进程管理

  1. 查看进程 - ps

    [root ~]# ps -ef
    UID        PID  PPID  C STIME TTY          TIME CMD
    root         1     0  0 Jun23 ?        00:00:05 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
    root         2     0  0 Jun23 ?        00:00:00 [kthreadd]
    ...
    [root ~]# ps -ef | grep mysqld
    root      4943  4581  0 22:45 pts/0    00:00:00 grep --color=auto mysqld
    mysql    25257     1  0 Jun25 ?        00:00:39 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
    
  2. 显示进程状态树 - pstree

    [root ~]# pstree
    systemd─┬─AliYunDun───18*[{AliYunDun}]
            ├─AliYunDunUpdate───3*[{AliYunDunUpdate}]
            ├─2*[agetty]
            ├─aliyun-service───2*[{aliyun-service}]
            ├─atd
            ├─auditd───{auditd}
            ├─dbus-daemon
            ├─dhclient
            ├─irqbalance
            ├─lvmetad
            ├─mysqld───28*[{mysqld}]
            ├─nginx───2*[nginx]
            ├─ntpd
            ├─polkitd───6*[{polkitd}]
            ├─rsyslogd───2*[{rsyslogd}]
            ├─sshd───sshd───bash───pstree
            ├─systemd-journal
            ├─systemd-logind
            ├─systemd-udevd
            └─tuned───4*[{tuned}]
    
  3. 查找与指定条件匹配的进程 - pgrep

    [root ~]$ pgrep mysqld
    3584
    
  4. 通过进程号终止进程 - kill

    [root ~]$ kill -l
     1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
     6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
    11) SIGSEGV     12) SIGUSR2     13) SIGPIPE     14) SIGALRM     15) SIGTERM
    16) SIGSTKFLT   17) SIGCHLD     18) SIGCONT     19) SIGSTOP     20) SIGTSTP
    21) SIGTTIN     22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
    26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO       30) SIGPWR
    31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
    38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
    43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
    48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
    53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
    58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
    63) SIGRTMAX-1  64) SIGRTMAX
    [root ~]# kill 1234
    [root ~]# kill -9 1234
    

    例子:用一条命令强制终止正在运行的Redis进程。

    ps -ef | grep redis | grep -v grep | awk '{print $2}' | xargs kill
    
  5. 通过进程名终止进程 - killall / pkill

    结束名为mysqld的进程。

    [root ~]# pkill mysqld
    

    结束hellokitty用户的所有进程。

    [root ~]# pkill -u hellokitty
    

    说明:这样的操作会让hellokitty用户和服务器断开连接。

  6. 将进程置于后台运行。

    • Ctrl+Z - 快捷键,用于停止进程并置于后台。
    • & - 将进程置于后台运行。
    [root ~]# mongod &
    [root ~]# redis-server
    ...
    ^Z
    [4]+  Stopped                 redis-server
    
  7. 查询后台进程 - jobs

    [root ~]# jobs
    [2]   Running                 mongod &
    [3]-  Stopped                 cat
    [4]+  Stopped                 redis-server
    
  8. 让进程在后台继续运行 - bg

    [root ~]# bg %4
    [4]+ redis-server &
    [root ~]# jobs
    [2]   Running                 mongod &
    [3]+  Stopped                 cat
    [4]-  Running                 redis-server &
    
  9. 将后台进程置于前台 - fg

    [root ~]# fg %4
    redis-server
    

    说明:置于前台的进程可以使用Ctrl+C来终止它。

  10. 调整程序/进程运行时优先级 - nice / renice

  11. 用户登出后进程继续工作 - nohup

    [root ~]# nohup ping www.baidu.com > result.txt &
    
  12. 跟踪进程系统调用情况 - strace

    [root ~]# pgrep mysqld
    8803
    [root ~]# strace -c -p 8803
    strace: Process 8803 attached
    ^Cstrace: Process 8803 detached
    % time     seconds  usecs/call     calls    errors syscall
    ------ ----------- ----------- --------- --------- ----------------
     99.18    0.005719        5719         1           restart_syscall
      0.49    0.000028          28         1           mprotect
      0.24    0.000014          14         1           clone
      0.05    0.000003           3         1           mmap
      0.03    0.000002           2         1           accept
    ------ ----------- ----------- --------- --------- ----------------
    100.00    0.005766                     5           total
    

    说明:这个命令的用法和参数都比较复杂,建议大家在真正用到这个命令的时候再根据实际需要进行了解。

  13. 查看当前运行级别 - runlevel

    [root ~]# runlevel
    N 3
    
  14. 实时监控进程占用资源状况 - top

    [root ~]# top
    top - 23:04:23 up 3 days, 14:10,  1 user,  load average: 0.00, 0.01, 0.05
    Tasks:  65 total,   1 running,  64 sleeping,   0 stopped,   0 zombie
    %Cpu(s):  0.3 us,  0.3 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem :  1016168 total,   191060 free,   324700 used,   500408 buff/cache
    KiB Swap:        0 total,        0 free,        0 used.   530944 avail Mem
    ...
    
    • -c - 显示进程的整个路径。
    • -d - 指定两次刷屏之间的间隔时间(秒为单位)。
    • -i - 不显示闲置进程或僵尸进程。
    • -p - 显示指定进程的信息。

系统诊断

  1. 系统启动异常诊断 - dmesg

  2. 查看系统活动信息 - sar

    [root ~]# sar -u -r 5 10
    Linux 3.10.0-957.10.1.el7.x86_64 (izwz97tbgo9lkabnat2lo8z)      06/02/2019      _x86_64_        (2 CPU)
    
    06:48:30 PM     CPU     %user     %nice   %system   %iowait    %steal     %idle
    06:48:35 PM     all      0.10      0.00      0.10      0.00      0.00     99.80
    
    06:48:30 PM kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact   kbdirty
    06:48:35 PM   1772012   2108392     54.33    102816   1634528    784940     20.23    793328   1164704         0
    
    • -A - 显示所有设备(CPU、内存、磁盘)的运行状况。
    • -u - 显示所有CPU的负载情况。
    • -d - 显示所有磁盘的使用情况。
    • -r - 显示内存的使用情况。
    • -n - 显示网络运行状态。
  3. 查看内存使用情况 - free

    [root ~]# free
                  total        used        free      shared  buff/cache   available
    Mem:        1016168      323924      190452         356      501792      531800
    Swap:             0           0           0
    
  4. 虚拟内存统计 - vmstat

    [root ~]# vmstat
    procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
     r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
     2  0      0 204020  79036 667532    0    0     5    18  101   58  1  0 99  0  0
    
  5. CPU信息统计 - mpstat

    [root ~]# mpstat
    Linux 3.10.0-957.5.1.el7.x86_64 (iZ8vba0s66jjlfmo601w4xZ)       05/30/2019      _x86_64_        (1 CPU)
    
    01:51:54 AM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
    01:51:54 AM  all    0.71    0.00    0.17    0.04    0.00    0.00    0.00    0.00    0.00   99.07
    
  6. 查看进程使用内存状况 - pmap

    [root ~]# ps
      PID TTY          TIME CMD
     4581 pts/0    00:00:00 bash
     5664 pts/0    00:00:00 ps
    [root ~]# pmap 4581
    4581:   -bash
    0000000000400000    884K r-x-- bash
    00000000006dc000      4K r---- bash
    00000000006dd000     36K rw--- bash
    00000000006e6000     24K rw---   [ anon ]
    0000000001de0000    400K rw---   [ anon ]
    00007f82fe805000     48K r-x-- libnss_files-2.17.so
    00007f82fe811000   2044K ----- libnss_files-2.17.so
    ...
    
  7. 报告设备CPU和I/O统计信息 - iostat

    [root ~]# iostat
    Linux 3.10.0-693.11.1.el7.x86_64 (iZwz97tbgo9lkabnat2lo8Z)      06/26/2018      _x86_64_       (1 CPU)
    avg-cpu:  %user   %nice %system %iowait  %steal   %idle
               0.79    0.00    0.20    0.04    0.00   98.97
    Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
    vda               0.85         6.78        21.32    2106565    6623024
    vdb               0.00         0.01         0.00       2088          0
    
  8. 显示所有PCI设备 - lspci

    [root ~]# lspci
    00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
    00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
    00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
    00:01.2 USB controller: Intel Corporation 82371SB PIIX3 USB [Natoma/Triton II] (rev 01)
    00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 03)
    00:02.0 VGA compatible controller: Cirrus Logic GD 5446
    00:03.0 Ethernet controller: Red Hat, Inc. Virtio network device
    00:04.0 Communication controller: Red Hat, Inc. Virtio console
    00:05.0 SCSI storage controller: Red Hat, Inc. Virtio block device
    00:06.0 SCSI storage controller: Red Hat, Inc. Virtio block device
    00:07.0 Unclassified device [00ff]: Red Hat, Inc. Virtio memory balloon
    
  9. 显示进程间通信设施的状态 - ipcs

    [root ~]# ipcs
    
    ------ Message Queues --------
    key        msqid      owner      perms      used-bytes   messages    
    
    ------ Shared Memory Segments --------
    key        shmid      owner      perms      bytes      nattch     status      
    
    ------ Semaphore Arrays --------
    key        semid      owner      perms      nsems
    

Shell编程

之前我们提到过,Shell是一个连接用户和操作系统的应用程序,它提供了人机交互的界面(接口),用户通过这个界面访问操作系统内核的服务。Shell脚本是一种为Shell编写的脚本程序,我们可以通过Shell脚本来进行系统管理,同时也可以通过它进行文件操作。总之,编写Shell脚本对于使用Linux系统的人来说,应该是一项标配技能。

互联网上有大量关于Shell脚本的相关知识,我不打算再此对Shell脚本做一个全面系统的讲解,我们通过下面的代码来感性的认识下Shell脚本就行了。

例子1:输入两个整数m和n,计算从m到n的整数求和的结果。

#!/usr/bin/bash
printf 'm = '
read m
printf 'n = '
read n
a=$m
sum=0
while [ $a -le $n ]
do
    sum=$[ sum + a ]
    a=$[ a + 1 ]
done
echo '结果: '$sum

例子2:自动创建文件夹和指定数量的文件。

#!/usr/bin/bash
printf '输入文件夹名: '
read dir
printf '输入文件名: '
read file
printf '输入文件数量(<1000): '
read num
if [ $num -ge 1000 ]
then
    echo '文件数量不能超过1000'
else
    if [ -e $dir -a -d $dir ]
    then
        rm -rf $dir
    else
        if [ -e $dir -a -f $dir ]
        then
            rm -f $dir
        fi
    fi
    mkdir -p $dir
    index=1
    while [ $index -le $num ]
    do
        if [ $index -lt 10 ]
        then
            pre='00'
        elif [ $index -lt 100 ]
        then
            pre='0'
        else
            pre=''
        fi
        touch $dir'/'$file'_'$pre$index
        index=$[ index + 1 ]
    done
fi

例子3:自动安装指定版本的Redis。

#!/usr/bin/bash
install_redis() {
    if ! which redis-server > /dev/null
    then
        cd /root
        wget $1$2'.tar.gz' >> install.log
        gunzip /root/$2'.tar.gz'
        tar -xf /root/$2'.tar'
        cd /root/$2
        make >> install.log
        make install >> install.log
        echo '安装完成'
    else
        echo '已经安装过Redis'
    fi
}

install_redis 'http://download.redis.io/releases/' $1

相关资源

  1. Linux命令行常用快捷键

    快捷键功能说明
    tab自动补全命令或路径
    Ctrl+a将光标移动到命令行行首
    Ctrl+e将光标移动到命令行行尾
    Ctrl+f将光标向右移动一个字符
    Ctrl+b将光标向左移动一个字符
    Ctrl+k剪切从光标到行尾的字符
    Ctrl+u剪切从光标到行首的字符
    Ctrl+w剪切光标前面的一个单词
    Ctrl+y复制剪切命名剪切的内容
    Ctrl+c中断正在执行的任务
    Ctrl+h删除光标前面的一个字符
    Ctrl+d退出当前命令行
    Ctrl+r搜索历史命令
    Ctrl+g退出历史命令搜索
    Ctrl+l清除屏幕上所有内容在屏幕的最上方开启一个新行
    Ctrl+s锁定终端使之暂时无法输入内容
    Ctrl+q退出终端锁定
    Ctrl+z将正在终端执行的任务停下来放到后台
    !!执行上一条命令
    !数字执行数字对应的历史命令
    !字母执行最近的以字母打头的命令
    !$ / Esc+.获得上一条命令最后一个参数
    Esc+b移动到当前单词的开头
    Esc+f移动到当前单词的结尾
  2. man查阅命令手册的内容说明

    手册中的标题功能说明
    NAME命令的说明和介绍
    SYNOPSIS使用该命令的基本语法
    DESCRIPTION使用该命令的详细描述,各个参数的作用,有时候这些信息会出现在OPTIONS中
    OPTIONS命令相关参数选项的说明
    EXAMPLES使用该命令的参考例子
    EXIT STATUS命令结束的退出状态码,通常0表示成功执行
    SEE ALSO和命令相关的其他命令或信息
    BUGS和命令相关的缺陷的描述
    AUTHOR该命令的作者介绍