linux常用命令

目录

【运维】日常遇到问题

linux常见作业

第1章 linux预备

001.在linux命令行下查看命令帮助

1. man用于查看命令的帮助信息 man cp
2. --help     cd  --help
3. info查看程序对应文档信息的命令,可以作为man和help命令的帮助补充info ls
4. 从互联网获取帮助 google>bing>baidu

002.调整中文显示

#  echo $LANG 
#vi /etc/sysconfig/i18n     i18n=internationalization i和n之间18个字母
或#  vi  /etc/locale.conf 
# cat /etc/locale.conf
  LANG="en_US.UTF-8"
#  LANG="zh_CN.UTF-8"   临时设置
#  source /etc/sysconfig/i18n   文件生效
# echo $LANG

003.命令行光标显示与隐藏

# echo -e "\033[?25l"   隐藏光标
#echo -e "\033[?25 h "  显示光标
   echo -e 开启转义
   echo -n 不换行输出
#  echo -e  "hello\n world"
   hello
    world

004.在Bash命令行显示当前用户的完整路径

echo $PS1 打印超级管理员对应的PS1值
#  echo $PS1 
  [\u@\h \W]\$
# PS1='[\u@\h \w]\$'   临时修改
#  vi /etc/bashrc        永久修改 
# source /etc/bashrc

005.关机重启注销命令

shutdown、init、halt、poweroff、reboot

shutdown  -h now  立即关机
shutdown  -h +1   1分钟后关机
shutdown -h 11:00 11:00关机
shutdown -r now    立即重启
shutdown  -r 11:00   11:00重启
shutdown  -c 取消
windows是
shutdown -s -t 7200  2小时后关机
shutdown -a 取消
# shutdown -r 11:00
Shutdown scheduled for Wed 2022-01-05 11:00:00 PST, use 'shutdown -c' to cancel.
# shutdown -c
init 0 表示关机
init 6 表示重启

从redhat或centos6开始,halt/poweroff/reboot三个命令对应的都是同一个man帮助文档,而halt、poweroff、reboot是systemctl命令的链接文件。

# ls -l  /sbin/halt 
lrwxrwxrwx. 1 root root 16 7月  18 2018 /sbin/halt -> ../bin/systemctl 
# ll  /sbin/poweroff 
lrwxrwxrwx. 1 root root 16 7月  18 2018 /sbin/poweroff -> ../bin/systemctl
# ll  /sbin/reboot 
lrwxrwxrwx. 1 root root 16 7月  18 2018 /sbin/reboot -> ../bin/systemctl

第2章 文件和目录操作

006.pwd 显示当前所在位置.pwd:print working directory

pwd -L 获取环境变量的PWD对应的值,即为echo $PWD的结果
pwd -P 显示链接对应的源文件的目录路径

[root@localhost sbin]#  pwd 
/sbin
[root@localhost sbin]#  pwd -P 
/usr/sbin

007.cd切换目录.cd:change directory

cd - 切换到当前用户上一次所在目录
cd ~ 切换到当前用户的家目录
cd   不带任何参数,和cd ~结果一样
cd ..切换到上一级目录
cd ../../ 切换到父目录的父目录,只要目录有足够多的层次,可以一直继续下去,直到/为止

008.tree以树形结构显示目录下的内容

tree 不接选项和目录,默认显示当前所在路径目录的目录结构
如果没有可以安装

# rpm -qa tree
# yum -y install tree
如果树形显示乱码
LANG=en_US.UTF-8临时解决
tree  -a  以树形结构显示目录下的所有内容
tree  -L 1  / 只列出根目录下第一层目录的结构
tree  -d  /etc/ 只显示所有的目录(不显示文件)
tree  -L 1 -f  /boot/ -f显示内容的完整路径
tree  -L  1  -fi  /boot/ -i不显示树枝,当需要获取所有文件的完整路径时,这个命令很好用

使用tree命令区分目录和文件的方法

tree -L 1  -F  /boot/ 使用-F参数会在目录后面添加/,方便区分目录
tree -L 1 -F /boot/ |  grep /$  过滤以斜线结尾的所有内容

009.mkdir创建目录.mkdir:make directories

mkdir data 当前目录下创建data
mkdir  -p  data/ptest  参数-p递归创建多级目录
tree -d
mkdir  -pv  data/pvtest 参数-v显示创建目录过程
mkdir  -m  333 datam   创建目录时指定333的数字权限

同时创建多个目录及多级子目录

mkdir -pv data/{dir_1,dir_2}/{dir_2_1,dir2_2}
mkdir -p data/dir{1..5} data2/dir{a..c}

实例:克隆目录结构:对文件目录做操作时,预先建立的目录结构

tree -fid  --noreport  /tmp/data 显示所有目录树 --noreport不显示最后一行的统计信息
tree -fid --noreport /tmp/data >> ./tongji.txt
cd /root/
mkdir -p `cat /tmp/data/tongji.txt`
tree -d /root/ 

010.touch创建空文件或改变文件的时间戳属性

mkdir是创建空文件夹,touch是创建空文件;stat a.txt 查看文件的时间戳属性

访问时间、修改时间、状态改变时间

Access: 2021-11-11 11:11:00.000000000 +0800
Modify: 2021-11-11 11:11:00.000000000 +0800
Change: 2021-12-31 21:38:49.346894400 +0800 

touch -a a.txt 修改最后访问时间(access)
touch -m a.txt 更改最后修改时间(modify)
状态改变时间自动更新

touch -d       指定创建文件后的文件修改时间access\modify
   touch -d 20201001 b.txt
ls -lh --full-time b.txt
touch  -r        修改b.txt的时间属性(access.modify),使其和a.txt的时间属性一致
    touch -r a.txt b.txt  
touch  -t          指定文件的最后修改时间(access.modify)
    touch -t 20220101010101.50 b.txt
ls -lu  最后访问时间      atime  access time  
ls -lt  最后修改时间      mtime  modify time
ls -lc  状态改变时间      ctime  change time

 touch -d 时间格式YYYYMMDD 不能指定时分秒
touch -t 时间格式YYYYMMDDHHMMSS 不能只指定YMD

011.ls 列出目录内容及其内容属性信息.list directory contents类似Dos系统下的dir命令

ls 直接执行,显示所有文件和目录(不显示隐藏文件)

ls -a 显示所有文件,特别是隐藏文件
ls -d 查看目录本身信息
ls -l 显示详细信息(文件类型 权限 连接数 属主(组) 大小 创建修改时间)
ls -ltr 其中的-t按时间顺序,-r倒序排列。最新更改的在最后一行(时间最大)
  ls -ltr --time-style=long-iso /etc | tail -n 3    

在linux系统中,以·开头的文件就是隐藏文件

touch .hide.txt
mkdir -pv .hide/test

ls -l --time-style=long-iso显示完整时间属性
      --time-style=iso     显示月日时分
      --time-style=full-iso等效于 --full-time
      --time-style=locale  默认模式

※若显示时间格式参数过长,可以设置别名

# alias | grep ls
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
# alias lst='ls -l --time-style=long-iso'
# lst
# unalias lst

ls -F 与tree -F参数类似,都是目录后面加上/,若不是目录,其他类型文件的情况下,会是别的符号.

加上*代表可执行的普通文件
加上/代表目录
加上=表示套接字(sockets)
加上|表示FIFOs
加上@表示符号链接

[root@localhost /home/sun]# ls -F
dir1/  test.txt
[root@localhost /home/sun]# ls -p               等价于-F,功能只是在目录后面加上/
dir1/  test.txt
[root@localhost /home/sun]#  ls -F | grep /      过滤目录 
dir1/
[root@localhost /home/sun]#  ls -F | grep -v  /  过滤普通文件 
test.txt

数据库备份获取数据库名列表

[root@localhost /tmp]# ls -F /etc | egrep "/" | awk -F "/" '{print $1}'
abrt
alternatives
audit
...

ls命令输出内容属性解读:

[root@localhost /home/sun]# ls -lhi
16898681 drwxrwxr-x. 2 sun  sun  6 1月  11 06:15 dir1
34143319 -rw-r--r--. 1 root root 6 1月  11 06:30 test.txt    
   第一列inode索引节点编号
   第二列文件类型及权限
   第三列硬链接个数
   第四列所属用户
   第五列所属组别
   第六列文件或目录的大小
   第七八九列是文件或目录的修改时间
   第十列实际文件或目录名

012.cp 复制文件或目录copy

cp -a 等同于-p -d -r 三个选项的总和
cp -p 复制文件时保持源文件的所有者、权限信息及时间属性
cp -d 如果复制的源文件是符号链接,仅复制符号链接本身,并保留符号链接所指向的目标文件或目录
cp -r 递归复制目录
cp -i 覆盖已有文件前提示用户确认,系统默认alias cp = 'cp -i'
cp -t 目标文件 源文件 = cp 源文件 目标文件 

※cp test.txt{,.bk2}方法原理是bash对大括号的展开操作,test.txt{,.bk2}展开成 test.txt test.txt.bk2再传给cp命令

# cp test.txt{,.bk2}
# ls -lh --time-style=long-iso
-rw-r--r--. 1 root root 11K 2022-01-16 05:43 test.txt
-rw-r--r--. 1 root root 11K 2022-01-16 05:48 test.txt.bk2

013.mv 移动或重命名文件。move/rename files

mv -f 若目标文件已经存在,不询问直接覆盖
mv -i 若文件已经存在,询问是否覆盖
mv -n 不覆盖已经存在的文件
mv -t 和cp -t 功能类似
mv -u 在源文件比目标文件新,或目标文件不存在时才进行移动

014.rm 删除文件或目录 remove files or directories

这是linux中最危险的命令之一,慎用。删除之前务必备份

rm -r 递归删除目录及其内容
rm -f 强制删除
rm -i 删除前提示,系统默认
rm -I 在删除超过三个文件或者递归删除前要求确认

rm -rf误删数据后恢复方法

015.rmdir 删除空目录 remove empty directories

当目录不为空时,命令不起作用。实际工作中使用极少

链接类型包括硬链接hardlink和软连接(符号链接,symbolic link)

硬链接

硬链接是指通过索引点(inode)来进行链接。在linux(ext2/3/4)文件系统中,所有文件都有一个唯一的inode编号。在linux中多个文件名指向同一个inode是被允许的,这种情况下的文件就是硬链接。相当于文件的另一个入口。通过建立硬链接来防止删除源数据。

ln 源文件 目标文件(硬链接生成的是普通文件 -字符)

软链接

软连接或符号链接(symbolic link or soft link)有点像windows里的快捷方式。
失效的时候一般是白字红底。

ln -s 源文件 目标文件

# ln file1.txt file
# stat file
  文件:file
  大小:0               块:0          IO 块:4096   普通空文件
设备:805h/2053d         Inode:34134067     硬链接:2
权限:(0644/-rw-r--r--)  Uid:(    0/    root)   Gid:(    0/    root)
环境:unconfined_u:object_r:user_home_t:s0
最近访问:2022-01-16 06:11:42.047874157 -0800
最近更改:2022-01-16 06:11:42.047874157 -0800
最近改动:2022-01-16 06:29:52.166152076 -0800
创建时间:-
# stat file1.txt
  文件:file1.txt
  大小:0               块:0          IO 块:4096   普通空文件
设备:805h/2053d         Inode:34134067     硬链接:2
权限:(0644/-rw-r--r--)  Uid:(    0/    root)   Gid:(    0/    root)
环境:unconfined_u:object_r:user_home_t:s0
最近访问:2022-01-16 06:11:42.047874157 -0800
最近更改:2022-01-16 06:11:42.047874157 -0800
最近改动:2022-01-16 06:29:52.166152076 -0800
创建时间:-
# ln -s file2.txt file2
# stat file2
  文件:file2 -> file2.txt
  大小:9               块:0          IO 块:4096   符号链接
设备:805h/2053d         Inode:34143313     硬链接:1
权限:(0777/lrwxrwxrwx)  Uid:(    0/    root)   Gid:(    0/    root)
环境:unconfined_u:object_r:user_home_t:s0
最近访问:2022-01-16 06:32:48.977393931 -0800
最近更改:2022-01-16 06:32:48.977393931 -0800
最近改动:2022-01-16 06:32:48.977393931 -0800
创建时间:-
# stat file2.txt
  文件:file2.txt
  大小:0               块:0          IO 块:4096   普通空文件
设备:805h/2053d         Inode:34134070     硬链接:1
权限:(0644/-rw-r--r--)  Uid:(    0/    root)   Gid:(    0/    root)
环境:unconfined_u:object_r:user_home_t:s0
最近访问:2022-01-16 06:11:42.047874157 -0800
最近更改:2022-01-16 06:11:42.047874157 -0800
最近改动:2022-01-16 06:11:42.047874157 -0800
创建时间:-

017.Linux查看分区文件系统类型的几种方法

#  df -T 
文件系统       类型        1K-块    已用     可用 已用% 挂载点
/dev/sda2      ext4       289285  122673   147156   46% /boot
#  parted -l 
Model: VMware, VMware Virtual S (scsi)
Disk /dev/sda: 21.5GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Number  Start   End     Size    Type      File system     标志
 1      1049kB  2097kB  1049kB  primary
 2      2097kB  317MB   315MB   primary   ext4            启动
 3      317MB   2464MB  2147MB  primary   linux-swap(v1)
 4      2464MB  21.5GB  19.0GB  extended
 5      2465MB  21.5GB  19.0GB  logical   xfs
#  blkid  
/dev/sda1: PARTUUID="5684473b-01"
/dev/sda2: UUID="eb6791ad-fdd2-453a-ae79-b5893ec9a18b" TYPE="ext4" PARTUUID="5684473b-02"
# lsblk -f
NAME   FSTYPE LABEL UUID                                 MOUNTPOINT
sda
├─sda1
├─sda2 ext4         eb6791ad-fdd2-453a-ae79-b5893ec9a18b /boot

readlink -f 将最后一个非符号链接文件显示出来,针对软链接

# ls -lhi /etc/init.d
17330846 lrwxrwxrwx. 1 root root 11 7月  22 2018 /etc/init.d -> rc.d/init.d
# readlink /etc/init.d
rc.d/init.d
# readlink -f /etc/init.d
/etc/rc.d/init.d

019.find 查找目录下的文件,同时也可以调用其他命令执行相应操作

查找指定时间内访问/修改过的文件

查找指定时间内修改过的文件
     find . -atime -2     当前目录下,查找两天内受访问的文件access time
查找/home/目录下修改时间在5天内的文件
     find /home/ -mtime -5 

在/home/目录下查找5天前以".txt"结尾的文件

find /home/ -name "*.txt" -mtime +5

利用!反向查找

[root@localhost /home]#  find . -type d 
...
./sun/dir3
./sun2
[root@localhost /home]#  find . ! -type d 
...
./sun2.txt

按照目录或文件的权限来查找文件

[root@localhost /home]#  find . -perm 755 
.
./sun/dir3
./sun2
[root@localhost /home]# ls -ld sun/dir3 sun2
drwxr-xr-x. 2 root root  6 1月  17 22:12 sun2
drwxr-xr-x. 2 root root 29 1月  17 21:53 sun/dir3

按大小查找文件(在/home/目录下查找文件大小大于100字节的文件,目录4096c)

[root@localhost /home]#  find /home/ -size +100c 
/home/sun
/home/sun/.bash_profile

查找文件时忽略某个目录(在/home/sun目录下,忽视dir3,查找名为file1.txt文件)

#  find /home/sun -path "/home/sun/dir3" -prune -o -print 
/home/sun/file1.txt
/home/sun/file2.txt
/home/sun/dir2
/home/sun/dir2/file1.txt
#  find /home/sun -path "/home/sun/dir3" -prune -o -name "file1.txt" -print 
/home/sun/file1.txt
/home/sun/dir2/file1.txt
※-prune 不在当前指定的目录中查找
※-print 将匹配文件检出到标准输出
※
与:-a
或:-o
非:-not, !

find /home/sun -name "file1.txt" | grep -v "/home/sun/dir3"

忽略多个目录(在/home/sun下,忽略dir2 dir3,查找名为file1.txt文件)

[root@localhost /home/sun]#  find /home/sun \( -path /home/sun/dir2 -o -path /home/sun/dir3 \) 
   -prune -o -name file1.txt -print 
/home/sun/file1.txt
※使用圆括号可以将多个表达式结合在一起,但是圆括号在命令行中有特殊含义,
所以使用\进行转义,即告诉bash不对后面的()作解析,而是留给find命令来处理。

使用user和nouser选项

-user
[root@localhost /home/sun]# chown oldboy:oldboy file1.txt
[root@localhost /home/sun]# ls -lh
总用量 12K
drwxr-xr-x. 2 root   root   23 1月  19 08:37 dir2
-rw-r--r--. 2 oldboy oldboy 11 1月  17 21:57 file1_hardlink
-rw-r--r--. 2 oldboy oldboy 11 1月  17 21:57 file1.txt
-rw-r--r--. 1 root   root   11 1月  17 22:19 file2.txt
[root@localhost /home/sun]#   find /home/sun -user oldboy 
/home/sun/file1.txt
/home/sun/file1_hardlink
-nouser 用途是为了查找账户被删除的文件
[root@localhost /home/sun]#  userdel oldboy 
[root@localhost /home/sun]#  find /home/sun -nouser 
/home/sun/file1.txt
/home/sun/file1_hardlink

使用group和nogroup选项

[root@localhost /home/sun]# groupadd newgroup
[root@localhost /home/sun]# chown sun:newgroup file1.txt
[root@localhost /home/sun]# ls -lh
总用量 12K
drwxr-xr-x. 2 root root     23 1月  19 08:37 dir2
-rw-r--r--. 2 sun  newgroup 11 1月  17 21:57 file1_hardlink
-rw-r--r--. 2 sun  newgroup 11 1月  17 21:57 file1.txt
[root@localhost /home/sun]# find . -group newgroup
./file1.txt
./file1_hardlink
[root@localhost /home/sun]# chown 555:555 file1.txt
[root@localhost /home/sun]# ls -lh
总用量 12K
drwxr-xr-x. 2 root root 23 1月  19 08:37 dir2
-rw-r--r--. 2  555  555 11 1月  17 21:57 file1_hardlink
-rw-r--r--. 2  555  555 11 1月  17 21:57 file1.txt
[root@localhost /home/sun]# find . -nogroup
./file1.txt
./file1_hardlink

查找比某个文件新或旧的文件

-newer 新  >
! -newer 取反  <= 
#  find . -newer dir3 
.
./dir2
#  find . -newer file2.txt ! -newer dir2 
.
./.bash_history
./dir3
./dir2                ←包含

find和xargs结合使用。

#  find /home/sun -type f !  -name ".*" | xargs ls -lh 
-rw-r--r--. 1 root root 0 2022-01-19 10:23 /home/sun/test1.txt

删除文件的方法(删除/root/data目录下的test.txt文件)

①进入目录下删除 
# touch test.txt
# cd /root/data/ ; rm -fv test.txt
已删除'test.txt'
 ②find+xargs 
# touch test.txt
# find /root/data/ -type f -name '*test.txt' |  xargs rm -fv 
已删除'/root/data/test.txt'
 ③find -exec 
# touch test.txt
# find /root/data/ -type f -name '*test.txt'  -exec rm -fv  {} \;
已删除'/root/data/test.txt'

将/root/data目录下所有.txt的文件中,-helloworld替换成china

-helloworld替换成china
# cat a.txt
helloworld1
helloworld2
#  find /root/data/ -name '*.txt' | xargs sed -i 's#helloworld#china#g' 
# cat a.txt
china1
china2
-将china替换成helloworld
#  find /root/data/ -name '*.txt' -ok sed -i 's#china#helloworld#g' {} \; 
< sed ... /root/data/bk.txt > ? y
< sed ... /root/data/a.txt > ? y
[root@localhost ~/data]# cat a.txt
helloworld1
helloworld2

将/root/data目录下所有.txt结尾的普通文件打包成压缩文件

#  tar z cvf  data.tar.gz `find /root/data -type f -name '*.txt'`;ls -l 
-rw-r--r--. 1 root root  66 1月  19 10:46 a.txt
-rw-r--r--. 1 root root  61 1月  19 10:46 bk.txt
-rw-r--r--. 1 root root 221 1月  19 10:56 data.tar.gz
#  tar tf data.tar.gz 
root/data/bk.txt
root/data/a.txt
#  tar tvf data.tar.gz 
-rw-r--r-- root/root        61 2022-01-19 10:46 root/data/bk.txt
-rw-r--r-- root/root        66 2022-01-19 10:46 root/data/a.txt
※tar c 归档
  tar x 释放
  tar -v 输出详细信息
  tar -f 使用归档文件,后接文件名
  tar -p 保留原始文件及目录权限
  tar -t 列表查看包内文件
  tar -C 解包释放到指定目录

删除/home/sun目录下,除dir3以外所有文件和目录

# find . ! -name 'dir3' -exec rm -rfv {} \;
实际案例:
站点目录下所有文件被植入广告链接(script language=javascript src=www.baidu.com)
解决思路:确认问题-制定方案-备份文件-解决方案-处理结果确认-追查根源-提供改善方案
方法:
find . -type f | xargs sed -i 's#script language=javascript src=www.baidu.com##g'
# echo script language=javascript src=www.baidu.com > a.txt
# cat a.txt
script language=javascript src=www.baidu.com
# find . -type f | xargs sed -i 's#script language=javascript src=www.baidu.com##g'
# cat a.txt

找到文件移动到指定目录下

# mv ` find . -name "*.sh" ` dir3/;tree

020.xargs 将标准输入转换成命令行参数

    xargs -n 数字        指定每行的输出个数
    xargs -d 分隔符      自定义分隔符
    xargs -i             以{}代替前面的结果
    xargs -I  自定义替代符号      指定一个符号替代前面的结果,而不是-i参数默认的{}
    xargs -0(数字0)      用null代替空格作为分隔符,配合find命令的-print0选项使用
# cat test.txt
hello world
java python
# xargs -n 2 < test.txt
hello world
java python
#  xargs   < test.txt
hello world java python
# xargs -n 3 < test.txt
hello world java
python
# cat test.txt |  xargs -n  3
hello world java
python
# cat test.txt |  xargs -d  o
hell  w rld
java pyth n

# find . -name "*.txt" |  xargs -i  mv {} testname.txt
# ls -l
总用量 4
-rw-r--r--. 1 root root 24 5月  17 23:09 testname.txt
# cat testname.txt
hello world
java python

021.rename 重命名文件。通过字符串替换的方式批量修改文件名

    语法格式:rename from to file
    file 可以用通配符*,代指所有文件

[root@svnt01 test]# ls -l
总用量 4
-rw-r--r--. 1 root root  0 5月  17 23:17 st_2022-05-17.1.log
-rw-r--r--. 1 root root  0 5月  17 23:17 st_2022-05-17.2.log
-rw-r--r--. 1 root root  0 5月  17 23:17 st_2022-05-17.3.log
-rw-r--r--. 1 root root  0 5月  17 23:17 st_2022-05-17.4.log
-rw-r--r--. 1 root root 24 5月  17 23:09 testname.txt
[root@svnt01 test]#  rename  '.log' '.jpg' *.log
[root@svnt01 test]# ls -l
总用量 4
-rw-r--r--. 1 root root  0 5月  17 23:17  st_2022-05-17.1.jpg 
-rw-r--r--. 1 root root  0 5月  17 23:17  st_2022-05-17.2.jpg 
-rw-r--r--. 1 root root  0 5月  17 23:17  st_2022-05-17.3.jpg 
-rw-r--r--. 1 root root  0 5月  17 23:17  st_2022-05-17.4.jpg 
-rw-r--r--. 1 root root 24 5月  17 23:09 testname.txt

022.basename 显示文件名或目录名。

用于显示去除路径和文件后缀部分的文件名或目录名

语法格式:
basename [文件或目录] [后缀]  ,后缀名可选参数

[root@svnt01 Desktop]# tree
.
└── test
    ├── st_2022-05-17.4.jpg
    └── testname.txt

1 directory, 2 files
[root@svnt01 Desktop]#  basename  test/st_2022-05-17.4.jpg
st_2022-05-17.4.jpg
[root@svnt01 Desktop]#  basename  test/testname.txt
testname.txt

023.dirname 显示目录或文件的路径

[root@svnt01 Desktop]# ls -l test/test1/testname.txt
-rw-r--r--. 1 root root 24 5月  17 23:09 test/test1/testname.txt
[root@svnt01 Desktop]# dirname test/test1/testname.txt
test/test1

024.chattr 命令用于改变文件的扩展属性

和chmod相比,chmod只是改变文件读写执行权限,更底层的属性控制是由chattr来改变的

    mode:
    +  增加参数
    -  移除参数
    =  更新为指定参数
    a  只能向文件中添加数据,多用于服务器日志文件安全
    i  只读,设定文件不能被删除、改名、写入或新增内容
    A  告诉系统不要修改这个文件的最后访问时间
    参数选项
    -R 递归更改目录属性
    -V 显示命令执行过程
#设置只能往文件里追加内容,但不能删除文件 
[root@svnt01 test]# cat st_2022-05-17.4.log
hello world
[root@svnt01 test]#  lsattr  st_2022-05-17.4.log
---------------- st_2022-05-17.4.log
[root@svnt01 test]#  chattr +a  st_2022-05-17.4.log
[root@svnt01 test]# lsattr st_2022-05-17.4.log
-----a---------- st_2022-05-17.4.log
[root@svnt01 test]# rm -rfv st_2022-05-17.4.log
rm: 无法删除"st_2022-05-17.4.log": 不允许的操作
[root@svnt01 test]# echo python >> st_2022-05-17.4.log
[root@svnt01 test]# cat st_2022-05-17.4.log
hello world
python
[root@svnt01 test]# echo python > st_2022-05-17.4.log
-bash: st_2022-05-17.4.log: 不允许的操作
#给文件加锁,使其只能只读 
[root@svnt01 test]# lsattr st_2022-05-17.4.log
---------------- st_2022-05-17.4.log
[root@svnt01 test]#  chattr +i  st_2022-05-17.4.log
[root@svnt01 test]# lsattr st_2022-05-17.4.log
----i----------- st_2022-05-17.4.log
[root@svnt01 test]# rm -rfv st_2022-05-17.4.log
rm: 无法删除"st_2022-05-17.4.log": 不允许的操作
[root@svnt01 test]# echo hello > st_2022-05-17.4.log
-bash: st_2022-05-17.4.log: 权限不够
[root@svnt01 test]# echo hello >> st_2022-05-17.4.log
-bash: st_2022-05-17.4.log: 权限不够

企业安全优化实战

避免恶意删除.bash_history历史记录或者重定向到/dev/null,又因为系统需要向这个文件写入历史记录,因此采用追加模式,只增不减
[root@svnt01 ~]#  locate   .bash_history
/root/.bash_history
[root@svnt01 ~]# lsattr /root/.bash_history
---------------- /root/.bash_history
[root@svnt01 ~]#  chattr +a   /root/.bash_history
[root@svnt01 ~]# lsattr /root/.bash_history
-----a---------- /root/.bash_history

025.lsattr 查看文件的扩展属性

    -R 递归查看目录的扩展属性
    -a 显示所有文件包括隐藏文件的扩展属性
    -d 显示目录的扩展属性
    -v 详细显示属性信息。
# lsattr -R .
# lsattr -aR .
# lsattr -adR .
# ls -d test1/
test1/
# ls -ld test1/
drwxr-xr-x. 2 root root 26 5月  17 23:24 test1/
# lsattr -d test1/
---------------- test1/

----i--------e-- filename

-:表示未设置该属性。
a:表示文件仅用于追加(append-only)。
i:表示文件不可更改(immutable)。
d:表示目录是不可删除的。
e:表示文件有扩展属性,如文件权限、所有者和修改时间。

026.file 用于显示文件的类型

-b 输出信息使用精简格式,不输出文件名

[root@svnt01 test]# file st_2022-05-17.4.log
st_2022-05-17.4.log: ASCII text
[root@svnt01 test]#  file  test1/
test1/: directory
[root@svnt01 test]# file -b st_2022-05-17.4.log
ASCII text
[root@svnt01 test]#  file -b  test1/
directory
[root@svnt01 test]# file *
st_2022-05-17.4.log: ASCII text
test1:               directory

027.md5sum 用于计算和校验文件的MD5值

软件或文件都有自己固定的文件格式或信息,如果被修改可能会导致用不了或者其他问题。
基于MD5不可逆性,如果数值一致,则表示文件没有被修改,反之,则表示修改了。

    -b 二进制模式读取文件
    -c 从指定文件中读取MD5校验值,并进行校验
    -t 文本模式读取文件,这是默认模式
    --quiet 校验文件使用的参数,验证通过不输出OK
    --status 校验文件使用的参数,不输出任何信息,可以通过命令的返回值判断
#md5sum -b test.txt
6005507a965339080a912a64ad7c5b9d *test.txt
#md5sum test.txt > md5.log
#cat md5.log
6005507a965339080a912a64ad7c5b9d  test.txt
#echo hello > test.txt
#md5sum -c md5.log
test.txt: 失败
md5sum: 警告:1 个校验和不匹配
#md5sum --status -c md5.log
#echo $?
1

#md5sum test* > md5.log
#cat md5.log
d41d8cd98f00b204e9800998ecf8427e  test1.txt
b1946ac92492d2347c6235b4d2611184  test.txt
#echo hello > test1.txt
#md5sum -c md5.log
test1.txt: 失败
test.txt: 确定
md5sum: 警告:1 个校验和不匹配

028.chown 改变文件或目录的用户和用户组

    chown 用户 文件或目录     仅授权用户
    chown :组  文件或目录     仅授权组,:可以用.来代替
    chown 用户:组  文件或目录 授权用户和组,用户和组必须存在

    -R 递归更改目录的用户和用户组
#chown sun test1.txt
#ls -l
总用量 12
-rw-r--r-- 1 sun  root  6 6月  11 17:04 test1.txt

#groupadd group1
#chown  :group1 test1.txt
#ls -l
总用量 12
-rw-r--r-- 1 sun  group1  6 6月  11 17:04 test1.txt

#chown sun:group1 test.txt
#ls -l
总用量 12
-rw-r--r-- 1 sun  group1  6 6月  11 17:04 test1.txt
-rw-r--r-- 1 sun  group1  6 6月  11 17:01 test.txt

#chown -R  root:root .
#ls -l
总用量 12
-rw-r--r-- 1 root root 87 6月  11 17:04 md5.log
-rw-r--r-- 1 root root  6 6月  11 17:04 test1.txt
-rw-r--r-- 1 root root  6 6月  11 17:01 test.txt

029.chmod 改变文件或目录权限

只有文件属主和超级用户root才能够执行这个命令

    两种格式:权限字母和操作符表达式;数字
    -R 递归处理指定目录以及其子目录下的所有文件
    u:user
    g:group
    o:other
    a:ugo总和
    rwx:421
#chmod a= test.txt
#ls -l test.txt
---------- 1 root root 6 6月  11 17:01 test.txt
#chmod u+rw test.txt
#ls -l test.txt
-rw------- 1 root root 6 6月  11 17:01 test.txt
Try 'chmod --help' for more information.
#chmod go+r test.txt
#ls -l test.txt
-rw-r--r-- 1 root root 6 6月  11 17:01 test.txt
#chmod 000 test.txt
#ls -l test.txt
---------- 1 root root 6 6月  11 17:01 test.txt
#chmod 644 test.txt
#ls -l test.txt
-rw-r--r-- 1 root root 6 6月  11 17:01 test.txt
#chmod ug=rw,o= test.txt
#ls -l test.txt
-rw-rw---- 1 root root 6 6月  11 17:01 test.txt

030.chgrp 更改文件用户组,功能被chown取代

#chgrp group1 test.txt ;ls -l
总用量 8
-rw-r--r-- 1 root root   87 6月  11 17:04 md5.log
-rw-rw---- 1 root group1  6 6月  11 17:01 test.txt
#chgrp -R group1 . ; ls -l
总用量 8
-rw-r--r-- 1 root group1 87 6月  11 17:04 md5.log
-rw-rw---- 1 root group1  6 6月  11 17:01 test.txt

031.umask 显示或设置权限掩码

通过八进制的数值来定义用户创建文件或目录的默认权限

     文件默认最大权限666(-rw-rw-rw-)
    目录默认最大权限777(-rwx-rwx-rwx) 
        umask 为 0022时
    创建文件权限为:      创建目录权限为:
        6 6 6                7 7 7
     -  0 2 2             -  0 2 2
    ------------          ---------------
        6 4 4                7 5 5
#umask
0022
#touch umasktest.txt
#mkdir umasktest
#ls -l
drwxr-xr-x 2 root root  6 6月  11 17:23 umasktest       ←755 
-rw-r--r-- 1 root root  0 6月  11 17:23 umasktest.txt   ←644

修改配置文件使umask永久生效

[root@aws ec2-user]#cat /etc/bashrc | grep -n "umask"
66:    # By default, we want umask to get set. This sets it for non-login shell.
71:       umask 002
73:       umask 022
[root@aws ec2-user]# sed -n '65,74p' /etc/bashrc 
    # By default, we want umask to get set. This sets it for non-login shell.
    # Current threshold for system reserved uid/gids is 200
    # You could check uidgid reservation validity in
    # /usr/share/doc/setup-*/uidgid file
    if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
       umask 002
    else
       umask 022
    fi
 预设的情况之下, root 的 umask 为 022 而一般使用者则为 002 
[sun@aws home]$ umask
0002
[root@aws home]# umask
0022

第3章 文件过滤及内容编辑处理命令

032.cat 合并文件或查看文件内容

concatenate,连接多个文件并且打印到屏幕输出,或者重定向到指定文件中

cat命令5大常用功能


       1.查看文件内容   cat a.txt
       2.多个文件合并成一个  cat a.txt b.txt > ab.txt
       3.创建编辑新文件  cat > file1.txt   
                        快捷键ctrl + d 或 ctrl+ c结束编辑
       4.非交互式的编辑或追加内容到文件尾部。
          生产工作中最重要的一个应用,必须掌握。 
         格式: cat >> file1.txt << EOF
                I am good learner.welcome to my blog.
                EOF
       5. 清空文件内容。 
          文件还在,内容清空
          cat /dev/null > file1.txt 

[root@aws ec2-user]#cat > cat.txt
1
2
[root@aws ec2-user]#cat cat.txt
1
2
[root@aws ec2-user]#cat >> cat.txt << EOF
> I am good at Linux.And I am pround of my study.
> yes,that's right!
> EOF
[root@aws ec2-user]#cat cat.txt
1
2
I am good at Linux.And I am pround of my study.
yes,that's right!

cat 命令的参数选项和说明

    cat -n 显示输出内容行号
    cat -b 和-n功能类似,但会忽略显示空白行行号
    cat -s 遇到连续两行以上的空白行时,就替换为一行空白行 
[root@aws ec2-user]#cat > cat.txt
1
2

4
[root@aws ec2-user]#cat cat.txt
1
2

4
[root@aws ec2-user]#cat -n cat.txt
     1  1
     2  2
     3
     4  4
[root@aws ec2-user]#cat -b cat.txt
     1  1
     2  2

     3  4

实际生产中,习惯使用grep -v " ^$ " filename 来过滤掉所有空行  
[root@aws ec2-user]# grep -v '^$' cat.txt
1
2
4

cat末尾追加文本,039 paste同行追加

033.tac 是cat的反向拼写,因此命令的功能为反向显示文件内容

[root@aws home]# cat test.txt
1
2
[root@aws home]# tac test.txt
2
1

034.more一页一页地显示文件内容

more命令的功能类似于cat,但cat命令是将整个文件的内容一次性显示在屏幕上,而more则会一页一页地显示文件内容。但more的功能还是比较简单的,有一个增强版的命令是less

[root@aws home]# more /etc/services
# /etc/services:

空格键 往下一页
b     往上一页
enter 一行
=     输出当前行号
/     搜索

[root@aws home]# more  -5  /etc/services  #每次只显示5行
# /etc/services:

035.less:分页显示文件内容

如果使用man less查看less的帮助文档,会发现官方的解释是less为more的反义词(opposite of more)。但less命令的名称只是个文字游戏,它是more命令的高级版本(less这个名称来自俗语“越简单就越丰富”,即less is more)。less命令的基本功能类似于more命令,可以分页显示文件内容,但比more的功能更强大。less命令在读取文件内容时,并不是像more、vi命令一样,要一次性将整个文件加载之后再显示,而是会根据需要来加载文件的内容,这样打开文件的速度会更快。而且less命令支持[page up]、[page down]等按键的功能,可以通过该功能向前或向后翻看文件,这样更容易查看一个文件的内容。

036.head:显示文件内容头部

head命令用于显示文件内容头部,它默认输出文件的开头10行。
[root@aws home]# head -n 5 /etc/services
# /etc/services:
# $Id: services,v 1.55 2013/04/14 ovasik Exp $
#
# Network services, Internet style
# IANA services version: last updated 2013-04-10

[root@aws home]#  head -qn  1 test.txt /etc/services #-q不显示文件名
---START---
# /etc/services:
[root@aws home]#  head -vn  1 test.txt /etc/services #-v显示文件名
==> test.txt <==
---START---

==> /etc/services <==
# /etc/services:


037.tail:显示文件内容尾部

tail命令用于显示文件内容的尾部,它默认输出文件的最后10行

# tail -5 /etc/passwd
ec2-instance-connect:x:997:995::/home/ec2-instance-connect:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
chrony:x:996:994::/var/lib/chrony:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash

-f和-F的使用

-f参数,当文件不存在时就会报错退出命令

-F参数,当文件不存在时会报错但不会退出,一直等待文件生成,不会退出命令

[root@aws home]# tail -f test.log
tail: 无法打开"test.log" 读取数据: No such file or directory
tail: 没有剩余文件
[root@aws home]# tail -F test.log
tail: 无法打开"test.log" 读取数据: No such file or directory
tail: "test.log" 已被建立,正在跟随新文件的末尾
hello
|


038.cut:从文本中提取一段文字并输出

cut命令从文件的每一行剪切字节、字符或字段,并将这些字节、字符或字段输出至标准输出。

-b 以字节为单位分割
[root@aws home]# cat test1.txt
1234567
1234567
[root@aws home]# cut -b 3,5,6 test1.txt
356
356
[root@aws home]# cut -b 2-4,6 test1.txt
2346
2346

-d 指定分割符号
-f 输出第几列

[root@aws home]# cut -d : -f 1  /etc/passwd
root
。。。
ec2-user
[root@aws home]# cut -d : -f 1  /etc/passwd | grep ec2-user
ec2-user

039.paste:合并文件

-d 指定合并分隔符,默认TAB

-s 每个文件占用一行

第一种情况

user和passwd分开两个文件

[root@aws home]# cat username.log
user001
user002
user003
user004
[root@aws home]# cat passwd.log
123
adb
2321asd
123213dfd 
[root@aws home]# paste username.log passwd.log
user001 123
user002 adb
user003 2321asd
user004 123213dfd
[root@aws home]# paste -d '=' username.log passwd.log
user001=123
user002=adb
user003=2321asd
user004=123213dfd
[root@aws home]# paste -s username.log
user001 user002 user003 user004
[root@aws home]# paste -s passwd.log
123     adb     2321asd 123213dfd
[root@aws home]# paste -s username.log passwd.log
user001 user002 user003 user004
123     adb     2321asd 123213dfd

第二种情况

user和passwd在同一个文件中

[root@aws home]# cat userpass.log
 user001 
123
 user002 
adb
 user003 
2321asd
 user004 
123213dfd
[root@aws home]# paste  -sd '=\n'  userpass.log  #轮流用=和\n做分隔符 
user001=123
user002=adb
user003=2321asd
user004=123213dfd
或者xargs -n 2 两行输出为一行
[root@aws home]# xargs -n 2 < userpass.log
user001 123
user002 adb
user003 2321asd
user004 123213dfd
[root@aws home]# xargs -n 2 < userpass.log | sed 's# #=#g'
user001=123
user002=adb
user003=2321asd
user004=123213dfd

040.sort:文本排序

sort命令将输入的文件内容按照指定的规则进行排序,然后将排序结果输出。

-n 按数值大小排序

-r 倒序排列

-u 去除重复行

[root@aws home]# cat test.txt
2
8
9
9
10
[root@aws home]# sort test.txt
10
2
8
9
9
[root@aws home]# sort -n  test.txt
2
8
9
9
10
[root@aws home]# sort -rn test.txt
10
9
9
8
2
[root@aws home]# sort -un test.txt
2
8
9
10

041.join:按两个文件的相同字段合并

join命令针对每一对具有相同内容的输入行,整合为一行输出到标准输出,默认情况下是把输入的第一个字段作为连接字段,字段之间用空格隔开。join命令可以处理具有相关性的文件。

注意:在处理之前,需要进行统一排序

[root@aws home]# cat username.log
user001 male
user002 female
user003 male
user004 male
[root@aws home]# cat userage.log
user001 10yearsold
user002 12yearsold
user003 13yearsold
user004 14yearsold
[root@aws home]# sort username.log > username.logn
[root@aws home]# sort userage.log > userage.logn
[root@aws home]# join username.logn userage.logn
user001 male 10yearsold
user002 female 12yearsold
user003 male 13yearsold
user004 male 14yearsold

042.uniq:去除重复行,通常用sort排序,而后再用uniq

-c 去除重复行,统计出现次数

-d 只显示重复的行

-u 只显示唯一的行

# uniq ipaddr.txt
10.61.133.54
10.62.133.44
10.62.133.29
10.61.133.19
10.62.133.19
10.61.133.47
10.61.133.54
10.62.133.44
10.62.133.29
# sort -n ipaddr.txt | uniq -c
      1 10.61.133.19
      1 10.61.133.47
      2 10.61.133.54
      1 10.62.133.19
      2 10.62.133.29
      2 10.62.133.44
# sort -n ipaddr.txt |uniq -d
10.61.133.54
10.62.133.29
10.62.133.44
# sort -n ipaddr.txt |uniq -u
10.61.133.19
10.61.133.47
10.62.133.19
# sort -n ipaddr.txt | uniq -c|sort -n
      1 10.61.133.19
      1 10.61.133.47
      1 10.62.133.19
      2 10.61.133.54
      2 10.62.133.29
      2 10.62.133.44

043.wc:统计文件的行数、单词数或字节数

-l 显示行数

-w 显示单词数

-c 显示字节数

-m 显示字符数

# cat wc_test.txt
hello world
hellohhhhhhhh
我你他
# wc wc_test.txt
 3  4 36 wc_test.txt
# wc -c wc_test.txt
36 wc_test.txt
# wc -m wc_test.txt   #一个汉字占一个字符,2个字节 
30 wc_test.txt

# who
ec2-user pts/0        2022-07-15 15:33 (203.90.236.205)
# who | wc -l
1


044.iconv:转换文件的编码格式

[root@aws ec2-user]# cat wc_test.txt
hello world
hellohhhhhhhh
我你他
[root@aws ec2-user]# file wc_test.txt
wc_test.txt:  UTF-8  Unicode text
[root@aws ec2-user]# iconv -f utf-8 -t gb2312 wc_test.txt > gb2312.txt
[root@aws ec2-user]# cat gb2312.txt
hello world
hellohhhhhhhh
▒▒▒▒▒▒
[root@aws ec2-user]# file gb2312.txt
gb2312.txt: ISO-8859 text

[root@aws ec2-user]# iconv -l
The following list contains all the coded character sets known. 
....
[root@aws ec2-user]# iconv -l | grep -i 'gb' | xargs -n 5
CN-GB// CSGB2312// CSISO58GB1988// EBCDIC-CP-GB// GB//
GB2312// GB13000// GB18030// GBK// GB_1988-80//
GB_198880// ISO646-GB//


编码转换的时候,如果你的源格式设定为 GB2312 的话,而且在转换成 UTF-8 的时候,发现程序会报“illegal input sequence at position xxxx”的错误。GB2312 是国标里面一个最小也是最早的中文编码标准。其中,只涵盖了 6,763 个汉字。这个时候,你可以用 GB18030 做为源格式来进行转换。GB18030 是最新的国家标准,包含了 27,564 个汉字,而且向下兼容 GB2312 和 GBK

045.dos2unix:将DOS格式文件转换成UNIX格式

将DOS(Windows系统)格式文件转换成UNIX格式(DOS/MAC to UNIX text file format converter)。DOS下的文本文件是以“\r\n”作为换行标志的,而UNIX下的文本文件是以“\n”作为换行标志的。所以在Linux中使用Windows的文本文件时,常常会出现错误。为了避免这种错误,Linux提供了两种文本格式相互转化的命令:dos2unix和unix2dos,dos2unix把Windows文件的“\r\n”转化成Linux文件的“\n”,unix2dos把Linux文件的“\n”转化成Windows文件的“\r\n”。

[root@aws sun]#  cat -A  test.sh
#/bin/bash ^M$ 
for i in `date +%y%m%d` ;{^M$
^Iecho $i^M$
}[root@aws sun]# dos2unix test.sh
dos2unix: converting file test.sh to Unix format ...
[root@aws sun]# cat -A test.sh
#/bin/bash $ 
for i in `date +%y%m%d` ;{$
^Iecho $i$

046.diff:比较两个文件的不同

diff命令可以逐行比较bash文件的内容,并输出文件的差异。也可以比较目录

-y 并列显示文件的异同

-c 使用上下文输出

-u 使用统一格式输出

-W 和-y搭配使用,指定显示宽度

[root@aws sun]# cat >> diff1.txt <<EOF
> 1
> 2
> 3
> EOF
[root@aws sun]# cat >> diff2.txt <<EOF
> 2
> 3
> 4
> EOF
[root@aws sun]# diff -y diff1.txt diff2.txt
1                                                             <
2                                                               2
3                                                               3
                                                              > 4
[root@aws sun]# diff diff1.txt diff2.txt
1d0
< 1
3a3
> 4
[root@aws sun]# diff -y -W 10 diff1.txt diff2.txt
1   <
2       2
3       3
    >   4
[root@aws sun]# diff -c diff1.txt diff2.txt
*** diff1.txt   2022-07-19 21:08:15.537390388 +0800
--- diff2.txt   2022-07-19 21:08:38.953472285 +0800
***************
*** 1,3 ****
- 1
  2
  3
--- 1,3 ----
  2
  3
+ 4
[root@aws sun]# diff -u diff1.txt diff2.txt
--- diff1.txt   2022-07-19 21:08:15.537390388 +0800
+++ diff2.txt   2022-07-19 21:08:38.953472285 +0800
@@ -1,3 +1,3 @@
-1
 2
 3
+4

047.vimdiff:可视化比较工具

vimdiff调用vim打开文件,可以同时打开多个文件,并且会以不同的颜色来区分文件的差异。

:qa退出所有文件

:wqa保存并退出所有文件

:wa保存所有文件

:qa!强制退出并不保存所有文件

048.rev:反向输出文件内容

rev命令可以按行反向输出文件内容。

[root@aws sun]# cat diff1.txt
line:1
line:2
line:3
[root@aws sun]# rev diff1.txt
1:enil
2:enil
3:enil

049.tr:替换或删除字符

tr命令从标准输入中替换、缩减或删除字符,并将结果写到标准输出。

'am' → 'RW', 不是am替换成RW,而是所有a替换成R;所有m替换成W

[root@aws sun]# cat tr.txt
I am a teacher!
you are old 66666!
[root@aws sun]# tr 'a-z' 'A-Z' < tr.txt
I AM A TEACHER!
YOU ARE OLD 66666!
[root@aws sun]# tr 'A-Z' 'a-z' < tr.txt
i am a teacher!
you are old 66666!
[root@aws sun]# tr 'am' 'RW' < tr.txt
I RW R teRcher!
you Rre old 66666!
[root@aws sun]# cat tr.txt
I am a teacher!
you are old 66666!

050.tee:多重定向

把数据重定向到给定文件和屏幕上。

-a 向文件追加内容而不是覆盖

[root@aws sun]# ls
diff1.txt  tr.txt
[root@aws sun]# ls | tee tr.txt
diff1.txt
tr.txt
[root@aws sun]# cat tr.txt
diff1.txt
tr.txt
[root@aws sun]# ls |  tee -a  tr.txt
diff1.txt
tr.txt
[root@aws sun]# cat tr.txt
diff1.txt
tr.txt
diff1.txt
tr.txt

第4章 文本处理三剑客

051.grep-在Linux下查找某个文件中的某个关键字

grep [keyword] [路径] -R 
例如要查找在/home/1jiao7lou/ 路径中含有6688.cc关键字的文件,则使用
grep 6688.cc /home/1jiao7lou -R
还可以指定在哪一行
‍grep 6688.cc /home/1jiao7lou -Rn

[root@localhost /home/sun]# grep hello . -R
./test.txt:helloworldze999
./work1/work2/test2.txt:helloworldze999

grep 查询关键字上下文

[root@aws ec2-user]# cat test.txt | grep -C 2 hello #上下文2行
for
now
hello
world
for 
[root@aws ec2-user]# cat test.txt | grep -A 2 hello  #只看下面2行
hello
world
for
[root@aws ec2-user]# cat test.txt | grep -B 2 hello   #只看上面2行
for
now
hello

-w 精准匹配到,不加-w就会匹配包含的所有内容

[root@aws sun]# grep  -E i 'zi1024|sun' /etc/passwd
sun:x:1001:1001::/home/sun:/bin/bash
zi1024:x:1003:1003::/home/zi1024:/bin/bash
zi10241:x:1004:1004::/home/zi10241:/bin/bash
zi10242:x:1005:1005::/home/zi10242:/bin/bash
[root@aws sun]# grep  -w Ei 'zi1024|sun' /etc/passwd
sun:x:1001:1001::/home/sun:/bin/bash
zi1024:x:1003:1003::/home/zi1024:/bin/bash
[root@aws sun]# grep  -n w 'zi1024' /etc/passwd
29:zi1024:x:1003:1003::/home/zi1024:/bin/bash
[root@aws sun]# grep  -v  'diff' tr.txt
hello
world
666
tr.txt
tr.txt

egrep在文件内查找指定的字符串

egrep命令来自于英文词组“extended Global Regular Expression Print”的缩写,其功能是用于在文件内查找指定的字符串。egrep命令的执行效果与grep -E相似,使用参数也可以直接参考grep命令,不同点在于改良了grep命令原有的一些字符串处理功能,支持了更多正则表达式规则。

[root@AWS ec2-user]# cat persons.txt
001,sun,CEO
002,li,CTO
003,zhang,COO
004,mao,CFO
[root@AWS ec2-user]# egrep -n 'zhang|sun' persons.txt
1:001,sun,CEO
3:003,zhang,COO
[root@AWS ec2-user]# egrep -n -v 'zhang|sun' persons.txt
2:002,li,CTO
4:004,mao,CFO

052.sed:字符流编辑器

sed是Stream Editor(字符流编辑器)的缩写,简称流编辑器。sed是操作、过滤和转换文本内容的强大工具。常用功能包括对文件实现快速增删改查(增加、删除、修改、查询),其中查询的功能中最常用的两大功能是过滤(过滤指定字符串)、取行(取出指定行)。

[root@aws ec2-user]# cat > persons.txt << EOF
> 001,sun,CEO
> 002,li,CTO
> 003,zhang,COO
> EOF
[root@aws ec2-user]# sed ' 2 a   004,mao,CFO' persons.txt   #第2行之后追加 
001,sun,CEO
002,li,CTO
004,mao,CFO  #第2行之后
003,zhang,COO
[root@aws ec2-user]# sed ' 2i  004,mao,CFO' persons.txt  #在第2行插入 
001,sun,CEO
004,mao,CFO #第2行
002,li,CTO
003,zhang,COO

[root@aws ec2-user]# sed '4i 004,mao,CFO' persons.txt   #不存在的行,无法操作 
001,sun,CEO
002,li,CTO
003,zhang,COO

[root@aws ec2-user]# sed '3a 004,mao,CFO \n 005,zhao,CIO \n 006,wen,CSO' persons.txt
001,sun,CEO
002,li,CTO
003,zhang,COO
004,mao,CFO
005,zhao,CIO
006,wen,CSO
[root@aws ec2-user]# sed   -i  '3a 004,mao,CFO\n005,zhao,CIO\n006,wen,CSO' persons.txt
[root@aws ec2-user]# sed -n '3,6p' persons.txt    #n和p搭配使用用于查看 
003,zhang,COO
004,mao,CFO
005,zhao,CIO
006,wen,CSO
[root@aws ec2-user]# sed -n '4,6p' persons.txt
004,mao,CFO
005,zhao,CIO
006,wen,CSO
[root@aws ec2-user]# sed 's#zhang#qian#g' persons.txt
001,sun,CEO
002,li,CTO
003,qian,COO
004,mao,CFO
005,zhao,CIO
006,wen,CSO
[root@aws ec2-user]# grep -n 'sun' /etc/passwd
 27 :sun:x:1001:1001::/home/sun:/bin/bash
[root@aws ec2-user]# sed -n '25,28p' /etc/passwd   #查看25,26,27,28行信息 
tcpdump:x:72:72::/:/sbin/nologin
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
sun:x:1001:1001::/home/sun:/bin/bash
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash

053.awk

awk不仅仅是Linux系统中的一个命令,而且其还是一种编程语言,可以用来处理数据和生成报告(Excel)。处理的数据可以是一个或多个文件,它是Linux系统最强大的文本处理工具,没有之一。

[root@aws ec2-user]# sed -n '25,28p' /etc/passwd > passwd.txt
[root@aws ec2-user]# cat -n passwd.txt
     1  tcpdump:x:72:72::/:/sbin/nologin
     2  ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
     3  sun:x:1001:1001::/home/sun:/bin/bash
     4  ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
 #打印指定行 
[root@aws ec2-user]# awk  'NR== 4' passwd.txt
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# sed -n '4p' passwd.txt
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
 #打印指定区间行 
[root@aws ec2-user]# awk  'NR==2,NR==4'  passwd.txt
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
sun:x:1001:1001::/home/sun:/bin/bash
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# sed  -n '2,4p'  passwd.txt
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
sun:x:1001:1001::/home/sun:/bin/bash
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# awk '{print NR,$0}' passwd.txt  # 等价于 cat -n passwd.txt 
1 tcpdump:x:72:72::/:/sbin/nologin
2 ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
3 sun:x:1001:1001::/home/sun:/bin/bash
4 ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# awk 'NR==2,NR==4 {print NR,$0}' passwd.txt
2 ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
3 sun:x:1001:1001::/home/sun:/bin/bash
4 ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# awk -F ':' '{print $1,$3,$NF}' passwd.txt  #输出1,3,最后一列信息 
tcpdump 72 /sbin/nologin
ec2-user 1000 /bin/bash
sun 1001 /bin/bash
ztadmn 1002 /bin/bash
 #字符串替换 
[root@aws ec2-user]# awk '{gsub ("/sbin/nologin","/bin/bash",$0);print $0}' passwd.txt
tcpdump:x:72:72::/:/bin/bash
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
sun:x:1001:1001::/home/sun:/bin/bash
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
[root@aws ec2-user]# sed  's# /sbin/nologin # /bin/bash #g'  passwd.txt
tcpdump:x:72:72::/:/bin/bash
ec2-user:x:1000:1000:EC2 Default User:/home/ec2-user:/bin/bash
sun:x:1001:1001::/home/sun:/bin/bash
ztadmn:x:1002:1002::/home/ztadmn:/bin/bash
 #实际应用案例,统计域名访问次数 
[root@aws ec2-user]# cat webip.txt
http://www.1.html
http://www.2.html
http://www.3.html
http://www.1.html
http://www.2.html
[root@aws ec2-user]# awk -F "/" '{print $3}' webip.txt | sort -n
www.1.html
www.1.html
www.2.html
www.2.html
www.3.html
[root@aws ec2-user]#
[root@aws ec2-user]# awk -F "/" '{print $3}' webip.txt | sort -n |uniq -c
      2 www.1.html
      2 www.2.html
      1 www.3.html
# df | awk '/\//'  显示包含/的行
/dev/xvda2     10473452 2488808 7984644   24% /
# df / | awk '/\//{print $4}'
7984636

第5章 Linux信息显示与搜索文件命令

054.uname:显示系统信息

-a 显示全部信息

-m 显示计算机硬件架构

-n 显示主机名

-r 内核发行版本号

-s 内核名称

-v 内核版本

-p 主机处理器类型

-o 显示操作系统名称

-i 硬件平台

[root@aws ec2-user]# uname -a  
Linux aws 4.14.281-212.502.amzn2.x86_64 #1 SMP Thu May 26 09:52:17 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
[root@aws ec2-user]# uname -m
x86_64
[root@aws ec2-user]# uname -r
4.14.281-212.502.amzn2.x86_64
[root@aws ec2-user]# uname -n
aws
[root@aws ec2-user]# uname -v
#1 SMP Thu May 26 09:52:17 UTC 2022
[root@aws ec2-user]# uname -p
x86_64
[root@aws ec2-user]# uname -o
GNU/Linux
[root@aws ec2-user]# uname -i
x86_64
#通常用法
[root@aws ec2-user]# echo `uname -r`
4.14.281-212.502.amzn2.x86_64
[root@aws ec2-user]# ln -s /usr/src/kernels/`uname -r` kernelname
[root@aws ec2-user]# ll
lrwxrwxrwx 1 root root  46 7月  20 16:36 kernelname -> /usr/src/kernels/4.14.281-212.502.amzn2.x86_64


055.hostname:显示或设置系统的主机名

-a 显示主机别名

-i 显示主机IP地址,这个参数以来DNS解析,比较慢,推荐 -I

-I 显示主机所有IP地址,不依赖DNS解析,速度快

-s 显示短格式的主机名

[root@aws ec2-user]# hostname
aws
[root@aws ec2-user]# hostname -a

[root@aws ec2-user]# hostname -i
fe80::105a:acff:feb7:98bb%eth0 172.31.86.78
[root@aws ec2-user]# hostname -I
172.31.86.78
[root@aws ec2-user]# hostname -s
aws

056.dmesg:系统启动异常诊断

内核环形缓冲区是物理内存的一部分,用于保存内核的日志消息。它具有固定的大小,这意味着一旦缓冲区已满,较旧的日志记录将被覆盖。

内核环形缓冲区的内容同时会保存在/var/log目录中,即名称为dmesg的文件里

-c 显示信息后,清除环形缓冲区中内容

-s bufsize 设置缓冲区大小,默认16384(2.1.113内核或更高)

-n level 显示信息等级

[root@AWS sun]# dmesg
....
[   18.183866] RPC: Registered tcp transport module.
[   18.196102] RPC: Registered tcp NFSv4.1 backchannel transport module.
[root@AWS sun]# ll -h /var/log/dmesg
-rw-r--r-- 1 root root 0 7月  22 14:45 /var/log/dmesg

057.stat 显示文件或文件系统状态

-f 显示文件所在分区的文件系统状态而非文件状态

-c 使用指定输出格式代替默认值

支持格式:
  %a 八进制权限
  %A 可读性较好的方式输出权限
  %b 计算已分配块数
  %B 以字节为单位输出%b所报告的每个块大小
  %F 文件类型
  %i inode节点

[root@masternode01 /]# stat /root/
  文件:"/root/"
  大小:4096        块:8          IO 块:4096   目录
设备:fd00h/64768d  Inode:33574977    硬链接:9
权限:(0550/dr-xr-x---)  Uid:(    0/    root)   Gid:(    0/    root)
最近访问:2022-07-24 12:20:39.109985487 +0800
最近更改:2022-07-06 23:25:43.618849534 +0800
最近改动:2022-07-06 23:25:43.618849534 +0800
创建时间:-
[root@masternode01 /]# stat -f /root/
  文件:"/root/"
    ID:fd0000000000 文件名长度:255     类型:xfs
块大小:4096       基本块大小:4096
    块:总计:4452864    空闲:2197003    可用:2197003
Inodes: 总计:8910848    空闲:8658177
[root@masternode01 /]# stat -c %A /root/
dr-xr-x---
[root@masternode01 /]# stat -c %a /root/
550
[root@masternode01 /]# stat -c %i /root/
33574977
[root@masternode01 /]# stat -c %F /root/
目录
[root@masternode01 /]# stat -c %F /etc/passwd
普通文件

058.du 统计磁盘空间使用情况

帮助我们找出占用磁盘空间过多的文件

-a 显示全部文件大小

-h 以可读的方式查看 ,单位K M G

-s 显示文件的总大小

—max=depth=N 显示N级子目录大小

—exclude=dir 略过指定的目录文件

[root@masternode01 test]# du 
4  ./1directory
0  ./2directory
0  ./3directory
0  ./4directory
0  ./5directory
4  .
[root@masternode01 test]# du -h
4.0K  ./1directory
0  ./2directory
0  ./3directory
0  ./4directory
0  ./5directory
4.0K  .
[root@masternode01 test]# du -sh
4.0K  .
[root@masternode01 test]# tree
.
├── 1directory
│   └── hello
├── 2directory
│   ├── hello
│   └── hello1
│       └── hello
├── 3directory
├── 4directory
│   └── hello
└── 5directory

6 directories, 4 files
[root@masternode01 test]# du -h
4.0K  ./1directory
4.0K  ./2directory/hello1
8.0K  ./2directory
0  ./3directory
4.0K  ./4directory
0  ./5directory
16K  .
[root@masternode01 test]# du -h --max-depth=1 
4.0K  ./1directory
8.0K  ./2directory
0  ./3directory
4.0K  ./4directory
0  ./5directory
16K  .
[root@masternode01 test]# du -h --max-depth=2
4.0K  ./1directory
4.0K  ./2directory/hello1
8.0K  ./2directory
0  ./3directory
4.0K  ./4directory
0  ./5directory
16K  .
[root@masternode01 test]# du -h /test/ --exclude=/test/2directory
4.0K  /test/1directory
0     /test/3directory
4.0K  /test/4directory
0     /test/5directory
8.0K  /test/

059.date

-d 显示字符串所描述的时间,而非当前时间

面试题:将日志中时间格式转换成指定格式

使用date转换格式,然后用awk拼接,最后用bash执行命令

# cat test.log 
Sun Jul 24 12:53:54 CST 2022 is the start time
Sat Jul 23 12:54:07 CST 2022 is stopped
# date -d "Sun Jul 24 12:53:54 CST 2022" "+%F %T"  
2022-07-24 12:53:54
# awk -F "is" '{print "echo $(date -d \" "$1" \" \"+%F %T \") "  ,$2}' test.log 
echo $(date -d " Sun Jul 24 12:53:54 CST 2022  " " +%F %T ")   the start time
echo $(date -d " Sat Jul 23 12:54:07 CST 2022  " " +%F %T ")   stopped
# awk -F "is" '{print "echo $(date -d \" "$1" \" \"+%F %T \") "  ,$2}' test.log |bash
2022-07-24 12:53:54 the start time
2022-07-23 12:54:07 stopped
root@masternode01 1directory]# date +%T%n%F
13:12:29
2022-07-24

# date +%a
Sun
# date +%A
Sunday
# date +%y%m%d
220724
# date +%T
13:14:39
# date +%H-%M-%S
13-15-04
# date -d "+1day"
Mon Jul 25 13:15:47 CST 2022
# date -d "-1day"
Sat Jul 23 13:15:52 CST 2022
# date -d "1day"
Mon Jul 25 13:15:56 CST 2022
# date -d "1year"
Mon Jul 24 13:16:07 CST 2023
# date -d "-10year"
Tue Jul 24 13:16:14 CST 2012


060.echo 打印一行文本

# echo hello world !
hello world !
# echo "hello world !"   
bash: !": event not found  #!在linux中有特殊功能,如果想打印,放在“”外面
# echo "hello world" !
hello world !
转义符
# echo -e "hello\tworld"
hello  world
# echo -e "hello\nworld"
hello
world
多重打印
# echo "line1";echo "line2"
line1
line2
不换行输出
# echo -n "line1";echo "line2"
line1line2
字体背景标注颜色
# echo -e "\033[40;37m blackbg whitefont \033[0m"
 blackbg whitefont 
# echo -e "\033[41;37m blackbg whitefont \033[0m"
 blackbg whitefont 
# echo -e "\033[42;37m blackbg whitefont \033[0m"
 blackbg whitefont 
# echo -e "\033[43;37m blackbg whitefont \033[0m"
 blackbg whitefont 
# echo -e "\033[44;37m blackbg whitefont \033[0m"
 blackbg whitefont 
打印变量内容
# f1=1234
# echo $f1
1234

061.watch 监视命令执行情况

-n 命令执行的间隔时间,默认为2s

-d 高亮显示命令结果的变动之处

-t 不显示头部信息

ctrl + c退出

# watch -n 2 -d netstat -ant
# watch -n 2 -d -t netstat -ant

062.which 显示命令的全路径

which命令查找的范围是PATH环境变量的路径

默认在PATH路径中从前往后查找命令,查找到就停止匹配。使用-a选项将遍历所有PATH路径,输出所有匹配项

# which ls
alias ls='ls --color=auto'
  /usr/bin/ls
# which -a ls
alias ls='ls --color=auto'
  /usr/bin/ls
  /bin/ls
# ll /usr/bin/ls
-rwxr-xr-x. 1 root root 117608 8月  20 2019 /usr/bin/ls
# ll /bin/ls
-rwxr-xr-x. 1 root root 117608 8月  20 2019 /bin/ls
# ls -i /usr/bin/ls
50527327 /usr/bin/ls
# ls -i /bin/ls
50527327 /bin/ls
# ls -lh /bin/ls
-rwxr-xr-x. 1 root root 115K 8月  20 2019 /bin/ls
# which cd
/usr/bin/cd
# which -a cd
/usr/bin/cd
/bin/cd

whereis 显示命令及相关文件全路径

用于定位命令的可执行文件(-b),源文件(-s),man帮助文件的路径(-m)

# whereis svn
svn: /usr/bin/svn /usr/share/man/man1/svn.1.gz
# whereis visudo
visudo: /usr/sbin/visudo /usr/share/man/man8/visudo.8.gz
# whereis -s svn
svn:                   #没有找到源文件
# whereis -b svn
svn: /usr/bin/svn
# whereis -m svn
svn: /usr/share/man/man1/svn.1.gz

063.locate 快速定位文件路径

linux中有个名为mlocate.db的数据库文件,包含系统文件的文件名和路径。

locate命令查找不用遍历磁盘,而是直接查找mlocate.db文件。

但如果是新添加的文件,mlocate.db里面就没有记录,可以使用updatedb命令更新数据库。当然,系统自带定时更新。

-i 忽视大小写

# mkdir /test2/
# locate test2
 # updatedb 
# locate test2
/test2
# whereis test2  
test2:

# mkdir test3
# locate test3/
# locate test3
 # updatedb 
# locate -i TEST3
/root/test3

updatedb 更新mlocate.db数据库

# locate mlocate.db
/usr/share/man/man5/mlocate.db.5.gz
 /var/lib/mlocate/mlocate.db 
/var/lib/mlocate/mlocate.db.A4xpkc
# ls -lh /var/lib/mlocate/mlocate.db 
-rw-r----- 1 root slocate 6.9M 7月  24 14:23 /var/lib/mlocate/mlocate.db

如果没有安装

yum install mlocate -y

第6章 文件备份与压缩命令

064.tar 打包备份

在Linux系统里,tar是将多个文件打包在一起,并且可以实现解压打包的文件的命令。是系统管理员最常用的命令之一,tar命令不但可以实现对多个文件进行打包,还可以对多个文件打包后进行压缩。

打包是指将一大堆文件或目录变成一个总的文件,压缩则是将一个大的文件通过一些压缩算法变成一个小文件。

tar命令选项的使用有点特殊,对于CentOS、Linux来说,“tar-z”和“tar z”的效果相同,加或不加“-”这个符号都是可以的。

常用操作:

-z 使用gzip压缩格式进行打包,后缀名为 *.tar.gz

-j 使用bzip2压缩格式进行打包,后缀名为 *.tar.bz2

使用 gzip要比bzip2快,但是bzip2会获得比 gzip高的压缩比率

====通用gzip打包====
[root@sun testuser]# tar zcvf test.tar.gz test/
test/
test/1.html
test/2.html
test/3.html
test/dir/
test/dir/dirtest.html
[root@sun testuser]# tar zcvf test.tar.gz2 test
test/
test/1.html
test/2.html
test/3.html
test/dir/
test/dir/dirtest.html
====不解压查看内容,省略z,自动匹配查看格式====
[root@sun testuser]# tar z t vf test.tar.gz
drwxr-xr-x root/root         0 2022-08-22 06:46 test/
-rw-r--r-- root/root         0 2022-08-22 06:45 test/1.html
-rw-r--r-- root/root         0 2022-08-22 06:45 test/2.html
-rw-r--r-- root/root         0 2022-08-22 06:45 test/3.html
drwxr-xr-x root/root         0 2022-08-22 06:46 test/dir/
-rw-r--r-- root/root         0 2022-08-22 06:46 test/dir/dirtest.html
[root@sun testuser]# mkdir ./tar
====打包到指定目录====
[root@sun testuser]# tar zxvf test.tar.gz -C ./tar/
test/
test/1.html
test/2.html
test/3.html
test/dir/
test/dir/dirtest.html
====排除打包====
[root@sun testuser]# tar zcvf exclude.gz test --exclude=test/dir
test/
test/1.html
test/2.html
test/3.html
test/dir/
test/dir/dirtest.html
 tar: The following options were used after any non-optional arguments in archive create or update mode.  These options are positional and affect only arguments that follow them.  Please, rearrange them properly.
tar: --exclude ‘test/dir’ has no effect
tar: Exiting with failure status due to previous errors 
###报错原因:###
末尾追加排除路径,适用tar1.30版本以下,否则报错。
解决:1.查看tar版本;2.排除项放在包名后
[root@sun testuser]# tar --version 
tar (GNU tar) 1.30
[root@sun testuser]# tar zcvf exclude.gz --exclude=test/dir test
test/
test/1.html
test/2.html
test/3.html
[root@sun testuser]# tar zcvf exclude.gz --exclude=test/dir --exclude=test/1.html test
test/
test/2.html
test/3.html
[root@sun testuser]# tar tvf exclude.gz                         drwxr-xr-x root/root         0 2022-08-22 06:46 test/
-rw-r--r-- root/root         0 2022-08-22 06:45 test/2.html
-rw-r--r-- root/root         0 2022-08-22 06:45 test/3.html

提示tar: 从成员名中删除开头的“/”,首先,出现这种提示是正常的,无须担心,它只是linux系统对用户的一个善意的提醒,并不影响打包操作,如果不想看到这个提示信息,在执行打包命令时,带上选项P就可以了。

065.gzip:压缩或解压文件

gzip命令用于将一个大的文件通过压缩算法(Lempel-Ziv coding(LZ77))变成一个小的文件。gzip命令不能直接压缩目录,因此目录需要先用tar打包成一个文件,然后tar再调用gzip进行压缩。

[root@sun test]# ll
total 12
-rw-r--r--. 1 root root 17 Aug 23 08:46 1.html
-rw-r--r--. 1 root root 36 Aug 23 08:46 2.html
-rw-r--r--. 1 root root 36 Aug 23 08:47 3.html
drwxr-xr-x. 2 root root 26 Aug 22 06:46 dir
====把目录下文件单独压缩成.gz====
[root@sun test]# gzip *.html
[root@sun test]# ls
1.html.gz  2.html.gz  3.html.gz  dir
###
gzip命令缺点是压缩后源文件不见了
,压缩和解压都会自动删除源文件
###
====压缩解压保留源文件====
[root@sun test]# gzip -c 1.html > 1.html.gz
[root@sun test]# ll
total 16
-rw-r--r--. 1 root root 17 Aug 23 08:46 1.html
-rw-r--r--. 1 root root 42 Aug 23 08:56 1.html.gz
-rw-r--r--. 1 root root 36 Aug 23 08:46 2.html
-rw-r--r--. 1 root root 36 Aug 23 08:47 3.html
drwxr-xr-x. 2 root root 26 Aug 22 06:46 dir
====不解压显示每隔压缩文件信息====
[root@sun test]# gzip -l *.gz
         compressed        uncompressed  ratio uncompressed_name
                 42                  17   0.0% 1.html
                 45                  36  44.4% 2.html
                 45                  36  44.4% 3.html
                132                  89 -20.2% (totals)
====查看、比较压缩包内容====
[root@sun test]# zcat 1.html.gz
htllsfs s fs f f
[root@sun test]# zdiff 1.html.gz 2.html.gz
1c1
< htllsfs s fs f f
---
> htllsfs s fssssssssssssssssssss f f
====解压、显示过程=====
[root@sun test]# gzip -dv *.gz
1.html.gz:        0.0% -- replaced with 1.html
2.html.gz:       44.4% -- replaced with 2.html
3.html.gz:       44.4% -- replaced with 3.html
[root@sun test]# ll
total 12
-rw-r--r--. 1 root root 17 Aug 23 08:46 1.html
-rw-r--r--. 1 root root 36 Aug 23 08:46 2.html
-rw-r--r--. 1 root root 36 Aug 23 08:47 3.html
drwxr-xr-x. 2 root root 26 Aug 22 06:46 dir

066.zip: 打包和压缩文件

zip压缩格式是Windows与Linux等多平台通用的压缩格式。和gzip命令相比,zip命令压缩文件不仅不会删除源文件,而且还可以压缩目录。

====压缩目录====
# zip **.zip ./目录名         
====递归压缩目录下所有文件====
# zip **.zip  -r  ./目录名 
====除外压缩====   
# zip **.zip  -r  ./目录名  -x  目录名/除外文件名   

067.unzip:解压zip文件

unzip命令可以解压zip命令或其他压缩软件压缩的zip格式的文件。

====查看.zip压缩文件====
# unzip -l **.zip
====解压文件====
# unzip -v **.zip     显示解压过程
# unzip -o **.zip     解压不提示是否覆盖
====指定解压目录====
# unzip **.zip  -d  /解压目录   

068.scp:远程文件复制

scp命令用于在不同的主机之间复制文件,它采用SSH协议来保证复制的安全性。

scp命令每次都是全量完整复制,因此效率不高,适合第一次复制时使用,增量复制建议使用rsync命令替代。

====推送(本地复制到远程目录)文件或目录====
# scp /etc/hosts 10.0.0.1:/tmp     第一次scp需要对方登录密码
# scp -p /etc/hosts 10.0.0.1:/tmp   #-p保持文件属性传输
# scp -rp /tmp 10.0.0.1:/tmp       #复制目录需要加-r 
====拉取(远程复制到本地目录)文件或目录====
# scp -rp 10.0.0.1:/tmp .  

069.rsync:文件同步工具

rsync是一款开源的、快速的、多功能的、可实现全量及增量的本地或远程数据镜像同步备份的优秀工具。

rsync命令三种常见模式:

1)本地模式
2)远程shell访问模式
3)rsync守护进程模式
====源地址带与不带/的区别====
# rsync -av  /data1/  /data2    #复制目录内的内容,而不是复制目录本身
# rsync -av  /data1   /data2    #复制目录本身及目录下内容
====1)本地赋值模式====
# rsync -av /etc/hosts /tmp
        -a 以递归方式传输文件,并保持文件属性,相当于-rtopgDI
        -v 详细模式输出,传输时的进度等信息
===问题:一个目录下有几十万个文件,用什么方式可以最快删除所有文件?===
# mkdir /null
# rsync -av --delete /null/  /tmp/
        --delete 使tmp目录内容和空目录null一致,不同的文件及目录将被删除
====2)远程shell访问模式====
2.1 拉取
# rsync -av 10.0.0.1:/tmp/ /tmp
2.2 推送
# rsync -av /tmp/ 10.0.0.1:/tmp/
====3)rsync守护进程模式====
利用SSH隧道模式(-e)加密拉取推送文件及目录
# rsync -av -e `ssh -p 22` /tmp/ 10.0.0.1:/tmp/
        ssh -p 22 指定SSH传输端口为22

-z  传输时进行压缩以提高传输速率
生产场景常用选项-avz

第7章 Linux用户管理及用户信息查询命令

070.useradd:创建用户

useradd命令可用于创建新的用户或者更改用户的信息。

1)使用useradd常规添加用户工作原理流程

在使用useradd命令时,若不加任何参数选项,后面直接跟所添加的用户名,那么系统首先会读取/etc/login.defs(用户定义文件)和/etc/default/useradd(用户默认配置文件)文件中所定义的参数和规则,然后根据所设置的规则添加用户,同时还会向/etc/passwd(用户文件)和/etc/group(组文件)文件内添加新用户和新用户组记录,向/etc/shadow(用户密码文件)和/etc/gshadow(组密码文件)文件里添加新用户和组对应的密码信息的相关记录。同时系统还会根据/etc/default/useradd文件所配置的信息建立用户的家目录,并将/etc/skel中的所有文件(包括隐藏的环境配置文件)都复制到新用户的家目录中。

# useradd user001
# grep -w user001 /etc/passwd
====指定初始组,uid====
# useradd -g primarygroup -u 900 user001
====修改其他用户信息====
# useradd -u 900 -s /bin/sh -c SysUser -G root,group1 -e "2022/08/24" -f 2 -d /tmp/user001 user001
uid:900
shell解释器:/bin/sh
comment:SysUser
附属组:root,group1
用户过期时间:2022/08/24
过期后两天停权
# id user001
# chage -l user001

使用useradd-D参数的结果实际上就是修改用户的初始配置文件/etc/default/useradd
useradd-D的功能完全可以使用vim/etc/default/useradd编辑修改后来替代。
# useradd -D -e "2022/08/24"


071.usermod:修改用户信息

usermod命令用于修改系统已经存在的用户的账号信息。

需求如下:将范例7-3添加的用户inca的用户注释信息修改为“TmpUser”,UID修改为999,归属修改为用户组root、sa、tech成员,其Shell类型为/sbin/nologin,设置家目录为/home/inca,用户过期时间为2018/07/12,过期后30天停权。

# usermod -u 999 -s /sbin/nologin -c TmpUser -G root,sa,tech 
  -e "2018/07/12" -f 30 -d /home/inca inca

072.userdel:删除用户

userdel命令用于删除指定的用户及与该用户相关的文件。

# userdel inca
====-r删除用户及家目录====
# userdel -r inca

在实际工作中尽量不要使用userdel删除用户,而是采用在/etc/passwd里注释用户的方法,防止用户误删带来的系统及服务不正常。读者需要谨慎使用-r参数,因为-r参数会将用户家目录下的所有目录和文件都删除,导致数据不可逆地丢失。

073.groupadd:创建新的用户组

groupadd命令用于创建新的用户组。但groupadd命令的用途一般不大,因为useradd命令在创建用户的同时还会创建与用户同名的用户组。

# groupadd -g 345 group01
# tail -1 /etc/group
# tail -1 /etc/gshadow

074.groupdel:删除用户组

groupdel命令用于删除指定的用户组,此命令的使用频率极低,了解即可。

# groupdel group01

075.passwd:修改用户密码

passwd命令可以修改用户密码及密码过期时间等内容,是工作中很常用的命令。普通用户和超级用户都可以运行passwd命令,但普通用户只能更改自身的用户密码,超级用户root则可以设置或修改所有用户的密码。

====修改密码====
# passwd user01
# echo "123456" | passwd --stdin user01
--stdin 参数能从标准输入获取密码,在工作中批量设置密码时这个命令很有用。
====显示账号密码信息====
# passwd -S userl01
要求user01用户7天内不能更改密码,60天以后必须修改密码,
过期前10天通知用户,过期后30天后禁止用户登录。
# passwd -n 7 -x 60 -w 10 -i 30 user01
# passwd -S user01
# chage -l user01
-n:修改密码最短天数  -x:修改密码最长天数


076.chage:修改用户密码有效期

chage命令用于查看或修改用户密码的有效期,有些参数和passwd的功能相同。

要求user01用户7天之内不能更改密码,60天以后必须修改密码,
过期前10天通知user01用户,过期后30天后禁止用户登录。
前文用passwd已经实现过这个案例了,将使用chage实现同样的功能
# chage -m 7 -M 60 -W 10 -I 30 user01
或者第二种写法:
# chage -m7 -M60 -W10 -I30 user01
# chage -l user01

077.chpasswd:批量更新用户密码

chpasswd命令用于从标准输入中读取一定格式的用户名、密码来批量更新用户的密码,其格式为“用户名:密码”。

[root@user01 ~]# chpasswd #<==在命令行输入chpasswd,回车。
root:123456      #<==格式 用户名:密码,用户必须存在才行。
user01:123456    #<==一行一个
[root@user01 ~]#      
#<==在新的空行输入Ctrl+D结束输入。 
====生产案例:批量修改====
[root@user01 ~]# cat pass.txt 
stu01:10027515
...省略若干行...
stu08:10029884
stu09:10026667
stu10:10025899


078.su:切换用户

su命令用于将当前用户切换到指定用户或者以指定用户的身份执行命令或程序。

·“su用户名”虽然能够切换到对应的用户,但是登录后的环境变量信息还是切换之前用户的环境变量信息。

如果仅希望在某用户下执行命令,而不用直接切换到该用户下来操作,可以使用su-用户名-c"命令"的方式。

079.visudo:编辑sudoers文件

visudo命令是专门用来编辑/etc/sudoers这个文件的,同时提供语法检查等功能。/etc/sudoers文件是sudo命令的配置文件。

# visudo
相当于直接执行 vim /etc/sudoers,但使用命令方式更安全,比较推荐
====/etc/sudoers/====
oldboy  ALL=(ALL)  ALL  
username 授权角色   可执行命令
#<==此行是98行,将oldboy提权为root身份。
oldgirl ALL=(ALL) /usr/sbin/useradd,/usr/sbin/userdel            
#<==授权oldgirl可以以root身份添加和删除用户权限。 
====语法检查====
# visudo -c

080.sudo:以另一个用户身份执行命令

通过sudo命令,可以让普通用户在执行指定的命令或程序上,拥有超级用户的权限,进行分类,并且有针对性地(精细)将不同的命令授予指定的普通用户,同时普通用户不需要知道root密码就可以得到授权,这个授权可以用visudo配置管理。

====查看当前用户被授予的sudo权限集合====
# sudo -l 

在生产环境中,通常会禁止root远程登录,不过,系统会为每个运维人员建立一个普通账号,然后根据运维人员的需求,通过sudo控制登录系统的权限,事实证明这是一个不错的权限管理方式。

081.id:显示用户与用户组的信息

显示指定用户的用户ID(UID)和组ID(GID)等信息

# id
# id user01
# id -gn   -n不显示数字,显示名称
# id -u
# id -un

082.w:显示已登录用户信息

w命令可以显示已经登录系统的用户,并显示用户正在执行的命令

# w
上面的第1行输出依次显示了当前的系统时间、系统从启动到现在已经运行的时间、
登录到系统中的用户数和系统平均负载。平均负载是指在1min、5min、15min内系统的负载状况。
# w -h  不显示前两行标题信息

083.who:显示已登录用户信息

who命令能够显示已经登录系统的用户,以及系统的启动时间等信息

# who
# who -b 显示启动时间
# who -d 显示已退出用户
# who -l 显示登录的进程
# who -H 显示标题
# who -H -a 显示最全的登录用户信息

084.users:显示已登录用户

users命令可以显示已经登录系统的用户。如果是同一用户登录多次,则登录几次就会显示几次用户名。

# users

085.whoami:显示当前登录的用户名

# whoami

086.last:显示用户登录列表

last命令能够从日志文件 /var/log/wtmp读取信息并显示用户最近的登录列表。

# last
# last user01  显示user01用户登录情况

087.lastb:显示用户登录失败的记录

lastb命令可以从日志文件 /var/log/btmp中读取信息,并显示用户登录失败的记录,用于发现系统登录异常。

# lastb  如果发现未知登录失败信息,需要考虑是否遭到暴力破解登录

088.lastlog:显示所有用户的最近登录记录

lastlog命令从日志文件/var/log/lastlog中读取信息,并显示所有用户的最近登录记录,用于查看系统是否有异常登录。

# lastlog

第8章 Linux磁盘与文件系统管理命令

089.fdisk:磁盘分区工具

fdisk是Linux下常用的磁盘分区工具。受mbr分区表的限制,fdisk工具只能给小于2TB的磁盘划分分区。如果使用fdisk对大于2TB的磁盘进行分区,虽然可以分区,但其仅识别2TB的空间,所以磁盘容量若超过2TB,就要使用parted分区工具(后面会讲)进行分区。

====查看当前系统所有磁盘分区信息====
# fdisk -l  
# fdisk -l /dev/sdb名
====磁盘分区====
# fdisk /dev/sdb名
====格式化磁盘====
# mkfs.ext4 /dev/sdb1   只有格式化后的磁盘才能挂载到系统中使用
====挂载====
# df -h
# mount /dev/sdb1 /mnt
# df -h
# vi /etc/fstab   开机自动挂载磁盘
  /dev/sdb1  /mnt  ext4  defaults 0 0
或者
# vi /etc/rc.local
  mount /dev/sdb1 /mnt

090.partprobe:更新内核的硬盘分区表信息

partprobe命令用于在硬盘分区发生改变时,更新Linux内核中的硬盘分区表数据。有时在使用fdisk、part命令对硬盘进行分区后,会发现找不到新分区,此时需要重启系统才能使修改生效,但使用partprobe可以不重启系统就让修改的分区表生效。

# partprobe /dev/sdb

091.tune2fs:调整ext2/ext3/ext4文件系统参数

tune2fs命令可以调整或查看ext2/ext3/ext4文件系统的参数,比如可以调整Linux文件系统开机自检的周期,此参数在工作中极少使用

====查看sda1设备挂载次数====
# tune2fs -l /dev/sda1 | grep -i Mount
Mount count:20  挂载次数
Maximum mount count: -1 强制挂载次数为-1,关闭自检功能
====设置挂载次数====
# tune2fs -C 30 /dev/sda1
# tune2fs -l /dev/sda1 | grep -i Mount
====设置强制自检的挂载次数====
# tune2fs -c 40 /dev/sda1
# tune2fs -l /dev/sda1 | grep -i Mount
# tune2fs -c -1 /dev/sda1  关闭自检功能
====设置强制自检的时间间隔====
# tune2fs -i 10 /dev/sda1  设置每10天检查一次
# tune2fs -l /dev/sda1 | grep -i check
# tune2fs -i 0  /dev/sda1  还原正常状态

092.parted:磁盘分区工具

对于小于2TB的磁盘可以用fdisk和parted命令进行分区,这种情况一般采用fdisk命令,但对于大于2TB的磁盘则只能用parted分区,且需要将磁盘转换为GPT格式。

[root@oldboy ~]# parted -l    #<==显示所有磁盘分区的信息。
Model: VMware, VMware Virtual S (scsi)  #<==磁盘型号,这里采用VMware虚拟化演示。
Disk /dev/sda: 8590MB                   #<==磁盘大小。
Sector size (logical/physical): 512B/512B     #<==扇区大小,为msdos,这是适合fdisk分区的类型。
Partition Table: msdos   #<==分区表类型。
Number Start End       Size      Type        File system   Flags 
1      1049kB  106MB   105MB   primary  ext4            boot 
2      106MB   7017MB  6911MB  primary  ext4 
3      7017MB  8590MB  1573MB  primary  linux-swap(v1)
Number:分区编号。
Start:分区开始位置。
End:分区结束位置。
Size:分区大小。
Type:分区类型。
primary:为主分区。
File system:文件系统,例如ext4、swap等。
Flags:标志位,boot为启动分区。

# parted /dev/sdb
后续格式化分区、分区挂载、开机自动挂载等步骤和fdisk分区完全相同

093.mkfs:创建Linux文件系统

mkfs命令用于在指定的设备(或硬盘分区等)上创建格式化并创建文件系统,fdisk和parted等分区工具相当于建好了房,把房子(硬盘),分成几居室(分区),mkfs就相当于对不同的居室进行功能划分(卧室,客厅)。

mkfs只是一个前端命令,它通过-t参数指定文件系统类型后会调用相应的命令mkfs.filesystemtype。因此可以直接使用mkfs.ext4这个命令创建ext4文件系统。

# ls /sbin/mkfs*     查看各种不同文件系统创建的命令
# mkfs -t ext4 -v /dev/sdb    -v显示详细信息
或者
# mkfs.ext4 /dev/sdb

094.dumpe2fs:导出ext2/ext3/ext4文件系统信息

dumpe2fs命令用于导出ext2/ext3/ext4文件系统内部的相关信息,例如:文件系统的组成包含超级快、块组、inode、block等信息。

====查看系统的inode信息。====
# dumpe2fs /dev/sda1 | egrep -i "inode size|inode count"
# df -i  查看inode数量和使用情况
====查看系统的block信息====
# dumpe2fs /dev/sda1 | egrep -i "block size|block count"

095.resize2fs:调整ext2/ext3/ext4文件系统大小

resize2fs命令用于扩容或收缩未挂载的ext2/ext3/ext4文件系统。

在Linux 2.6或更高版本的内核中,该命令还支持在线扩容已经挂载的文件系统,该命令常用来针对LVM扩容后的分区使用。

生产场景一般是事先规划好不会出现扩容需求,非I/O密集应用可以采用LVM实现规范动态扩容。

096.umount:卸载文件系统

# umount /mnt/
# umount -lf /mnt 强制卸载

097.df:报告文件系统磁盘空间的使用情况

显示文件系统磁盘空间的使用情况。

# df
# df /usr/
# df -h  人类可读的格式显示容量
# df -ih 显示inode使用情况
# df -t ext4
# df -T   显示文件系统的类型


范例:向磁盘写入数据提示如下错误:No space left on device,然后通过df-h查看磁盘空间,结果发现磁盘没满,那么请问这可能是什么原因?

解答:可能是inode数量被耗尽了。用df-i可查看inode的使用情况。

解决方法:①小文件太多,这时需要用到ls|xargs rm-f命令进行删除。②定时任务

098.mkswap:创建交换分区

mkswap命令是在Linux系统里创建交换分区的工具,当系统没有交换分区或交换分区不够用时,可以新建一个交换分区。

====创建交换分区====
可以将一块磁盘分区后再针对某一个分区创建交换分区,
也可以将整块磁盘创建为交换分区,但需要-f参数。
# mkswap /dev/sdb
# mkswap -f /dev/sdb

099.swapon:激活交换分区

使用mkswap命令创建交换分区后,分区并没有生效,还需要使用swapon命令使之生效。

====激活交换分区====
# free -m       查看系统内存包括虚拟内存swap交换分区
# swapon /dev/sdb
# free -m
====查看交换分区====
# swapon -s

100.swapoff:关闭交换分区

如果需要回收磁盘资源,则可以使用swapoff关闭交换分区释放磁盘空间。

在关闭交换分区时,需要确保交换分区没有被使用。
否则系统会提示“device is busying”的错误信息。
# swapoff /dev/sdb
# free -m
# swapoff -a   关闭所有交换分区
# free -m

101.sync:刷新文件系统缓冲区

sync命令会将内存缓冲区内的数据强制刷新到磁盘。

Linux内核为了达到最佳的磁盘操作效率,默认会先在内存中将需要写入到磁盘的数据缓存起来,然后等待合适的时机将它们真正写入到磁盘中,这在绝大多数情况下都是没有任何问题的,而且还提高了系统的效率

但是如果系统出现宕机、掉电等情况,就可能会导致有些文件内容没能保存下来。

当然,在Linux系统正常关机或者重启时,会将缓冲区中的内容自动同步到磁盘中。我们也可以手工执行sync命令,将内存中的文件缓冲内容强制写到磁盘中。

但是通常情况下没有必要执行这个命令,一是Linux内核会尽快让内存中的数据自动同步到磁盘上去,二是我们也无法预计什么时候会宕机、掉电。

# sync

第9章 Linux进程管理命令

102.ps:查看进程

ps命令用于列出执行ps命令的那个时刻的进程快照,如果想要动态地显示进程的信息,就需要使用top命令

参数的格式具体如下。

·UNIX格式:一个“-”开头。
·BSD格式:没有“-”开头。
·GNU长格式:两个“-”开头。
[root@sun ~]# ps
    PID TTY          TIME CMD
  22793 pts/0    00:00:00 su
  22797 pts/0    00:00:00 bash
·PID是进程的标识号。
·TTY是进程所属的终端控制台。
·TIME列是进程所使用的总的CPU时间。
·CMD列是正在执行的命令行。

常见操作组合:

[root@sun ~]# ps -ef   ← unix格式参数 -e显示所有 -f额外显示其他信息
UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 Aug22 ?        00:00:13 /usr/lib/systemd/systemd
·UID:进程被该UID所拥有。
·PPID:进程的父进程的标识号。
·C:CPU使用的资源百分比。
·STIME:进程开始的时间。

[root@sun ~]# ps aux   ← BSD格式参数 a显示所有 x额外显示其他信息 u用户信息
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  1.7 174824 14576 ?        Ss   Aug22   0:13 /usr/lib/syst

·%CPU:该进程使用掉的CPU资源百分比。

·%MEM:该进程所占用的物理内存百分比。

·VSZ:该进程使用掉的虚拟内存量(单位为Kbytes)。·RSS:该进程占用的固定的内存量(单位为Kbytes)。

·STAT:该进程目前的状态

[root@sun ~]# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          27  0.0  0.0      0     0 ?        SN   Aug22   0:00 [ksmd]
root          28  0.0  0.0      0     0 ?        SN   Aug22   0:03 [khugepaged]
root         664  0.0  0.3  75000  2536 ?        S<sl Aug22   0:00 /sbin/auditd
root         774  0.0  2.3 601744 19020 ?        Ssl  Aug22   0:13 /usr/sbin/Net
root        1037  0.0  0.1 226360  1552 tty1     Ss+  Aug22   0:00 /sbin/agetty
root       11233  0.0  0.0      0     0 ?        I<   Aug26   0:00 [ib_nl_sa_wq]
root       22517  0.0  0.0      0     0 ?        R    06:28   0:00 [kworker/u30:
ec2-user   22765  0.0  0.4 233792  4028 pts/0    Ss   08:49   0:00 -bash
root       22793  0.0  0.7 347420  6276 pts/0    S    08:49   0:00 su -
root       22797  0.0  0.4 236048  4012 pts/0    S    08:49   0:00 -bash
root       22831  0.0  0.0      0     0 ?        I    08:55   0:00 [kworker/0:0-
root       22832  0.0  0.4 268552  3988 pts/0    R+   08:55   0:00 ps aux

·R:正在运行,或者是可以运行。
·S:正在中断睡眠中,可以由某些信号(signal)唤醒。
·D:不可中断睡眠。
·T:正在侦测或者是停止了。
·Z:已经终止,但是其父进程无法正常终止它,从而变成zombie(僵尸)进程的状态。
·+:前台进程。
·l:多线程进程。
·N:低优先级进程。
·<:高优先级进程。

[root@sun ~]# ps -u ec2-user  ← 与指定用户相关的进程信息
    PID TTY          TIME CMD
  22753 ?        00:00:00 systemd
  22758 ?        00:00:00 (sd-pam)
  22764 ?        00:00:00 sshd
  22765 pts/0    00:00:00 bash

[root@sun ~]# ps -u ec2-user -l ← -l显示详细信息
F S   UID     PID    PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
4 S  1000   22753       1  0  80   0 - 22354 do_epo ?        00:00:00 systemd
5 S  1000   22758   22753  0  80   0 - 63156 -      ?        00:00:00 (sd-pam)
5 S  1000   22764   22749  0  80   0 - 40963 core_s ?        00:00:00 sshd
0 S  1000   22765   22764  0  80   0 - 58448 -      pts/0    00:00:00 bash

·F:代表这个进程的标志(flag),4代表使用者为super user。
·S:代表这个进程的状态(STAT)
·UID:进程被该UID所拥有。
·PID:进程的标识号。
·PPID:父进程的ID。
·C:CPU使用的资源百分比。
·PRI:Priority(优先执行序)的缩写。
·NI:Nice值。
·ADDR:指出该进程在内存的哪个部分。如果是个running的进程,则一般是“-”。
·SZ:使用掉的内存大小。
·WCHAN:目前这个进程是否正在运作当中,若为“-”则表示正在运作。

Nice理解:

PRI,即进程的优先级,或者通俗点说就是程序被CPU执行的先后顺序,此值越小进程的优先级别越高。
NI,就是我们所要说的nice值了,其表示进程可被执行的优先级的修正数值。

如前面所说,PRI值越小越快被执行,那么加入nice值后,将会使得PRI变为:PRI(new)=PRI(old)+nice。这样,当nice值为负值的时候,那么该程序将会优先级值将变小,即其优先级会变高,则其越快被执行。
在UNIX系统或者LINUX系统中,使用从-20到+19的一个可变数值来表示这个nice值(HP-UX系统的值范围是从0到39),并且在通常情况下,子进程会继承父进程的系统nice值。

具有最高优先级的程序,其nice值最低,所以在UNIX和LINUX系统中,值-20使得一项任务变得非常重要(HP-UX为0);与之相反,如果任务的 nice为+19(HP-UX为39),则表示它是一个高尚的、无私的任务,允许所有其他任务比自己享有宝贵的 CPU 时间的更大使用份额,这也就是nice的名称的意会来意。

[root@sun ~]# ps -eH ← -H显示进程树
    PID TTY          TIME CMD
      1 ?        00:00:13 systemd
    600 ?        00:00:03   systemd-journal
    628 ?        00:00:00   systemd-udevd
    664 ?        00:00:00   auditd
    701 ?        00:00:00   sssd
    729 ?        00:00:03     sssd_be
    730 ?        00:00:04     sssd_nss
   1033 ?        00:00:00   sshd
  22749 ?        00:00:00     sshd
  22764 ?        00:00:00       sshd
  22765 pts/0    00:00:00         bash
  22793 pts/0    00:00:00           su
  22797 pts/0    00:00:00             bash
  22899 pts/0    00:00:00               ps
  22753 ?        00:00:00   systemd
  22758 ?        00:00:00     (sd-pam)

103.pstree:显示进程状态树

如果不指定进程的PID号,或者不指定用户名称,则会以init进程为根进程,显示系统的所有进程信息;若指定用户或PID,则将以用户或PID为根进程,显示用户或PID对应的所有进程。

# pstree
# pstree username
# pstree -c -p  username  -c显示所有 -p显示进程号
# pstree -u               -u显示进程对应用户名称

104.pgrep:查找匹配条件的进程

pgrep命令可以查找匹配条件的进程号。

# pgrep ProcessName    显示进程PID
# pgrep -u username    显示所有指定用户的进程号

105.kill:终止进程

kill命令能够终止你希望停止的进程。

# kill -l      列出系统所有信号
# kill PID
# kill -9 PID  强制终止进程,可能会带来数据丢失,或终端无法恢复到正常状态

106.killall:通过进程名终止进程

使用kill命令终止进程还需要先获取进程的pid进程号,这个过程有点繁琐,而使用killall命令就可以直接用“killall进程名”这种形式终止进程。

# killall crond
# killall -w crond        -w等待几秒后结束命令操作
# killall -u username ProcessName  终止所有归属于username的ProcessName进程

107.pkill:通过进程名终止进程

pkill命令可通过进程名终止指定的进程。使用killall终止进程需要连续执行几次,而pkill可以杀死指定进程及其所有子进程。

====通过终端名终止进程====
# w
# pkill -t 终端名
# pkill -u username   终止指定用户所有进程,用户将被强制退出

108.top:实时显示系统中各个进程的资源占用状况

# top 
数字1,可监控每个逻辑CPU的状况
# top -a       按内存降序
# top -c       显示进程的整个命令路径
# top -d 3     信息更新周期3秒一次
# top -n 2     刷新两次后终止退出
# top -p PID   只显示指定PID进程信息

109.nice:调整程序运行时的优先级

nice命令是一个当程序启动时,修改程序运行优先级的命令。Linux的优先级范围是从-20(最大优先级)到19(最小优先级)。优先级越高的程序占用CPU的次数越多,反之亦然。

# nice            显示当前系统默认的程序运行优先级
# nice -n number  设置nice增加的值;
                  root取值范围:-20~19
                  普通用户取值范围:0~19,避免用户抢占系统资源;且仅能往高了调

110.renice:调整运行中的进程的优先级

nice命令常用于修改未运行的程序运行时的优先级,但是对于正在运行的进程,若想要修改其优先级,就需要用到renice命令。

# renice -n 5 -p PID  将PID的nice值调成5

111.nohup:用户退出系统进程继续工作

nohup命令可以将程序以忽略挂起信号的方式运行起来,被运行程序的输出信息将不会显示到终端。无论是否将nohup命令的输出重定向到终端,输出都将写入到当前目录的nohup.out文件中。如果当前目录的nohup.out文件不可写,则输出重定向到$HOME/nohup.out文件中。

# nohup ping www.baidu.com
# ps -ef | grep ping
# tail -f nohup.out
# kill PID

112.strace:跟踪进程的系统调用

strace是Linux环境下的一款程序调试工具,用于检查一个应用程序所使用的系统调用以及它所接收的系统信息。strace会追踪程序运行时的整个生命周期,输出每一个系统调用的名字、参数、返回值和执行所消耗的时间等

# strace -tt -f 进程名      -f 跟踪目标及其子进程 -tt行首加上时间精确到微秒
# strace -tt -f -p PID
====定向输出到文本====
# strace -c 进程名 -o strace.log  选项-c还能对进程所有的系统调用做一个统计分析


113.ltrace:跟踪进程调用库函数

ltrace能够跟踪进程的库函数调用,它会显现出调用了哪个库函数,而strace则是跟踪进程的每个系统调用。

# ltrace ProcessName
# ltrace -p PID

114.runlevel:输出当前运行级别

runlevel命令用于输出当前Linux系统的运行级别。

# runlevel
N 3
·0:停机·1:单用户模式·2:无网络的多用户模式·3:多用户模式
·4:未使用·5:图形界面多用户模式·6:重启

115.init:初始化Linux进程

init命令是Linux下的进程初始化工具,init进程是所有Linux进程的父进程,它的进程号为1。init命令的主要任务是依据配置文件“/etc/inittab”创建Linux进程。

# init 0    关机
# init 6    重启

116.service:管理系统服务

service命令用于对系统服务进行管理,比如启动(start)、停止(stop)、重启(restart)、重新加载配置(reload)、查看状态(status)等,该命令在CentOS 7里被systemctl取代。

# service --status-all
# service crond stop
# service crond start
# service crond restart
# service crond status

第10章 Linux网络管理命令

117.ifconfig:配置或显示网络接口信息

ifconfig命令用于配置网卡IP地址等网络参数或显示当前网络的接口状态,其类似于Windows下的ipconfig命令。此外,ifconfig命令在配置网卡信息时必须以root用户的身份来执行。如果系统中没有ifconfig命令,那就需要安装一下,安装命令为yum-y install net-tools。

Linux下的网络接口名类似于eth0、eth1和lo等,分别表示第1块网卡、第2块网卡和回环接口

使用ifconfig命令配置网卡信息仅会临时生效,重启网络或服务器配置就会失效

要想将上述配置信息永远地存储在服务器里,需要修改网卡的配置文件

/etc/sysconfig/network-scripts/ifcfg-eth**

118.ifup:激活网络接口

# ifup eth1
# ifconfig eth1

119.ifdown:禁用网络接口

# ifdown eth1
# ifconfig

120.route:显示或管理路由表

route命令可以显示或管理Linux系统的路由表,route命令设置的路由主要是静态路由。

路由分为静态路由和动态路由。

Linux上配置的路由都属于静态路由。静态路由规则是系统管理员使用route命令加入的,也就是通过手动输入的方式来加入的路由规则。

动态路由就是无需手动输入路由的规则,其路由规则是本机与不同的机器彼此经过路由程序(Routing daemon)相互交换路由规则而来的。

=====删除、添加路由====
# route -n   使用-n不进行DNS解析,显示速度会加快
# route del default      删除网关方法1
# route -n 
# route add default gw 10.0.0.2 dev eth0   添加网关,使用dev指明设备
# route -n 

有两个网段10.0.0.0/24和192.168.1.0/24,现在想要实现10网段的机器访问192网段的机器,其中有一台机器有两块网卡,eth0的IP地址为192.168.1.254,eth1的IP地址为10.0.0.254。

# route add -net 192.168.1.0/24 gw 10.0.0.254
或
# route add -net 192.168.1.0 netmask 255.255.255.0 dev eth1
====删除路由===
# route del -net 192.168.1.0/24 dev eth1

====路由永久生效===
# vi /etc/sysconfig/network-scripts/route-eth1
 192.168.1.0/24 via 10.0.0.254
# systemctl restart network 

121.arp:管理系统的arp缓存

什么是arp?即地址解析协议(ARP,Address Resolution Protocol),其主要功能是根据IP地址获取物理地址(MAC地址)。

arp命令用于操作本机的arp缓存区,它可以显示arp缓存区中的所有条目、删除指定的条目或者添加静态的IP地址与MAC地址的对应关系。

如果没有arp命令,可以执行
yum -y install net-tools
===显示arp缓存区的所有条目
[root@sun ~]# arp
Address                  HWtype  HWaddress           Flags Mask            Iface
ip-172-31-16-1.ec2.inte  ether   0a:e7:56:9a:6d:0f   C                     eth0
===以数字形式显示arp缓存区的所有条目
[root@sun ~]# arp -n
Address                  HWtype  HWaddress           Flags Mask            Iface
172.31.16.1              ether   0a:e7:56:9a:6d:0f   C                     eth0
===查询指定主机的arp条目
[root@sun ~]# arp -n 172.31.16.1
Address                  HWtype  HWaddress           Flags Mask            Iface
172.31.16.1              ether   0a:e7:56:9a:6d:0f   C                     eth0
===静态绑定ip地址与MAC地址
 ##当局域网有arp病毒时,可以用此方法绑定MAC,以防止中毒 
[root@sun ~]# arp -s 172.31.16.100 0a:e7:56:9a:6d:0f
[root@sun ~]# arp -n
Address                  HWtype  HWaddress           Flags Mask            Iface
172.31.16.1              ether   0a:e7:56:9a:6d:0f   C                     eth0
172.31.16.100            ether   0a:e7:56:9a:6d:0f   CM                    eth0
[root@sun ~]# arp -d 172.31.16.100
[root@sun ~]# arp -n
Address                  HWtype  HWaddress           Flags Mask            Iface
172.31.16.1              ether   0a:e7:56:9a:6d:0f   C                     eth0

=======
-n 显示数字ip地址
-s 设置指定主机IP地址与MAC地址的静态映射
-d 从arp缓存区删除指定主机arp条目
·Address:主机地址。·Hwtype:硬件类型。·Hwaddress:硬件地址。
·Flags Mask:记录标志,“C”表示arp高速缓存中的条目,“M”表示静态的arp条目。·Iface:网络接口。

122.ip:网络配置工具

ip命令用于显示或管理Linux系统的路由、网络设备、策略路由和隧道。

====显示网络设备属性
# ip link show dev eth0
# ip -s link show dev eth0  显示详细属性
# ip -s -s link show dev eth0
ip link 可以简写成 ip l
====关闭和激活网络设备
# ip link set eth0 up
# ip link set eth0 down
====修改网卡MAC地址
# ip link set eth0 address 0:0c:29:13:10:11
====查看网卡信息
# ip a  效果和ip addr一样
====添加或删除ip地址
# ip a add 10.0.0.1/24 dev eth0
# ip a show eth0
# ip a del 10.0.0.1/24 dev eth0
====创建ip别名
# ip a add 10.0.0.1/24 dev eth0 label eth0:1
# ip a show eth0
# ifconfig    别名用ip格式显示

====查看路由表
# ip route
# ip route | column -t  
使用column命令格式化,根据空格分隔
# route -n
# netstat -rn
====添加或删除路由表
# ip route add 10.0.0.1/24 via 10.0.0.0 dev eth0
# ip route | column -t

# ip route del 10.0.0.1/24
# ip route | column -t

123.netstat:查看网络状态

netstat命令用于显示本机网络的连接状态、运行端口和路由表等信息。

# netstat -an
-a 显示处于监听状态和非监听状态的socket信息
-n 不进行DNS解析,加快命令执行速度
# netstat -lntup
-l 仅显示连接状态为listen的服务的网络状态
-t tcp连接状况
-u udp连接状况
-p 显示socket所属的PID和名称
  # netstat -rn
-r 显示路由表信息
  # netsta -i
-i 显示网络接口情况

124.ss:查看网络状态

ss命令是类似并将取代netstat的工具,它能用来查看网络状态信息,包括TCP、UDP连接、端口等。它的优点是能够显示更多更详细的有关网络连接状态的信息,而且比netstat更快速更高效。

如果没有ss命令
# yum -y install iproute
====显示所有socket连接
# ss -an
# ss -an | column -t    
====显示所有正在监听的TCP和UDP连接
# ss -lntup | column -t
====显示socket统计
# ss -s
[root@sun ~]# ss -s
Total: 141
TCP:   3 (estab 1, closed 0, orphaned 0, timewait 0)

Transport Total     IP        IPv6
RAW       0         0         0
UDP       3         2         1
TCP       3         2         1
INET      6         4         2
FRAG      0         0         0
统计当前的established,closed,orphaned和waiting的TCP socket数量
#当服务器产生大量socket连接时,通常用该命令进行宏观数据统计

125.ping:测试主机之间网络的连通性

执行ping命令会使用ICMP传输协议,发出要求回应的信息,若远端主机的网络功能没有问题,就会回应该信息,因而可得知该主机运作正常。

# ping www.baidu.com
===指定ping次数
# ping -c www.baidu.com
===指定发送3次ICMP包、每次发包间隔2秒、发送数据包大小为1024字节、ttl值为100
-t 设定发送包生命周期
# ping -c 3 -i 2 -s 1024 -t 100 www.baidu.com
PING www.wshifen.com (183.232.231.173) 1024(1052) bytes of data.
1032 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=1 ttl=33 time=227 ms
1032 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=2 ttl=33 time=227 ms
1032 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=3 ttl=33 time=227 ms
===指定TTL值低
[root@sun sysconfig]# ping -c 2 -t 30 www.baidu.com
PING www.wshifen.com (183.232.231.173) 56(84) bytes of data.
--- www.wshifen.com ping statistics ---
2 packets transmitted, 0 received,  100% packet loss , time 1056ms

ping命令的输出信息中含有TTL值。TTL(Time To Life)称为生存期,它是ICMP报文在网络上的存活时间。即指定IP包被路由器丢弃之前允许通过的最大网段数量。

不同的操作系统发出的ICMP报文的生存期各不相同,常见的生存期为32、64、128和255等。

TTL值反映了ICMP报文所能够经过的路由器数目,每经过一个路由器,路由器都会将其数据包的生存期减去1,如果TTL值变为0,则路由器将不再转发此报文,包被丢弃。

因为现在绝大多数路由器的消耗时间都小于1s,而时间小于1s就当1s计算,所以数据包没经过一个路由器节点TTL都减一

默认TTL值的情况下:

[root@sun sysconfig]# ping -c 2 www.baidu.com
PING www.wshifen.com (183.232.231.173) 56(84) bytes of data.
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=1 ttl=33 time=227 ms
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=2 ttl=33 time=227 ms

--- www.wshifen.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1605ms
rtt min/avg/max/mdev = 226.647/226.690/226.733/0.043 ms
[root@sun sysconfig]# traceroute -d www.baidu.com
traceroute to www.baidu.com (183.232.231.173), 30 hops max, 60 byte packets
 1  216.182.229.94 (216.182.229.94)  9.157 ms * *
 2  100.66.40.200 (100.66.40.200)  9.334 ms * *
 3  100.66.14.152 (100.66.14.152)  20.805 ms 100.66.11.200 (100.66.11.200)  19.260 ms 100.66.14.50 (100.66.14.50)  18.274 ms
.....
27  * * 120.241.49.30 (120.241.49.30)  221.402 ms
28  * * *
29  * * *
30  * * *

===
TTL值为33(找2^n且离返回值最近的那个值)
经过64-1-33=30个路由器
===
ping TTL值不会变
[root@sun sysconfig]# ping -c 2 -t 64 www.baidu.com
PING www.wshifen.com (183.232.231.173) 56(84) bytes of data.
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=1 ttl=33 time=227 ms
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=2 ttl=33 time=227 ms
[root@sun sysconfig]# ping -c 2 -t 40 www.baidu.com
PING www.wshifen.com (183.232.231.173) 56(84) bytes of data.
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=1 ttl=33 time=227 ms
64 bytes from 183.232.231.173 (183.232.231.173): icmp_seq=2 ttl=33 time=227 ms
以星号表示的。出现这样的情况,可能是防火墙封掉了ICMP的返回信息,所以我们得不到什么相关的数据包返回数据

修改TTL值情况下:

[root@sun sysconfig]# ping -c 2 www.sina.com
PING ww1.sinaimg.cn.w.alikunlun.com (8.38.121.226) 56(84) bytes of data.
64 bytes from 8.38.121.226 (8.38.121.226): icmp_seq=1 ttl=26 time=25.4 ms
64 bytes from 8.38.121.226 (8.38.121.226): icmp_seq=2 ttl=26 time=25.5 ms

--- ww1.sinaimg.cn.w.alikunlun.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 25.394/25.438/25.483/0.165 ms
 ====经过节点查看 
[root@sun sysconfig]# traceroute -d www.sina.com
traceroute to www.sina.com (8.38.121.225), 30 hops max, 60 byte packets
 1  * 216.182.231.253 (216.182.231.253)  3.355 ms *
 2  100.66.13.108 (100.66.13.108)  17.979 ms 100.65.104.240 (100.65.104.240)  6.922 ms 100.66.12.68 (100.66.12.68)  15.560 ms
......
14  8.38.121.225 (8.38.121.225)  26.408 ms * *
 ====得知经过14个路由节点,计算TTL值为 26+14=40 
===验证:
==指定TTL为40时,余1
如果TTL值变为0,则路由器将不再转发此报文,包被丢弃
[root@sun sysconfig]# ping -c 2 -t 40 www.sina.com
PING ww1.sinaimg.cn.w.alikunlun.com (8.38.121.225) 56(84) bytes of data.
64 bytes from 8.38.121.225 (8.38.121.225): icmp_seq=1 ttl=1 time=26.1 ms
64 bytes from 8.38.121.225 (8.38.121.225): icmp_seq=2 ttl=1 time=26.1 ms

126.traceroute:追踪数据传输路由状况

traceroute命令用于显示网络数据包传输到指定主机的路径信息,追踪数据传输路由状况。默认数据包大小是60字节(IPv4)或80字节(IPv6),用户可另行设置。它与Windows下的tracert命令类似。

# traceroute www.baidu.com
# traceroute -d www.baidu.com
-d 不解析DNS

系统默认没有安装此命令
# yum -y install traceroute

127.telnet:远程登录主机

telnet命令以前是用于登录远程主机,对远程主机进行管理的。

但是因为telnet是采用明文传送报文的,其安全性不好,因此现在很多Linux服务器都不开放telnet服务,而是改用更安全的SSH服务了。

当然,交换机等网络设备还是会采用telnet登录的方式。

128.ssh:安全地远程登录主机

sh命令是openssh套件中的客户端连接工具,可以使用ssh加密协议实现安全的远程登录服务器,实现对服务器的远程管理.

Windows中的替代工具为Xshell、putty、SecureCRT等。

# ssh IP
= ssh -p 22 root@IP
===指定用户,也可以同时指定端口
# ssh -p 22 user@IP
===远程执行命令
# ssh 10.0.0.29 "free -m"

129.wget:命令行下载工具

wget命令用于从网络上下载自己所需要的文件。

wget的特点如下:

  • 支持断点下载功能。

  • 支持FTP和HTTP下载方式。

  • 支持代理服务器。

  • 非常稳定,它在带宽很窄的情况下或不稳定的网络中有很强的适应性。如果是由于网络的原因下载失败,wget会不断地尝试,直到整个文件下载完毕。
    如果是服务器打断了下载过程,它会再次连接到服务器上从停止的地方继续下载。这对那些从限定了连接时间的服务器上下载大文件非常有用。

====使用wget下载单个文件====
# wget http://www.~~~~

====指定下载文件保存目录和文件名====
# wget http://www.~~~~ -O /etc/yum.repos.d/yum.repo
====通过--limit-rate限速下载====
# wget --limit-rate= 3k  http://www.~~~~
====使用-c参数断点续传====
# wget -c http://www.~~~~
====使用-b参数后台下载文件====
# wget -b http://www.~~~~
# tail wget-log

====伪装代理名称下载====
有些网站会根据判断代理名称不是浏览器而拒绝你的下载请求。
# wget --user-agent="Mozilla/5.0 (Windows; U; Windows NT 6.1;
 en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16" 
 http://www.~~~~
====监控网站URL是否正常的案例====
采用静默访问的方式,3秒超时,重试1次,模拟爬虫的方式进行访问
# wget -q -T 3 --tries=1 --spider www.baidu.com
# echo $?   返回0表示正常

130.mailq:显示邮件传输队列

mailq命令是mail queue(邮件队列)的缩写,它会显示待发送的邮件队列,显示的条目包括邮件队列ID、邮件大小、加入队列时间、邮件发送者和接受者。如果邮件进行最后一次尝试后还没有将邮件投递出去,则显示发送失败的原因。

[root@sun ~]# yum -y install postfix
[root@sun ~]# mailq
postqueue: warning: Mail system is down -- accessing queue directly
Mail queue is empty
[root@sun ~]# systemctl start postfix
[root@sun ~]# systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
   Loaded: loaded (/usr/lib/systemd/system/postfix.service; disabled; vendor preset: disabled)
   Active:  active  (running) since Thu 2022-09-15 07:13:58 UTC; 10s ago
  Process: 30484 ExecStart=/usr/sbin/postfix start (code=exited, status=0/SUCCESS)
[root@sun ~]# mailq
Mail queue is empty

131.nslookup:域名查询工具

nslookup命令是常用的域名解析查询工具。

如果没有nslookup
# yum -y install bind-utils

从文件读取DNS服务器地址

# cat /etc/resolv.conf
search ec2.internal
nameserver 172.31.0.2
# nslookup www.baidu.com
Server:         172.31.0.2
Address:        172.31.0.2#53

Non-authoritative answer:
www.baidu.com   canonical name = www.a.shifen.com.
www.a.shifen.com        canonical name = www.wshifen.com.
Name:   www.wshifen.com
Address: 183.232.231.173

132.dig:域名查询工具

dig命令是常用的域名查询工具,可以用于测试域名系统的工作是否正常。

====查询指定域名的IP地址====
# dig www.163.com
; <<>> DiG 9.11.36-RedHat-9.11.36-3.el8 <<>> www.163.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45140
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;www.163.com.                   IN      A

;; ANSWER SECTION:
www.163.com.            60      IN      CNAME   www.163.com.163jiasu.com.
www.163.com.163jiasu.com. 60    IN      CNAME   www.163.com.w.kunluncan.com.
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.225
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.226
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.227
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.228
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.229
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.230
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.231
www.163.com.w.kunluncan.com. 60 IN      A       163.181.57.232
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.224
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.225
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.226
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.227
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.228
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.229
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.230
www.163.com.w.kunluncan.com. 60 IN      A       79.133.176.231

;; Query time: 232 msec
;; SERVER: 172.31.0.2#53(172.31.0.2)
;; WHEN: Thu Sep 15 08:08:29 UTC 2022
;; MSG SIZE  rcvd: 369
====简洁方式====
# dig +short www.163.com
www.163.com.163jiasu.com.
www.163.com.w.kunluncan.com.
79.133.176.230
79.133.176.231
163.181.57.225
163.181.57.226
163.181.57.227
163.181.57.228
163.181.57.229
163.181.57.230
163.181.57.231
163.181.57.232
79.133.176.224
79.133.176.225
79.133.176.226
79.133.176.227
79.133.176.228
79.133.176.229
====反向域名解析====
# dig -x 79.133.176.229
====显示完整的DNS解析过程====
# dig www.163.com +trace

133.host:域名查询工具

host命令是用于查询DNS的工具,它可以将指定主机名称转换为IP地址。

====DNS查询====
# host www.baidu.com
www.baidu.com is an alias for www.a.shifen.com.
www.a.shifen.com is an alias for www.wshifen.com.
www.wshifen.com has address 183.232.231.173
# host -a www.baidu.com 
← 查询详细信息
====按类进行查询====
-t 指定查询的域名信息类型,A/ALL/MX/NS
# host -t MX www.163.com
www.163.com is an alias for www.163.com.163jiasu.com.
www.163.com.163jiasu.com is an alias for www.163.com.w.kunluncan.com.
# host -t MX www.baidu.com
www.baidu.com is an alias for www.a.shifen.com.
www.a.shifen.com is an alias for www.wshifen.com.

134.nmap:网络探测工具和安全/端口扫描器

nmap命令是一款开放源代码的网络探测和安全审核工具,是Network Mapper的缩写。其设计目标是快速地扫描大型网络。nmap可以发现网络上有哪些主机,主机提供了什么服务(应用程序名称和版本号),并探测操作系统的类型及版本信息。

如果没有nmap命令

# yum -y install nmap
====查看指定IP当前开放的端口====
# host www.baidu.com
www.baidu.com is an alias for www.a.shifen.com.
www.a.shifen.com is an alias for www.wshifen.com.
www.wshifen.com has address 183.232.231.173
# nmap 183.232.231.173   #←==nmap直接接IP,默认扫描1-1000的端口
Starting Nmap 7.70 ( https://nmap.org ) at 2022-09-15 08:26 UTC
Nmap scan report for 183.232.231.173
Host is  up  (0.23s latency).   #←==目标主机正在运行
Not shown: 998 filtered ports
PORT    STATE SERVICE
80/tcp  open  http            #←==开放80、443端口
443/tcp open  https
Nmap done: 1 IP address (1 host up) scanned in 19.78 seconds

# hostname -I
172.31.22.215 10.0.0.0
[root@sun ~]# nmap 10.0.0.0
Starting Nmap 7.70 ( https://nmap.org ) at 2022-09-15 08:35 UTC
Nmap scan report for ip-10-0-0-0.ec2.internal (10.0.0.0)
Host is up (0.0000040s latency).
Not shown: 999 closed ports  #←==999个端口关闭
PORT   STATE SERVICE
22/tcp open  ssh             #←==开放22端口
Nmap done: 1 IP address (1 host up) scanned in 1.60 seconds

====扫描主机指定端口====
# nmap -p 443 183.232.231.173
  Starting Nmap 7.70 ( https://nmap.org ) at 2022-09-15 08:32 UTC
  Nmap scan report for 183.232.231.173
  Host is up (0.23s latency).
  
  PORT    STATE SERVICE
  443/tcp open  https
  Nmap done: 1 IP address (1 host up) scanned in 1.87 seconds
====扫描局域网内所有的IP====
# nmap 10.0.0.0/24
  Starting Nmap 7.70 ( https://nmap.org ) at 2022-09-15 08:38 UTC
  Nmap scan report for ip-10-0-0-0.ec2.internal (10.0.0.0)
  Host is up (0.0000040s latency).
  Not shown: 999 closed ports
  PORT   STATE SERVICE
  22/tcp open  ssh
  Nmap done: 256 IP addresses (1 host up) scanned in 12.02 seconds
# nmap -sn 183.232.231.173   #←==不扫描端口,只检查主机正在运行
  Starting Nmap 7.70 ( https://nmap.org ) at 2022-09-15 08:41 UTC
  Nmap scan report for 183.232.231.173
  Host is up (0.23s latency).
  Nmap done: 1 IP address (1 host up) scanned in 2.18 seconds

135.tcpdump:监听网络流量

tcpdump命令是一个截获网络数据包的包分析工具。tcpdump可以将网络中传送的数据包的“头”完全截获下来以提供分析。

它支持针对网络层、协议、主机、端口等的过滤,并支持与、或、非逻辑语句协助过滤有效信息。

tcpdump命令工作时要先把网卡的工作模式切换到混杂模式(promiscuous mode)。因为要修改网络接口的工作模式,所以tcpdump命令需要以root的身份运行。

====不加参数运行tcpdump命令监听网络====
默认情况下,直接启动tcpdump将监听第一个网络接口上所有数据包
# tcpdump
  使用tcpdump命令时,如果不输入过滤规则,则输出的数据量将会很大。
  ctrl+c中止程序
  79162 packets captured
  80394 packets received by filter
  1232 packets dropped by kernel
  最后三行就是监听数据包汇总信息
# tcpdump -q  #←==精简显示信息
====监听指定网卡收到的数据包====
# tcpdump -i eth0
08:59:25.077047 IP netblock-208-127-160-206.dslextreme.com.cichild-lm 
> ip-172-31-22-215.ec2.internal.ssh: Flags [P.], seq 321:385, ack 317136, win 4112,           length 64
说明:
  08:59:25.077047:当前时间,精确到微秒
  >:代表数据流向
  Flags [P.]:TCP包中的标志信息,S是SYN标志的缩写,F(FIN)、P(PUSH)、R(RST)、"."(没有标记)
  ·seq:数据包中的数据的顺序号。
  ·ack:下次期望的顺序号。
  ·win:接收缓存的窗口大小。
  ·length:数据包长度。
====监听指定主机的数据包====
# tcpdump -n host 10.0.0.1    #←== -n不进行DNS解析,加快显示速度;监听指定主机关键字host
# tcpdump -n src host 10.0.0.1 #←== 只监听从10.0.0.1发出的数据包,即源地址为10.0.0.1
# tcpdump -n dst host 10.0.0.1 #←== 只监听从10.0.0.1收到的数据包,即目的地址为。。。
====监听指定端口的数据包====
# tcpdump -n port 22 -c 3
dropped privs to tcpdump
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
08:53:51.809576 IP 172.31.22.215.ssh > 203.90.236.205.23668: Flags [P.], seq 149258787:149258851, ack 1590032509, win 564, length 64
08:53:51.817347 IP 172.31.22.215.ssh > 203.90.236.205.23668: Flags [P.], seq 64:432, ack 1, win 564, length 368
08:53:51.817475 IP 172.31.22.215.ssh > 203.90.236.205.23668: Flags [P.], seq 432:608, ack 1, win 564, length 176
3 packets captured
3 packets received by filter
0 packets dropped by kernel  
====监听指定协议的数据包====
# tcpdump -n arp    #←==监听arp数据包
# tcpdump -n icmp
常见的协议关键字有ip、arp、icmp、tcp、udp等类型

1)正常的TCP连接的三个阶段

·TCP三次握手·数据传送·TCP四次断开

2)TCP的状态标识

  • SYN:(同步序列编号,Synchronize Sequence Numbers)该标志仅在三次握手建立TCP连接时有效。表示一个新的TCP连接请求。
  • ACK:(确认编号,Acknowledgement Number)是对TCP请求的确认标志,同时提示对端系统已经成功接收了所有的数据。
  • FIN:(结束标志,FINish)用来结束一个TCP回话。但对应端口仍然处于开放状态,准备接收后续数据。

第11章 Linux系统管理命令

136.lsof:查看进程打开的文件

lsof全名为list open files,也就是列举系统中已经被打开的文件,通过lsof命令,就可以根据文件找到对应的进程信息,也可以根据进程信息找到进程打开的文件。

====显示使用文件的进程====
# lsof /var/log/messages
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
rsyslogd 1013 root    6w   REG  202,2   420768 9282831 /var/log/messages
====显示指定进程/进程号所打开的文件====
-c -p
# lsof -c rsyslog
# lsof -p 1013
COMMAND   PID USER   FD      TYPE             DEVICE SIZE/OFF     NODE NAME
rsyslogd 1013 root  txt       REG              202,2   741608 25166969 /usr/sbin/rsyslogd

====监听指定的协议、端口和主机等信息,显示符合条件的进程信息====
lsof -i [46] [protocol][@hostname][:service|port]
其中各项的含义如下。
  ·46:4代表IPv4,6代表IPv6。
  ·protocol:传输协议,可以是TCP或UDP。
  ·hostname:主机名称或者IP地址。
  ·service:进程的服务名,例如NFS、SSH和FTP等。
  ·port:系统中与服务对应的端口号。例如HTTP服务默认对应的端口号为80,SSH服务默认对应的端口号为22。

# lsof -i       #<==显示所有进程
# lsof -i 4     #<==显示所有ipv4进程
# lsof -i tcp   #<==显示所有tcp网络连接的进程

# lsof -i :22   #<==显示端口为22的所有进程  #常用,提示某某端口被占用

# lsof -i tcp:22 #<==显示满足tcp和端口为22的所有进程
====显示指定用户使用的文件====
# lsof -u ec2-user
# lsof -U  #<==显示所有socket文件

137.uptime:显示系统的运行时间及负载

uptime命令可以输出当前系统时间、系统开机到现在的运行时间、目前有多少用户在线和系统平均负载等信息。

# uptime
 06:49:23 up 13 days, 22:10,  1 user,  load average: 0.00, 0.00, 0.00
系统时间    运行时长  登录用户数 平均负载           1min,5min,15min 

138.free:查看系统内存信息

free命令用于显示系统内存状态,具体包括系统物理内存、虚拟内存、共享内存和系统缓存等。

# free -m   #<==以MB为单位显示内存使用情况
              total        used        free      shared  buff/cache   available
Mem:            801         141         191          47         469         489
Swap:             0           0           0
# free -h   #<==根据大小,按KB,MB,GB显示内存使用情况
              total        used        free      shared  buff/cache   available
Mem:          801Mi       141Mi       191Mi        47Mi       469Mi       489Mi
Swap:            0B          0B          0B
# free -h -s 10 #<==定时查询内存(每10秒)

139.vmstat:虚拟内存统计

vmstat是Virtual Memory Statistics(虚拟内存统计)的缩写,利用vmstat命令可以对操作系统的内存信息、进程状态和CPU活动等进行监视。但是只能对系统的整体情况进行统计,无法对某个进程进行深入分析。

====显示虚拟内存的使用情况====
# 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 194412    712 480796    0    0     1     2   29   15  0  0 100  0  0
第1列:procs。
  ·r列表示运行和等待CPU时间片的进程数。
  ·b列表示正在等待资源的进程数。
第2列:memory。
  ·swpd列表示使用虚拟内存的大小。
  ·free列表示当前空闲的物理内存数量。
  ·buff列表示buffers的内存数量。
  ·cache列表示cache的内存数量。
第3列:swap。
  ·si(swap in)列表示由磁盘调入内存,也就是内存进入内存交换区的数量。
  ·so(swap out)列表示由内存调入磁盘,也就是内存交换区进入内存的数量。
第4列:I/O项显示磁盘读写状况。
  ·bi列表示从块设备读入数据的总量(即读磁盘)(块/s)。
  ·bo列表示写入块设备的数据总量(即写磁盘)(块/s)。
第5列:system显示采集间隔内发生的中断数。
  ·in列表示在某一时间间隔中观测到的每秒设备中断数。
  ·cs列表示每秒产生的上下文切换次数。
第6列:CPU项显示了CPU的使用状态。
  ·us列显示了用户进程消耗的CPU时间百分比。
  ·sy列显示了系统(内核)进程消耗的CPU时间百分比。
  ·id列显示了CPU处在空闲状态的时间百分比。
  ·wa列显示了I/O等待所占用的CPU时间百分比。
  ·st列显示了虚拟机占用的CPU时间的百分比。

# vmstat 5    #<==每5秒显示一次
# vmstat 2 3  #<==2秒显示一次,显示3次结束
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 3  0      0 194412    712 480820    0    0     1     2   29   15  0  0 100  0  0
 0  0      0 194352    712 480820    0    0     0     0   77  149  0  0 100  0  0
 0  0      0 194352    712 480820    0    0     0     0   79  153  0  0 100  0  0
# vmstat -a 2 3  #<==显示活跃和非活跃内存,2秒显示一次,显示3次结束
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free  inact active   si   so    bi    bo   in   cs us sy id wa st
 3  0      0 194352 206308 296544    0    0     1     2   29   16  0  0 100  0  0
 0  0      0 194232 206368 296548    0    0     0     0   60  112  0  0 100  0  0
 0  0      0 194232 206420 296548    0    0     0     0   57  110  0  1 100  0  0
# vmstat -s  #<==查看内存使用详细
       821044 K total memory
       145140 K used memory
       296544 K active memory
       206308 K inactive memory
...
       799112 pages paged in
      2956797 pages paged out
# vmstat -d  #<==查看磁盘的读/写
disk- ------------reads------------ ------------writes----------- -----IO------
       total merged sectors      ms  total merged sectors      ms    cur    sec
xvda   17757     24 1598224   26806 186447  48511 5913595  321857      0    138
# vmstat -p /dev/xvda2  #<==查看指定磁盘的读/写统计信息
xvda2           reads      read sectors      writes  requested writes
                17639           1594728      186529           5915058

·reads:来自于该分区的读的次数。
·read sectors:来自于该分区的读扇区的次数。
·writes:来自于该分区的写的次数。
·requested writes:来自于该分区的写请求次数。

140.mpstat:CPU信息统计

mpstat是Multiprocessor Statistics的缩写,是一种实时系统监控工具。mpstat命令会输出CPU的一些统计信息,这些信息存放在/proc/stat文件中。在多CPU的系统里,此命令不但能用来查看所有CPU的平均状况信息,而且还能够用来查看特定CPU的信息。mpstat命令的最大特点是:可以查看多核心CPU中每个计算核心的统计数据,而类似命令vmstat只能查看系统整体的CPU情况。命令需要yum

# mpstat
# mpstat 5 6
# mpstat -P 0  #<==显示第一个cpu的信息

141.iostat:I/O信息统计

iostat是I/O statistics(输入/输出统计)的缩写,其主要功能是对系统的磁盘I/O操作进行监视。它的输出主要是显示磁盘读写操作的统计信息,同时也会给出CPU的使用情况。同vmstat命令一样,iostat命令也不能对某个进程进行深入分析,仅会对系统的整体情况进行分析。需要yum

# iostat
# iostat 2 3
# iostat -d
# iostat -d -m   #<==以MB为单位显示
# iostat -c      #<==只查看CPU的统计信息

142.iotop:动态显示磁盘I/O统计信息

iotop命令是一款实时监控磁盘I/O的工具,但必须以root用户的身份运行。使用iotop命令可以很方便地查看每个进程使用磁盘I/O的情况。最小化安装系统一般是没有这个命令的,需要使用yum命令额外安装

# iotop

143.ntsysv:管理开机服务

ntsysv命令提供了一种基于文本界面的菜单操作方式,以设置不同运行级别下的系统服务启动状态。

# ntsysv

空格键 开启或关闭
Tab键 切到确认键

144.ethtool:查询网卡参数

ethtool命令用于查询或设置网卡参数。

# ethtool eth0

145.mii-tool:管理网络接口的状态

mii-tool命令用于查看、管理网络接口,默认情况下网卡的状态是自动协商的,但是有时也会出现不正常的情况,可以使用mii-tool进行调整。

# mii-tool eth0
# mii-tool -v eth0  #<==显示详细信息
# mii-tool -r eth0  #<==重启自动协商模式

146.dmidecode:查询系统硬件信息

dmidecode命令可以用来在Linux系统下获取硬件方面的信息。dmidecode遵循SMBIOS/DMI标准,其输出的信息包括BIOS、处理器、内存、缓存等。

# dmidecode -t 1   #<==显示服务器信息
# dmidecode -s system-serial-number #<==显示系统序列号
# dmidecode -t processor  #<==显示CPU处理器信息
  ==# lscpu
# dmidecode -t memory     #<==显示内存信息

147.lspci:显示所有PCI设备

lspci命令用来显示系统中的所有PCI总线设备或是连接到该总线上的所有设备。

# lspci  #<==显示所有PCI设备
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.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 01)
# lspci -s 00:01.1  #<==查看指定PCI设备
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
# lspci -s 00:01.1 -v   #<==查看详细信息
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II] (prog-if 80 [ISA Compatibility mode-only controller, supports bus mastering])
        Subsystem: XenSource, Inc. Device 0001
        Physical Slot: 1
        Flags: bus master, medium devsel, latency 64

148.ipcs:显示进程间通信设施的状态

ipcs命令用于显示Linux中进程间通信设施的状态,显示的信息包括消息列表、共享内存和信号量等信息。

# 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
# ipcs -q  #<==显示活动的消息队列信息  Message Queues
# ipcs -m  #<==显示活动的共享内存信息  Shared Memory Segments
# ipcs -s  #<==显示活动的信号量信息    Semaphore Arrays
# ipcs -a  #<==显示全部信息

149.ipcrm:清除ipc相关信息

ipcrm命令用于移除一个消息对象、共享内存段或一个信号集,但它同时也会将与ipc对象相关的数据一起移除。只有超级管理员,或者ipc对象的创建者才能使用这个命令。

# ipcs
------ Message Queues -------- #<==-q
key        msqid      owner      perms      used-bytes   messages
0x0000       0           root       600          
------ Shared Memory Segments -------- #<==-m
key        shmid      owner      perms      bytes      nattch     status
0x0000       2           root       600 
------ Semaphore Arrays -------- #<== -s
key        semid      owner      perms      nsem
0x0000       3           root       600 
# ipcrm -q 0
# ipcrm -m 2
# ipcrm -s 3

150.rpm:RPM包管理器

rpm命令的全称是Red Hat Package Manager(Red Hat包管理器),几乎所有的Linux发行版本都使用了这种形式的命令管理、安装、更新和卸载软件。

概括地说,rpm命令包含了五种基本功能(不包括创建rpm包):安装、卸载、升级、查询和验证。

参数选项

-q 查询软件包
-p 后面接以.rpm 为后缀的软件包
-i 跟qp搭配是显示概要信息 info;安装软件包,是install
-l 显示软件包中所有文件列表
-R 显示软件包的依赖环境
-v 显示详细信息
-h 用#显示安装进度条
-a 与q搭配,查询所有软件包
-e 卸载
-f 查看文件或命令属于哪个软件包
-U 升级软件包
# rpm -qa 
# rpm -ql tree-1.7.0-15.el8.x86_64
# rpm -qR tree-1.7.0-15.el8.x86_64
# rpm -qi tree-1.7.0-15.el8.x86_64
# rpm -e tree-1.7.0-15.el8.x86_64
# rpm -ivh tree-1.7.0-15.el8.x86_64
# rpm -qf /usr/bin/tree

151.yum:自动化RPM包管理工具

yum(Yellow dog Updater Modified)是多个Linux发行版的软件包管理器,例如Redhat RHEL、CentOS和Fedora。yum主要用于自动安装、升级rpm软件包,它能自动查找并解决rpm包之间的依赖关系。

# yum info httpd  #<==获取软件包信息
# yum history  #<==查看yum的历史纪录
Loaded plugins: fastestmirror
ID     | Command line             | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
     5 | -y install iotop         | 2023-11-13 16:38 | Install        |    1   
     4 | -y install bind-utils    | 2023-11-13 15:08 | Install        |    6   
     3 | -y install traceroute    | 2023-11-13 14:54 | Install        |    1   
     2 | -y install tree          | 2023-11-09 16:38 | Install        |    1   
     1 | install -y ncurses-devel | 2023-10-14 12:40 | Install        |    1 

# yum clean all  #<==清理所有yum的缓存内容

# yum install httpd -y #<==安装httpd
# yum update httpd  #<==更新httpd
# yum remove httpd  #删除安装包

# yum list          #<==列出说有可用软件
# yum list httpd    #<==查找httpd
# yum list installed #<==列出已安装的软件
# yum list installed httpd 
# yum search httpd  #<==如果不记得包名,可以搜索一下

====群组软件包====
# yum grouplist     #<==列出所有可用群组
# yum groupinstall "Network Servers" -y #<==安装群组
# yum groupupdate "Network Servers"  #<==更新群组

-y 确认操作为默认yes
--nogpgcheck  忽略gpg验证
-v 显示详细信息

其它补充:

152.seq:打印数字序列

seq命令用于以指定增量从首数开始打印数字到尾数,即产生从某个数到另外一个数之间的所有整数,并且可以对整数的格式、宽度、分割符号进行控制。

-f 格式 
-s 字符串 
-w 在列前添加0 使得宽度相同

# seq 1 5
1
2
3
4
5
# seq 1 2 5
1
3
5
# seq 5 -2 1
5
3
1
# seq -w 1 5
1
2
3
4
5
# seq -w 8 10
08
09
10
# seq -f "%03g" 8 10
008
009
010
# seq -s ":--:" 8 10
8:--:9:--:10
# seq -s ":--:" -f "%03g" 8 10
008:--:009:--:010

153.mkpasswd

make password的简写。可以随机生成字符串。

参数:

-c 设置在密码中小写字母的最少个数 
-C 设置在密码中大写字母的最少个数 
-d 设置密码的最少数字 
-l 设置生成口令的长度
-s 设置在密码中特殊字符的最少个数

如果没有命令,可以通过安装expect来使用
# yum install -y expect
# which mkpasswd 
/usr/bin/mkpasswd
# mkpasswd -d 3
|s2O78Aen
# mkpasswd -d 3 -l 10
5nt24fB~pN
# mkpasswd -c 2 -C 2 -d 3 -s 2 -l 10  
68op0X[)Ux
# mkpasswd -C 5 -l 10 | passwd --stdin zi1024
更改用户 zi1024 的密码 。
passwd:所有的身份验证令牌已经成功更新。

# for i in {1..5};do echo `mkpasswd -c 2 -l 10`;done
71kouTsvC^
h}9RFst1yk
M=kN28scct
e73DB"xikn
v;EjvE0ks8

查询IP地址

ip addr

ip a 效果和ip addr一样

hostname -I

ifconfig

查看硬件配置

cat /proc/cpuinfo CPU信息

cat /proc/meminfo 内存信息

free -m 查看内存使用量和交换区使用量

cat 合并文件或查看文件内容

补充

1.在vi编辑器中,您可以使用正则表达式来查找文件中是否存在空格结尾的行。

请按照以下步骤进行操作:

打开待编辑的文件,在命令模式下按下 / 进入搜索模式。

输入正则表达式 ^$,表示空行。

在 ^$ 正则表达式后添加一个空格,表示空格结尾的行。最终搜索模式为 ^ $(结尾处一个空格)。

按下回车键,编辑器会定位到第一个匹配的空格结尾行。

按下 n 键,可以继续查找下一个匹配的行。

若要退出搜索模式,按下 Esc 键。

2.在vi编辑器中,可以使用以下命令直接跳转到指定行:

按下:进入命令模式。

输入行号,然后按下回车键。例如,要跳转到第10行,可以输入 10。

编辑器会自动跳转到指定行。

请注意,如果指定的行号超出文件的总行数,编辑器将无法跳转到该行。

另外,也可以使用 / 命令来搜索并定位到指定的关键字或模式。例如,输入 /关键字 可以定位到文件中出现的第一个匹配关键字的地方。

使用 n 和 N 可以在搜索结果中进行前后跳转。

在跳转到指定行之后,您可以进行编辑和其他操作。

posted @ 2021-09-20 16:32  橘子洲头喝两口  阅读(195)  评论(0编辑  收藏  举报