1. 重置root密码
1. 重启服务器(虚拟机) 2. 快速选择第二项,然后按 e 键 3. 在linux这一行的最后加上一个空格,然后输入 rd.break,然后按 ctrl + x 来重启服务 4. 在提示符所在位置输入 mount -o remount,rw /sysroot 5. 在提示符后输入 chroot /sysroot 6. 在提示符后输入 echo 新的密码 | passwd --stdin root 7. 在提示符后输入 touch /.autorelabel 8. 在提示符后输入 exit 9. 在提示符后输入 exit
2. 查看IP
# 第一种方式 [root@localhost ~]# ifconfig # 第二种方式 [root@localhost ~]# ip address # 还可以简化 [root@localhost ~]# ip addr [root@localhost ~]# ip ad [root@localhost ~]# ip a
判断网络是否畅通:
[root@localhost ~]# ping -c 3 www.baidu.com
3. 命令的分类
在 linux 中命令是分为两大类:
-
内部命令
-
外部命令
# 内部命令 [root@localhost ~]# type cd cd is a shell builtin # 外部命令 [root@localhost ~]# type cat cat is /usr/bin/cat
4. 查看时间
查看时间是使用 date 命令来完成的。
[root@localhost ~]# date Wed Feb 21 10:01:15 AM CST 2024 [root@localhost ~]# date %j date: invalid date ‘%j’ [root@localhost ~]# date "+%j" 052 [root@localhost ~]# date +%j 052 [root@localhost ~]# date "+%Y-%m-%d %H:%M:%S" 2024-02-21 10:03:36 # 或者使用timedatectl [root@localhost ~]# timedatectl --help timedatectl [OPTIONS...] COMMAND ... Query or change system time and date settings. Commands: status Show current time settings show Show properties of systemd-timedated set-time TIME Set system time set-timezone ZONE Set system time zone list-timezones Show known time zones set-local-rtc BOOL Control whether RTC is in local time set-ntp BOOL Enable or disable network time synchronization systemd-timesyncd Commands: timesync-status Show status of systemd-timesyncd show-timesync Show properties of systemd-timesyncd Options: -h --help Show this help message --version Show package version --no-pager Do not pipe output into a pager --no-ask-password Do not prompt for password -H --host=[USER@]HOST Operate on remote host -M --machine=CONTAINER Operate on local container --adjust-system-clock Adjust system clock when changing local RTC mode --monitor Monitor status of systemd-timesyncd -p --property=NAME Show only properties by this name -a --all Show all properties, including empty ones --value When showing properties, only print the value See the timedatectl(1) man page for details. [root@localhost ~]# timedatectl status Local time: Wed 2024-02-21 10:07:04 CST Universal time: Wed 2024-02-21 02:07:04 UTC RTC time: Wed 2024-02-21 02:07:04 Time zone: Asia/Shanghai (CST, +0800) System clock synchronized: yes NTP service: active RTC in local TZ: no
5. 用户切换
用户切换需要使用到 su 命令
[root@localhost ~]# su redhat [redhat@localhost root]$ exit exit [root@localhost ~]# su - redhat [redhat@localhost ~]$
在使用 su 来切换用户时,带有 - 和不带的区别:带有 - 的不仅仅是切换用户,同时还会切换用户的运行环境。
如果希望查看用户的信息,我们需要使用 id 命令:
[root@localhost ~]# su redhat [redhat@localhost root]$ exit exit [root@localhost ~]# su - redhat [redhat@localhost ~]$ exit logout [root@localhost ~]# id root uid=0(root) gid=0(root) groups=0(root) [root@localhost ~]# id redhat uid=1000(redhat) gid=1000(redhat) groups=1000(redhat),10(wheel)
在 linux 中,用户分为三类:
-
超级用户,它的 uid = 0,它是用于管理系统的
-
系统用户,它的 uid = 1 ~ 999,这些用户是不能登录的,目的就是运行相关的软件
-
普通用户,它的 uid = 1000 ~ 65535 之间,大部分用户都是这类
6. 设置主机名
设置主机名我们需要使用 hostnamectl 命令。
[root@localhost ~]# hostnamectl --help hostnamectl [OPTIONS...] COMMAND ... Query or change system hostname. Commands: status Show current hostname settings hostname [NAME] Get/set system hostname icon-name [NAME] Get/set icon name for host chassis [NAME] Get/set chassis type for host deployment [NAME] Get/set deployment environment for host location [NAME] Get/set location for host Options: -h --help Show this help --version Show package version --no-ask-password Do not prompt for password -H --host=[USER@]HOST Operate on remote host -M --machine=CONTAINER Operate on local container --transient Only set transient hostname --static Only set static hostname --pretty Only set pretty hostname --json=pretty|short|off Generate JSON output See the hostnamectl(1) man page for details.
使用示例:
# 查看主机状态 [root@localhost ~]# hostnamectl status Static hostname: (unset) Transient hostname: localhost Icon name: computer-vm Chassis: vm 🖴 Machine ID: 5c5bb57619564f628a3f3f51cb63f773 Boot ID: c1c700d3567c42609978aa3567144489 Virtualization: vmware Operating System: Red Hat Enterprise Linux 9.2 (Plow) CPE OS Name: cpe:/o:redhat:enterprise_linux:9::baseos Kernel: Linux 5.14.0-284.11.1.el9_2.x86_64 Architecture: x86-64 Hardware Vendor: VMware, Inc. Hardware Model: VMware Virtual Platform Firmware Version: 6.00 # 查看主机名 [root@localhost ~]# hostnamectl hostname localhost # 修改主机名称 [root@localhost ~]# hostnamectl hostname jock [root@localhost ~]# hostnamectl hostname jock
7. 文件类型
在 linux 中一切皆文件。这些文件也是有类型的,但它与 windows 中的文件类型不一样:windows 中文件类型是以扩展名来区分的,而在 linux 中不存在扩展名的说法,它不是以扩展名来进行区分的。linux 中的扩展名唯一的作用是让我们人类知道是什么类型的文件。
在 linux 中文件类型一共有 7 种类型:
-
-:表示普通文件
-
d:表示目录
-
c:表示字符设置文件
-
p:表示管道符文件
-
b:表示块设置文件
-
s:表示套接字文件
-
l:表示链接文件
-
软链接文件:它有自己的 inode 值,它的内容是这个文件的链接地址,如果删除原文件,则链接文件失效。
-
硬链接文件:它只是引用同一个文件,因此它们的 inode 值一致,只是增加了文件的链接数据,当删除源文件时,链接数减1。
-
要想查看文件,我们需要使用 ls (list)命令:
[root@localhost ~]# ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last modification of file status information); with -l: show ctime and sort by name; otherwise: sort by ctime, newest first -C list entries by columns --color[=WHEN] colorize the output; WHEN can be 'always' (default if omitted), 'auto', or 'never'; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f do not sort, enable -aU, disable -ls --color -F, --classify append indicator (one of */=>@|) to entries --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc. --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --hyperlink[=WHEN] hyperlink file names; WHEN can be 'always' (default if omitted), 'auto', or 'never' --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for disk usage; used only with -s and per directory totals -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print entry names without quoting -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape (overrides QUOTING_STYLE environment variable) -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X) --time=WORD change the default of using modification times; access time (-u): atime, access, use; change time (-c): ctime, status; birth time: birth, creation; with -l, WORD determines which time to show; with --sort=time, sort by WORD (newest first) --time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below -t sort by time, newest first; see --time -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file -1 list one file per line. Avoid '\n' with -q or -b --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
使用示例:
# 查看当前所在目录下的内容 [root@localhost ~]# ls 12a 12c BC1 BC3 Documents m1 m3 menu02.sh Music n72 passwd Public test5 12b 12d BC2 Desktop Downloads m2 menu01.sh menu03.sh n71 n73 Pictures Templates Videos # 查看当前目录下所有内容,包括隐藏文件 [root@localhost ~]# ls -a . 12b .bash_history .bashrc BC3 .cshrc Downloads m1 menu01.sh Music n73 Public Templates .viminfo .. 12c .bash_logout BC1 .cache Desktop .lesshst m2 menu02.sh n71 passwd .ssh test5 .Xauthority 12a 12d .bash_profile BC2 .config Documents .local m3 menu03.sh n72 Pictures .tcshrc Videos # 以长列表的格式进行查看 [root@localhost ~]# ls -l total 4 -rw-r--r--. 1 root root 0 Jan 25 14:43 12a -rw-r--r--. 1 root root 0 Jan 25 14:43 12b -rw-r--r--. 1 root root 0 Jan 25 14:43 12c -rw-r--r--. 1 root root 0 Jan 25 14:43 12d -rw-r--r--. 1 root root 0 Jan 25 14:38 BC1 -rw-r--r--. 1 root root 0 Jan 25 14:38 BC2 -rw-r--r--. 1 root root 0 Jan 25 14:38 BC3 drwxr-xr-x. 2 root root 6 Feb 19 09:08 Desktop drwxr-xr-x. 2 root root 6 Feb 19 09:08 Documents drwxr-xr-x. 2 root root 6 Feb 19 09:08 Downloads -rw-r--r--. 1 root root 0 Jan 25 14:32 m1 -rw-r--r--. 1 root root 0 Jan 25 14:32 m2 -rw-r--r--. 1 root root 0 Jan 25 14:32 m3 -rw-r--r--. 1 root root 0 Jan 25 14:35 menu01.sh -rw-r--r--. 1 root root 0 Jan 25 14:35 menu02.sh -rw-r--r--. 1 root root 0 Jan 25 14:35 menu03.sh drwxr-xr-x. 2 root root 6 Feb 19 09:08 Music -rw-r--r--. 1 root root 0 Jan 25 14:34 n71 -rw-r--r--. 1 root root 0 Jan 25 14:34 n72 -rw-r--r--. 1 root root 0 Jan 25 14:34 n73 -rw-r--r--. 1 root root 2400 Jan 25 16:20 passwd drwxr-xr-x. 2 root root 6 Feb 19 09:08 Pictures drwxr-xr-x. 2 root root 6 Feb 19 09:08 Public drwxr-xr-x. 2 root root 6 Feb 19 09:08 Templates # 查看指定目录的内容 [root@localhost ~]# ls -l /dev total 0 crw-r--r--. 1 root root 10, 235 Feb 21 09:41 autofs drwxr-xr-x. 2 root root 160 Feb 21 09:41 block drwxr-xr-x. 2 root root 60 Feb 21 09:41 bsg lrwxrwxrwx. 1 root root 3 Feb 21 09:41 cdrom -> sr0 drwxr-xr-x. 2 root root 3040 Feb 21 09:41 char crw--w----. 1 root tty 5, 1 Feb 21 09:41 console lrwxrwxrwx. 1 root root 11 Feb 21 09:41 core -> /proc/kcore drwxr-xr-x. 6 root root 120 Feb 21 09:41 cpu crw-------. 1 root root 10, 124 Feb 21 09:41 cpu_dma_latency drwxr-xr-x. 8 root root 160 Feb 21 09:41 disk brw-rw----. 1 root disk 253, 0 Feb 21 09:41 dm-0 brw-rw----. 1 root disk 253, 1 Feb 21 09:41 dm-1 drwxr-xr-x. 2 root root 60 Feb 21 09:41 dma_heap crw-rw----+ 1 root audio 14, 9 Feb 21 09:41 dmmidi drwxr-xr-x. 3 root root 100 Feb 21 09:41 dri # 如果只希望查看目录本身而不是目录的内容 [root@localhost ~]# ls -l Documents/ total 0 [root@localhost ~]# ls -l -d Documents/ drwxr-xr-x. 2 root root 6 Feb 19 09:08 Documents/ [root@localhost ~]# ls -ld Documents/ drwxr-xr-x. 2 root root 6 Feb 19 09:08 Documents/ # 查看文件的inode值 [root@localhost ~]# ls -lai total 48 33554562 dr-xr-x---. 15 root root 4096 Feb 21 09:42 . 128 dr-xr-xr-x. 18 root root 235 Oct 15 19:36 .. 34762523 -rw-r--r--. 1 root root 0 Jan 25 14:43 12a 34762524 -rw-r--r--. 1 root root 0 Jan 25 14:43 12b 34776687 -rw-r--r--. 1 root root 0 Jan 25 14:43 12c 34776689 -rw-r--r--. 1 root root 0 Jan 25 14:43 12d 34762509 -rw-------. 1 root root 1547 Feb 19 11:49 .bash_history 36303874 -rw-r--r--. 1 root root 18 Aug 11 2021 .bash_logout [root@localhost ~]# ls -ila / total 28 128 dr-xr-xr-x. 18 root root 235 Oct 15 19:36 . 128 dr-xr-xr-x. 18 root root 235 Oct 15 19:36 .. 67157107 dr-xr-xr-x. 2 root root 6 Aug 10 2021 afs 13383 lrwxrwxrwx. 1 root root 7 Aug 10 2021 bin -> usr/bin 128 dr-xr-xr-x. 5 root root 4096 Oct 15 19:45 boot
我们在使用 ls 命令查看时,我们发现目录下都有两个特殊的目录:. 和 ..,它们分别表示当前目录和上一级目录。如果不是根目录,那么当前目录和上一级目录的 inode 值是不一样的,这说明它们是两个不同的目录;如果是根目录,则当前目录和上一级目录的 inode 值是一样的,这说明它们两个是同一个目录,因为根目录没有上一级目录,为了程序的完整,所以所根目录的上一级目录指向了它自身。
8. 路径问题
在 linux 中路径分为绝对路径和相对路径。
绝对路径是以 / 开头的路径,而相对路径是以当前路径为起点到目标路径。
路径的切换我们可以使用 cd 命令来实现:
[root@localhost etc]# cd --help cd: cd [-L|[-P [-e]] [-@]] [dir] Change the shell working directory. Change the current directory to DIR. The default DIR is the value of the HOME shell variable. The variable CDPATH defines the search path for the directory containing DIR. Alternative directory names in CDPATH are separated by a colon (:). A null directory name is the same as the current directory. If DIR begins with a slash (/), then CDPATH is not used. If the directory is not found, and the shell option `cdable_vars' is set, the word is assumed to be a variable name. If that variable has a value, its value is used for DIR. Options: -L force symbolic links to be followed: resolve symbolic links in DIR after processing instances of `..' -P use the physical directory structure without following symbolic links: resolve symbolic links in DIR before processing instances of `..' -e if the -P option is supplied, and the current working directory cannot be determined successfully, exit with a non-zero status -@ on systems that support it, present a file with extended attributes as a directory containing the file attributes The default is to follow symbolic links, as if `-L' were specified. `..' is processed by removing the immediately previous pathname component back to a slash or the beginning of DIR. Exit Status: Returns 0 if the directory is changed, and if $PWD is set successfully when -P is used; non-zero otherwise.
使用示例:
[root@localhost usr]# cd /etc [root@localhost etc]# cd /root [root@localhost ~]# cd - # 使用 - 来表示上一次的切换目录位置,它会把上一次的目录路径保存在一个变量中 /etc [root@localhost etc]# cd - /root # 如果希望快速回到家目录,则需要使用 ~ [root@localhost etc]# cd ~ [root@localhost ~]# [root@localhost ~]# cd . [root@localhost ~]# cd .. [root@localhost /]#
9. 文件管理
9.1 目录管理
9.1.1 创建目录
创建目录我们需要 mkdir 命令。
在 Linux 中所有的操作都是通过命令的来完成的,这些命令如何记意?
根据英文单词来记意,如:cat,sort
根据单词的组合或简写来记意,如:ls(list)、cd(change directory)、mkdir(make directory)、pwd(print working directory)
通过给这些命令分类,如:文件操作命令,目录操作命令,权限操作命令,磁盘操作命令。。。。。
mkdir 命令的格式:
[root@localhost /]# mkdir --help Usage: mkdir [OPTION]... DIRECTORY... Create the DIRECTORY(ies), if they do not already exist. Mandatory arguments to long options are mandatory for short options too. -m, --mode=MODE set file mode (as in chmod), not a=rwx - umask -p, --parents no error if existing, make parent directories as needed -v, --verbose print a message for each created directory -Z set SELinux security context of each created directory to the default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit
使用示例:
# 以绝对路径的方式来创建 [root@localhost ~]# mkdir /root/dir1 # 验证创建结果 [root@localhost ~]# ls dir1 # 创建多级目录 [root@localhost ~]# mkdir -p dir1/dir11/dir111 [root@localhost ~]# tree dir1 dir1 └── dir11 └── dir111 2 directories, 0 files # 创建多个目录 [root@localhost ~]# mkdir dir{2,3,4} [root@localhost ~]# ls dir1 dir2 dir3 dir4 [root@localhost ~]# mkdir dir{11..15} [root@localhost ~]# ls dir1 dir11 dir12 dir13 dir14 dir15 dir2 dir3 dir4
9.1.2 查看目录
还是使用 ls 命令来查看,但是我们要使用 -d 选项,这样才能够查看目录本身而不是进入到目录中。
[root@localhost ~]# ls -l dir1 total 0 drwxr-xr-x. 3 root root 20 Feb 21 11:15 dir11 [root@localhost ~]# ls -dl dir1 drwxr-xr-x. 3 root root 19 Feb 21 11:15 dir1 # 查看多个目录 [root@localhost ~]# ls -ld dir{1,2,3} drwxr-xr-x. 3 root root 19 Feb 21 11:15 dir1 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir2 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir3 [root@localhost ~]# ls -ld dir{1..4} drwxr-xr-x. 3 root root 19 Feb 21 11:15 dir1 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir2 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir3 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir4 # 还可以使用通配符 [root@localhost ~]# ls -ld dir* # * 表示匹配多个字符 drwxr-xr-x. 3 root root 19 Feb 21 11:15 dir1 drwxr-xr-x. 2 root root 6 Feb 21 11:16 dir11 drwxr-xr-x. 2 root root 6 Feb 21 11:16 dir12 drwxr-xr-x. 2 root root 6 Feb 21 11:16 dir13 drwxr-xr-x. 2 root root 6 Feb 21 11:16 dir14 drwxr-xr-x. 2 root root 6 Feb 21 11:16 dir15 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir2 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir3 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir4 [root@localhost ~]# ls -ld dir? # ? 表示匹配一个字符 drwxr-xr-x. 3 root root 19 Feb 21 11:15 dir1 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir2 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir3 drwxr-xr-x. 2 root root 6 Feb 21 11:15 dir4
我们可以使用 du 命令来查看文件或目录占用的磁盘空间大小。
[root@localhost ~]# du --help Usage: du [OPTION]... [FILE]... or: du [OPTION]... --files0-from=F Summarize disk usage of the set of FILEs, recursively for directories.
使用示例:
[root@localhost ~]# du -h . 0 ./.ssh 0 ./.cache/ibus 0 ./.cache/evolution/addressbook/trash 0 ./.cache/evolution/addressbook 0 ./.cache/evolution/calendar/trash 0 ./.cache/evolution/calendar 0 ./.cache/evolution/mail/trash 0 ./.cache/evolution/mail 0 ./.cache/evolution/memos/trash 0 ./.cache/evolution/memos 0 ./.cache/evolution/sources/trash 0 ./.cache/evolution/sources 0 ./.cache/evolution/tasks/trash 0 ./.cache/evolution/tasks 0 ./.cache/evolution 2.0M ./.cache/gnome-software/appstream 4.0K ./.cache/gnome-software/flatpak-system-default 4.0K ./.cache/gnome-software/flatpak-user-user 1.5M ./.cache/gnome-software/odrs 3.5M ./.cache/gnome-software 500K ./.cache/gstreamer-1.0 4.0M ./.cache 4.0K ./.config/ibus/bus 4.0K ./.config/ibus 4.0K ./.config/dconf 4.0K ./.config/evolution/sources 4.0K ./.config/evolution 0 ./.config/goa-1.0 4.0K ./.config/gtk-3.0 0 ./.config/gnome-session/saved-session 0 ./.config/gnome-session 32K ./.config ...........
9.1.3 删除目录
删除目录我们要使用 rm(remove) 命令来实现,它的使用格式为:
[root@localhost ~]# rm --help Usage: rm [OPTION]... [FILE]... Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo
使用示例:
[root@localhost ~]# ls dir1 dir11 dir12 dir13 dir14 dir15 dir2 dir3 dir4 # 如果删除的是目录,是不会成功的 [root@localhost ~]# rm dir2 rm: cannot remove 'dir2': Is a directory # 如果删除的目录是空目录,则需要带 -d 选项 [root@localhost ~]# rm -d dir2 rm: remove directory 'dir2'? yes [root@localhost ~]# ls dir1 dir11 dir12 dir13 dir14 dir15 dir3 dir4 # 当删除的目录不为空时,需要带上 -r 选项 [root@localhost ~]# rm -d dir1 rm: cannot remove 'dir1': Directory not empty [root@localhost ~]# rm -r dir1 rm: descend into directory 'dir1'? yes rm: descend into directory 'dir1/dir11'? yes rm: remove directory 'dir1/dir11/dir111'? yes rm: remove directory 'dir1/dir11'? yes rm: remove directory 'dir1'? yes [root@localhost ~]# ls dir11 dir12 dir13 dir14 dir15 dir3 dir4 # 删除多个目录 [root@localhost ~]# rm -rf dir{3,4} [root@localhost ~]# ls dir11 dir12 dir13 dir14 dir15 [root@localhost ~]# rm -rf dir{11..13} [root@localhost ~]# ls dir14 dir15 # 删除所有 [root@localhost ~]# rm -rf * [root@localhost ~]# ls [root@localhost ~]#
9.2 普通文件管理
9.2.1 创建文件
创建文件可以有以下几种方式:
-
使用 touch 命令
-
使用重定向符
-
vi或vim命令
9.2.1.1 touch
这个命令是用于创建一个空的文件,如果创建的文件不存在则创建,如果存在则更新文件的元数据,但是创建时间不变。
[root@localhost ~]# touch a.txt # 查看这个文件的元数据信息,使用 stat 命令来查看 [root@localhost ~]# stat a.txt File: a.txt Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: fd00h/64768d Inode: 34762516 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root) Context: unconfined_u:object_r:admin_home_t:s0 Access: 2024-02-21 11:42:25.552932073 +0800 Modify: 2024-02-21 11:42:25.552932073 +0800 Change: 2024-02-21 11:42:25.552932073 +0800 Birth: 2024-02-21 11:42:25.552932073 +0800 #重新创建已有文件,发现元数据除了创建时间都进行了更新 [root@localhost ~]# touch a.txt [root@localhost ~]# stat a.txt File: a.txt Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: fd00h/64768d Inode: 34762516 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root) Context: unconfined_u:object_r:admin_home_t:s0 Access: 2024-02-21 11:45:43.123726570 +0800 Modify: 2024-02-21 11:45:43.123726570 +0800 Change: 2024-02-21 11:45:43.123726570 +0800 Birth: 2024-02-21 11:42:25.552932073 +0800
Access: 2024-02-21 11:42:25.552932073 +0800 表示访问文件的时间
Modify: 2024-02-21 11:42:25.552932073 +0800 表示文件内容的修改时间
Change: 2024-02-21 11:42:25.552932073 +0800 表示文件元数据的修改时间
Birth: 2024-02-21 11:42:25.552932073 +0800 表示文件的创建时间
创建多个文件:
[root@localhost ~]# touch file{1..4} [root@localhost ~]# ls a.txt file1 file2 file3 file4 [root@localhost ~]# touch file{11,12,13} [root@localhost ~]# ls a.txt file1 file11 file12 file13 file2 file3 file4
9.2.1.2 echo
这个命令的作用是将它的参数显示在终端上。
# 显示123 [root@localhost ~]# echo 123 123 # 显示 aaa [root@localhost ~]# echo aa aa # 显示变量$USER的内容 [root@localhost ~]# echo $USER root # 显示变量$PWD的内容 [root@localhost ~]# echo $PWD /root
9.2.1.3 重定向
数据流向:输入和输出。
标准输入:在默认情况下,标准输入是从键盘或鼠标中获取输入的内容。
标准输出:在默认情况下,标准输出是将命令执行后的正确结果传到终端(屏幕)上。
标准错误输出:将命令执行后的错误信息输出到屏幕或文件中。
输入是使用 < 来表示,而输出是使用 > 或 >> 来表示。
>:表示覆盖的形式来输出内容
>>:表示是追加的形式来输出内容
标准输入的数字代码为 0,标准输出的数字代码为 1,标准错误输出的数字代码为 2。
通过 echo 加上重定向来创建文件。
# 将当前日期写入到 date.txt 文件中 [root@localhost ~]# date 1> date.txt # 注意1和>之间不要有空格,它表示将命令执行后的结果输出到指定文件中 [root@localhost ~]# cat date.txt Wed Feb 21 02:25:36 PM CST 2024 [root@localhost ~]# echo hello >> date.txt [root@localhost ~]# cat date.txt Wed Feb 21 02:27:10 PM CST 2024 hello
使用 > 或者 >> 时,如果文件不存在,则会自动把文件创建起来;如果文件存在,则覆盖或追加内容到指定的文件中。
[root@localhost ~]# ls /etc/passwd /etc/passwd [root@localhost ~]# ls /etc/passwd >> date.txt [root@localhost ~]# cat date.txt Wed Feb 21 02:27:10 PM CST 2024 hello /etc/passwd # 查看一个不存在的文件或目录 [root@localhost ~]# ls /aaa ls: cannot access '/aaa': No such file or directory # 将正确执行的结果写入到 success.txt 文件中,将执行过程中发生的错误信息写入到 error.txt 文件中 [root@localhost ~]# ls /aaa > success.txt 2>> error.txt [root@localhost ~]# ls a.txt date.txt error.txt file1 file11 file12 file13 file2 file3 file4 success.txt [root@localhost ~]# cat success.txt [root@localhost ~]# cat error.txt ls: cannot access '/aaa': No such file or directory
9.2.2 查看文件
9.2.2.1 cat
这个命令用于查看文件的所有内容。
[root@localhost ~]# cat a.txt hello redhat world hadoop python java linux # 查看时输出行号 [root@localhost ~]# cat -n a.txt 1 hello 2 redhat 3 world 4 hadoop 5 python 6 java 7 linux # 内容中加了空行 [root@localhost ~]# cat a.txt hello redhat world hadoop python java linux # 使用 -n 时空行也会标上行号 [root@localhost ~]# cat -n a.txt 1 hello 2 3 redhat 4 world 5 6 hadoop 7 python 8 java 9 linux # 使用 -b 时空行不会标上行号 [root@localhost ~]# cat -b a.txt 1 hello 2 redhat 3 world 4 hadoop 5 python 6 java 7 linux
9.2.2.2 head
这个命令是默认读取文件的前 10 行内容。命令和使用格式:
[root@localhost ~]# head --help Usage: head [OPTION]... [FILE]... Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[-]NUM print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file -n, --lines=[-]NUM print the first NUM lines instead of the first 10; with the leading '-', print all but the last NUM lines of each file -q, --quiet, --silent never print headers giving file names -v, --verbose always print headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit
使用示例:
# 默认显示文件的前 10 行 [root@localhost ~]# head /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin # 指定显示文件前 5 行 [root@localhost ~]# head -n 5 /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin # 指定显示文件的前 10 个字符 [root@localhost ~]# head -c 10 /etc/passwd root:x:0:0 # 显示前面10行并且带行号 [root@localhost ~]# head /etc/passwd | cat -n 1 root:x:0:0:root:/root:/bin/bash 2 bin:x:1:1:bin:/bin:/sbin/nologin 3 daemon:x:2:2:daemon:/sbin:/sbin/nologin 4 adm:x:3:4:adm:/var/adm:/sbin/nologin 5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 6 sync:x:5:0:sync:/sbin:/bin/sync 7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown 8 halt:x:7:0:halt:/sbin:/sbin/halt 9 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 10 operator:x:11:0:operator:/root:/sbin/nologin
9.2.2.3 tail
这个命令用于默认显示文件的最后 10 行内容。它的使用格式为:
[root@localhost ~]# tail --help Usage: tail [OPTION]... [FILE]... Print the last 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to output starting with byte NUM of each file -f, --follow[={name|descriptor}] output appended data as the file grows; an absent option argument means 'descriptor' -F same as --follow=name --retry -n, --lines=[+]NUM output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line NUM --max-unchanged-stats=N with --follow=name, reopen a FILE which has not changed size after N (default 5) iterations to see if it has been unlinked or renamed (this is the usual case of rotated log files); with inotify, this option is rarely useful --pid=PID with -f, terminate after process ID, PID dies -q, --quiet, --silent never output headers giving file names --retry keep trying to open a file if it is inaccessible -s, --sleep-interval=N with -f, sleep for approximately N seconds (default 1.0) between iterations; with inotify and --pid=P, check process P at least once every N seconds -v, --verbose always output headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit
使用示例:
# 查看密码文件的最后 10 行内容 [root@localhost ~]# tail /etc/passwd gdm:x:42:42::/var/lib/gdm:/sbin/nologin cockpit-ws:x:983:982:User for cockpit web service:/nonexisting:/sbin/nologin cockpit-wsinstance:x:982:981:User for cockpit-ws instances:/nonexisting:/sbin/nologin gnome-initial-setup:x:981:980::/run/gnome-initial-setup/:/sbin/nologin rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin chrony:x:980:978:chrony system user:/var/lib/chrony:/sbin/nologin dnsmasq:x:979:977:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin tcpdump:x:72:72::/:/sbin/nologin redhat:x:1000:1000:redhat:/home/redhat:/bin/bash # 查看密码文件最后 5 行内容 [root@localhost ~]# tail -n 5 /etc/passwd sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin chrony:x:980:978:chrony system user:/var/lib/chrony:/sbin/nologin dnsmasq:x:979:977:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin tcpdump:x:72:72::/:/sbin/nologin redhat:x:1000:1000:redhat:/home/redhat:/bin/bash
9.2.2.4 less
这个命令是用于分页查看文件的内容,可以按 enter 键来向下逐行滚动显示,也可以按空格键来向下翻一页,还可以按 b 键向上翻一页,如果要退出则按 q 键。
[root@localhost ~]# cat /etc/passwd >> passwd [root@localhost ~]# cat /etc/passwd >> passwd [root@localhost ~]# less passwd
9.2.2.5 more
它的作用与 less 的作用一样,但是 more 显示到最后会自动退出。
[root@localhost ~]# more passwd
9.2.3 过滤文件内容
这个功能的实现需要使用到 grep 命令。它的作用是在指定的普通文件中查找并显示包含指定的字符串的行。
命令的使用格式为:
[root@localhost ~]# grep --help Usage: grep [OPTION]... PATTERNS [FILE]... Search for PATTERNS in each FILE. Example: grep -i 'hello world' menu.h main.c PATTERNS can contain multiple patterns separated by newlines. Pattern selection and interpretation: -E, --extended-regexp PATTERNS are extended regular expressions -F, --fixed-strings PATTERNS are strings -G, --basic-regexp PATTERNS are basic regular expressions -P, --perl-regexp PATTERNS are Perl regular expressions -e, --regexp=PATTERNS use PATTERNS for matching -f, --file=FILE take PATTERNS from FILE -i, --ignore-case ignore case distinctions in patterns and data --no-ignore-case do not ignore case distinctions (default) -w, --word-regexp match only whole words -x, --line-regexp match only whole lines -z, --null-data a data line ends in 0 byte, not newline Miscellaneous: -s, --no-messages suppress error messages -v, --invert-match select non-matching lines -V, --version display version information and exit --help display this help text and exit Output control: -m, --max-count=NUM stop after NUM selected lines -b, --byte-offset print the byte offset with output lines -n, --line-number print line number with output lines --line-buffered flush output on every line -H, --with-filename print file name with output lines -h, --no-filename suppress the file name prefix on output --label=LABEL use LABEL as the standard input file name prefix -o, --only-matching show only nonempty parts of lines that match -q, --quiet, --silent suppress all normal output --binary-files=TYPE assume that binary files are TYPE; TYPE is 'binary', 'text', or 'without-match' -a, --text equivalent to --binary-files=text -I equivalent to --binary-files=without-match -d, --directories=ACTION how to handle directories; ACTION is 'read', 'recurse', or 'skip' -D, --devices=ACTION how to handle devices, FIFOs and sockets; ACTION is 'read' or 'skip' -r, --recursive like --directories=recurse -R, --dereference-recursive likewise, but follow all symlinks --include=GLOB search only files that match GLOB (a file pattern) --exclude=GLOB skip files that match GLOB --exclude-from=FILE skip files that match any file pattern from FILE --exclude-dir=GLOB skip directories that match GLOB -L, --files-without-match print only names of FILEs with no selected lines -l, --files-with-matches print only names of FILEs with selected lines -c, --count print only a count of selected lines per FILE -T, --initial-tab make tabs line up (if needed) -Z, --null print 0 byte after FILE name Context control: -B, --before-context=NUM print NUM lines of leading context -A, --after-context=NUM print NUM lines of trailing context -C, --context=NUM print NUM lines of output context -NUM same as --context=NUM --group-separator=SEP use SEP as a group separator --no-group-separator use empty string as a group separator --color[=WHEN], --colour[=WHEN] use markers to highlight the matching strings; WHEN is 'always', 'never', or 'auto' -U, --binary do not strip CR characters at EOL (MSDOS/Windows)
在使用过程中,常用的选项有:
-c 仅显示找到的行数
-i 忽悠大小写
-n 显示行号
-v 反向选择
使用示例:
1)我们在 /root/passwd 文件中查找包含所有 root 的行
[root@localhost ~]# grep "root" passwd Root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin # 忽悠查找内容的大小写匹配 [root@localhost ~]# grep -i "root" passwd Root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin root:x:0:0:root:/root:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin
2)使用特殊符号来进行字符串的匹配
# 在 /root/passwd 文件中查找以 a 开头的所有行 [root@localhost ~]# grep ^a passwd adm:x:3:4:adm:/var/adm:/sbin/nologin avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin # 在 /root/passwd 文件中查找以 h 结尾的所有行 [root@localhost ~]# grep h$ passwd Root:x:0:0:root:/root:/bin/bash redhat:x:1000:1000:redhat:/home/redhat:/bin/bash root:x:0:0:root:/root:/bin/bash redhat:x:1000:1000:redhat:/home/redhat:/bin/bash # 在 /etc/ssh/sshd_config 查找所有带有数字的行 [root@localhost ~]# grep -n [0-9] /etc/ssh/sshd_config 1:# $OpenBSD: sshd_config,v 1.104 2021/07/02 05:11:21 dtucker Exp $ 4:# sshd_config(5) for more information. 21:#Port 22 23:#ListenAddress 0.0.0.0 28:#HostKey /etc/ssh/ssh_host_ed25519_key 39:#LoginGraceTime 2m 42:#MaxAuthTries 6 43:#MaxSessions 10 47:# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2 83:#GSSAPIEnablek5users no 101:#X11Forwarding no 102:#X11DisplayOffset 10 103:#X11UseLocalhost yes 110:#ClientAliveInterval 0 111:#ClientAliveCountMax 3 114:#MaxStartups 10:30:100 127:# X11Forwarding no
9.2.4 文本内容统计
这个命令的作用是将指定文件内容进行统计,可以统计字符,也可以统计行数。
wc(word count)命令的格式:
[root@localhost ~]# wc --help Usage: wc [OPTION]... [FILE]... or: wc [OPTION]... --files0-from=F Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of characters delimited by white space. With no FILE, or when FILE is -, read standard input. The options below may be used to select which counts are printed, always in the following order: newline, word, character, byte, maximum line length. -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts --files0-from=F read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input -L, --max-line-length print the maximum display width -w, --words print the word counts --help display this help and exit --version output version information and exit
使用示例:
# 统计 /etc/passwd 文件的行数 [root@localhost ~]# wc -l /etc/passwd 39 /etc/passwd
9.2.5 切割文件内容
这个功能需要使用 cut 命令主来实现,它功能就是用于按列提取文件的内容。它的语法格式为:
[root@localhost ~]# cut --help Usage: cut OPTION... [FILE]... Print selected parts of lines from each FILE to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --bytes=LIST select only these bytes -c, --characters=LIST select only these characters -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter -f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified -n with -b: don't split multibyte characters --complement complement the set of selected bytes, characters or fields -s, --only-delimited do not print lines not containing delimiters --output-delimiter=STRING use STRING as the output delimiter the default is to use the input delimiter -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit
使用示例:
# 查看 /etc/passwd 文件的第一列内容 [root@localhost ~]# cut -d : -f 1 /etc/passwd root bin daemon adm lp sync shutdown halt mail operator games ftp nobody tss systemd-coredump ..... # 查看 /etc/passwd 文件中家目录 [root@localhost ~]# cut -d : -f 6 /etc/passwd /root /bin /sbin /var/adm /var/spool/lpd /sbin /sbin /sbin /var/spool/mail /root /usr/games ..... # 查看 /etc/passwd 文件中第一列和第六列的内容 [root@localhost ~]# cut -d : -f 1,6 /etc/passwd root:/root bin:/bin daemon:/sbin adm:/var/adm lp:/var/spool/lpd sync:/sbin shutdown:/sbin halt:/sbin mail:/var/spool/mail operator:/root ..... # 查看 /etc/passwd 文件的第一列到第三列的内容 [root@localhost ~]# cut -d : -f 1-3 /etc/passwd root:x:0 bin:x:1 daemon:x:2 adm:x:3 lp:x:4 sync:x:5 shutdown:x:6 halt:x:7 mail:x:8 operator:x:11 ......
9.2.6 排序显示内容
排序显示需要使用到 sort 命令,它的功能就是将文件的内容进行排序再显示。语法格式如下:
[root@localhost ~]# sort --help Usage: sort [OPTION]... [FILE]... or: sort [OPTION]... --files0-from=F Write sorted concatenation of all FILE(s) to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. Ordering options: -b, --ignore-leading-blanks ignore leading blanks -d, --dictionary-order consider only blanks and alphanumeric characters -f, --ignore-case fold lower case to upper case characters -g, --general-numeric-sort compare according to general numerical value -i, --ignore-nonprinting consider only printable characters -M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC' -h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G) -n, --numeric-sort compare according to string numerical value -R, --random-sort shuffle, but group identical keys. See shuf(1) --random-source=FILE get random bytes from FILE -r, --reverse reverse the result of comparisons --sort=WORD sort according to WORD: general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V -V, --version-sort natural sort of (version) numbers within text Other options: --batch-size=NMERGE merge at most NMERGE inputs at once; for more use temp files -c, --check, --check=diagnose-first check for sorted input; do not sort -C, --check=quiet, --check=silent like -c, but do not report first bad line --compress-program=PROG compress temporaries with PROG; decompress them with PROG -d --debug annotate the part of the line used to sort, and warn about questionable usage to stderr --files0-from=F read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input -k, --key=KEYDEF sort via a key; KEYDEF gives location and type -m, --merge merge already sorted files; do not sort -o, --output=FILE write result to FILE instead of standard output -s, --stable stabilize sort by disabling last-resort comparison -S, --buffer-size=SIZE use SIZE for main memory buffer -t, --field-separator=SEP use SEP instead of non-blank to blank transition -T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or /tmp; multiple options specify multiple directories --parallel=N change the number of sorts run concurrently to N -u, --unique with -c, check for strict ordering; without -c, output only the first of an equal run -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit
在使用过程中常用的选项有:
-f 忽悠大小写
-b 忽悠缩进与空格
-n 以数值进行排序
-r 反向排序
-u 去除重复的行
-t 指定间隔符
-k 设置字段的范围
使用示例:
# 查看 /etc/passwd 文件第 3 列并排序 # 接合 cut 来实现 [root@localhost ~]# cut -d : -f 3 /etc/passwd | sort # 得到的是自然顺序 [root@localhost ~]# cut -d : -f 3 /etc/passwd | sort -n # 得到的是数值顺序 [root@localhost ~]# cut -d : -f 3 /etc/passwd | sort -nr # 得到反序 # 使用 sort 独自实现 [root@localhost ~]# sort -t : -k 3 /etc/passwd root:x:0:0:root:/root:/bin/bash redhat:x:1000:1000:redhat:/home/redhat:/bin/bash operator:x:11:0:operator:/root:/sbin/nologin bin:x:1:1:bin:/bin:/sbin/nologin games:x:12:100:games:/usr/games:/sbin/nologin ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin [root@localhost ~]# sort -t : -k 3 -n /etc/passwd # 也可以对文件的内容进行排序 [root@localhost ~]# sort /etc/passwd adm:x:3:4:adm:/var/adm:/sbin/nologin avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin bin:x:1:1:bin:/bin:/sbin/nologin
9.2.7 去重显示内容
要实现这个功能,我们可以使用 uniq 命令,它的功能就是用于去除文本中连续的重复的行。语法如下:
[root@localhost ~]# uniq --help Usage: uniq [OPTION]... [INPUT [OUTPUT]] Filter adjacent matching lines from INPUT (or standard input), writing to OUTPUT (or standard output). With no options, matching lines are merged to the first occurrence. Mandatory arguments to long options are mandatory for short options too. -c, --count prefix lines by the number of occurrences -d, --repeated only print duplicate lines, one for each group -D print all duplicate lines --all-repeated[=METHOD] like -D, but allow separating groups with an empty line; METHOD={none(default),prepend,separate} -f, --skip-fields=N avoid comparing the first N fields --group[=METHOD] show all items, separating groups with an empty line; METHOD={separate(default),prepend,append,both} -i, --ignore-case ignore differences in case when comparing -s, --skip-chars=N avoid comparing the first N characters -u, --unique only print unique lines -z, --zero-terminated line delimiter is NUL, not newline -w, --check-chars=N compare no more than N characters in lines --help display this help and exit --version output version information and exit
使用示例:
# 案例准备 [root@localhost ~]# vim file1 [root@localhost ~]# cat file1 hello 9 hello 9 world 7 hello 9 world 7 world 7 # 去除 file1 文件中重复的行 [root@localhost ~]# uniq file1 hello 9 world 7 hello 9 world 7 [root@localhost ~]# uniq -c file1 2 hello 9 1 world 7 1 hello 9 2 world 7
9.2.8 编辑文件
使用 vim 来进行文件的编辑(包括创建、修改)。
在Vim编辑器中设置了三种模式:命令模式 、末行模式 和编辑模式
-
命令模式:
这是 vim 进入后的默认模式。在这个模式下,可以执行如下的命令: - 光标跳转: 1. 通过上下左右键来进行移动 2. gg 用于回到文件开头(连续按两次 g 键) 3. G 用于回到文件的结尾(shift + g) 4. 将当前光标所在位置移动到行首和行尾按^(行首)和$(行尾) 5. 按单词进行向后移动,按 w,如果希望按单词几前则按 b - 复制: 1. yy表示复制,nyy表示复制 n 行(从光标所以位置向后计算) 2. p表示粘贴所复制的内容 - 删除: 1. u表示撤销当前的操作 2. dd表示删除光标所在行,ndd表示删除从光标所在行向后计算 n 行,dG 表示从当前光标删除后最后,dgg表示从当前光标删除到最前
-
编辑模式:
编辑模式也叫插入模式,当我们在命令模式下按 aios 或者 AIOS 这几个键时,就会从命令模式转换为编辑模式。 i:表示在将前插入 a:表示在光标后插入 I:表示在非空行前插入 A:表示在非空行后插入 o:表示在光标所在行的下一行插入 O:表示在光标所在行的上一行插入 s:表示删除插入 S:表示删除行插入
-
末行模式:
- 文档保存并退出 :wq shift+zz - 文件保存 :w - 退出 :q :q! - 另存为 :w 文件路径 - 将指定的文件写入到该文件中 :r 文件路径 - 执行关键字搜索 /输入要搜索的关键字 找到后按 n 向后查找,按 N 向前查找 - 搜索替换 :%s/被替换的关键字/替换的内容/gi g表示全局替换,i表示不区分大小写 - 只替换某一行 :3,12s/root/admin/g 表示替换3到 12 行所有 root 为 admin - 显示行号 :set nu - 关闭行号 :set nonu - 取消高亮 :noh
9.2.9 删除文件
删除文件也是使用 rm 命令来完成。操作方式与删除目录一样,只是在删除文件是不需要带 -r 选项。
[root@localhost ~]# rm -f aa a.txt [root@localhost ~]# ls date.txt error.txt file1 file11 file12 file13 file2 file3 file4 passwd success.txt [root@localhost ~]# rm -f *.txt [root@localhost ~]# ll total 12 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 1 root root 4456 Feb 21 16:18 passwd
9.3 链接文件管理
在 Linux 中,链接文件分为如下两种:
-
软件链接文件,它也叫符号链接
-
硬链接文件
创建链接文件的命令是 ln,它的语法格式为:
[root@localhost ~]# ln --help Usage: ln [OPTION]... [-T] TARGET LINK_NAME or: ln [OPTION]... TARGET or: ln [OPTION]... TARGET... DIRECTORY or: ln [OPTION]... -t DIRECTORY TARGET... In the 1st form, create a link to TARGET with the name LINK_NAME. In the 2nd form, create a link to TARGET in the current directory. In the 3rd and 4th forms, create links to each TARGET in DIRECTORY. Create hard links by default, symbolic links with --symbolic. By default, each destination (name of new link) should not already exist. When creating hard links, each TARGET must exist. Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument -d, -F, --directory allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser) -f, --force remove existing destination files -i, --interactive prompt whether to remove destinations -L, --logical dereference TARGETs that are symbolic links -n, --no-dereference treat LINK_NAME as a normal file if it is a symbolic link to a directory -P, --physical make hard links directly to symbolic links -r, --relative create symbolic links relative to link location -s, --symbolic make symbolic links instead of hard links -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create the links -T, --no-target-directory treat LINK_NAME as a normal file always -v, --verbose print name of each linked file --help display this help and exit --version output version information and exit
使用示例:
# 我们为/root/passwd 文件创建一个符号链接,名称为 passwdln [root@localhost ~]# ln -s /root/passwd passwdln [root@localhost ~]# ll total 12 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 1 root root 4456 Feb 21 16:18 passwd lrwxrwxrwx. 1 root root 12 Feb 21 16:23 passwdln -> /root/passwd # 符号链接文件和原文件的inode 值不一样 [root@localhost ~]# ll -i total 12 34763139 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 34762525 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 34762529 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 34762530 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 34762521 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 34762523 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 34762524 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 34762544 -rw-r--r--. 1 root root 4456 Feb 21 16:18 passwd 34762516 lrwxrwxrwx. 1 root root 12 Feb 21 16:23 passwdln -> /root/passwd # 删除源文件后,符号链接文件不可用 [root@localhost ~]# rm -f passwd [root@localhost ~]# ll total 4 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 lrwxrwxrwx. 1 root root 12 Feb 21 16:23 passwdln -> /root/passwd [root@localhost ~]# cat passwdln cat: passwdln: No such file or directory
创建硬链接文件:
[root@localhost ~]# ln /root/passwd passwd1 [root@localhost ~]# ll total 12 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 2 root root 2224 Feb 21 16:26 passwd -rw-r--r--. 2 root root 2224 Feb 21 16:26 passwd1 # 硬链接文件与源文件的 inode 值相同 [root@localhost ~]# ll -i total 12 34763139 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 34762525 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 34762529 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 34762530 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 34762521 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 34762523 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 34762524 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 34762516 -rw-r--r--. 2 root root 2224 Feb 21 16:26 passwd 34762516 -rw-r--r--. 2 root root 2224 Feb 21 16:26 passwd1 # 删除原文件,链接文件也可以用,只是链接数减少 [root@localhost ~]# rm -f passwd [root@localhost ~]# ll total 8 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 [root@localhost ~]# cat passwd1
9.4 块设备管理
查看块设备所使用的命令是 lsblk。使用语法格式:
[root@jock ~]# lsblk --help Usage: lsblk [options] [<device> ...] List information about block devices. Options: -D, --discard print discard capabilities -E, --dedup <column> de-duplicate output by <column> -I, --include <list> show only devices with specified major numbers -J, --json use JSON output format -O, --output-all output all columns -P, --pairs use key="value" output format -S, --scsi output info about SCSI devices -T, --tree[=<column>] use tree format output -a, --all print all devices -b, --bytes print SIZE in bytes rather than in human readable format -d, --nodeps don't print slaves or holders -e, --exclude <list> exclude devices by major number (default: RAM disks) -f, --fs output info about filesystems -i, --ascii use ascii characters only -l, --list use list format output -M, --merge group parents of sub-trees (usable for RAIDs, Multi-path) -m, --perms output info about permissions -n, --noheadings don't print headings -o, --output <list> output columns -p, --paths print complete device path -r, --raw use raw output format -s, --inverse inverse dependencies -t, --topology output info about topology -w, --width <num> specifies output width as number of characters -x, --sort <column> sort output by <column> -z, --zoned print zone model --sysroot <dir> use specified directory as system root -h, --help display this help -V, --version display version
使用示例:
[root@jock ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS sr0 11:0 1 8.9G 0 rom nvme0n1 259:0 0 50G 0 disk ├─nvme0n1p1 259:1 0 1G 0 part /boot └─nvme0n1p2 259:2 0 49G 0 part ├─rhel_bogon-root 253:0 0 44G 0 lvm / └─rhel_bogon-swap 253:1 0 5G 0 lvm [SWAP] [root@jock ~]# lsblk /dev/sr0 NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS sr0 11:0 1 8.9G 0 rom
9.5 复制和移动文件
9.5.1 复制文件
复制文件有两种方式:
-
本地文件复制,cp
-
远程文件复制,scp
9.5.1.1本地复制
使用的命令是 cp (copy),它的使用语法格式为:
[root@jock ~]# cp --help Usage: cp [OPTION]... [-T] SOURCE DEST or: cp [OPTION]... SOURCE... DIRECTORY or: cp [OPTION]... -t DIRECTORY SOURCE... Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a previous -i option) -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all -c deprecated, same as --preserve=context --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file -u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit
在工作中常用的选项有如下:
-a 通过在拷贝目录时使用,它会保留链接、文件属性
-d 拷贝时保留链接
-f 当复制文件时如果已经存在则强制覆盖而不会有提示信息
-i 当复制文件时如果已经存在时给出提示信息
-p 除复制源文件的内容外,还会将其修改的时间和访问权限也复制到新的文件中
-r 递归复制目录中所有内容
使用示例:
# 复制普通文件 [root@jock ~]# mkdir dir1 [root@jock ~]# ll total 8 drwxr-xr-x. 2 root root 6 Feb 22 09:44 dir1 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 [root@jock ~]# cp file1 dir1/file1 [root@jock ~]# ll dir1/file1 -rw-r--r--. 1 root root 48 Feb 22 09:44 dir1/file1 # 复制目录 [root@jock ~]# cp -ar dir1 dir2 [root@jock ~]# ll total 8 drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir2 -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file4 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1
9.5.1.2 远程复制
要实现这个功能,我们需要使用 scp 命令,它的语法格式如下:
[root@jock ~]# scp --help usage: scp [-346ABCOpqRrTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] source ... target scp 源文件路径 目标文件路径
使用示例:
[root@jock ~]# scp root@192.168.72.120:/root/file1 redhat@192.168.72.120:/home/redhat/ redhat@192.168.72.120's password: root@192.168.72.120's password: file1 100% 48 29.4KB/s 00:00 [root@jock ~]#
命令的使用解析:
1. scp 表示远程拷贝的命令
2. root@192.168.72.120:/root/file1 表示要拷贝的文件路径,它由以下几个部分组成:
2.1 root 表示当前登录的用户
2.2 192.168.72.120 表示当前登录的主机名,它和用户名之间使用 @ 符号来连接
2.3 :/root/file1 表示要复制的文件的绝对路径,它和主机名之间有一个冒号
3. redhat@192.168.72.120:/home/redhat/ 表示要拷贝文件的目标路径,它的组成与第2部分相同
如果端口不一样,我们就需要使用 -P 选项来指定端口
scp -P 6666 root@192.168.72.120:/root/file1 redhat@192.168.72.120:/home/redhat/
9.5.2 移动文件
移动文件我们使用 mv 命令,它的语法格式为:
[root@jock ~]# mv --help Usage: mv [OPTION]... [-T] SOURCE DEST or: mv [OPTION]... SOURCE... DIRECTORY or: mv [OPTION]... -t DIRECTORY SOURCE... Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument -f, --force do not prompt before overwriting -i, --interactive prompt before overwrite -n, --no-clobber do not overwrite an existing file If you specify more than one of -i, -f, -n, only the final one takes effect. --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file -u, --update move only when the SOURCE file is newer than the destination file or when the destination file is missing -v, --verbose explain what is being done -Z, --context set SELinux security context of destination file to default type --help display this help and exit --version output version information and exit
使用示例:
# 移动文件 [root@jock ~]# mv file2 dir2 [root@jock ~]# ll dir2 total 4 drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 -rw-r--r--. 1 root root 48 Feb 22 09:44 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 # 移动文件并重命名 [root@jock ~]# mv file3 dir2/file33 [root@jock ~]# ll dir2 total 4 drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 -rw-r--r--. 1 root root 48 Feb 22 09:44 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file33 # 对文件得命名 [root@jock ~]# mv file4 file [root@jock ~]# ll total 8 drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir3 -rw-r--r--. 1 root root 0 Feb 21 11:48 file -rw-r--r--. 1 root root 48 Feb 21 15:39 file1 -rw-r--r--. 1 root root 0 Feb 21 11:48 file11 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 # 也可以对目录进行操作 [root@jock ~]# mv dir3 dir [root@jock ~]# ls dir dir1 dir2 file file1 file11 file12 file13 passwd1
9.6 查找文件
9.6.1 whereis
这个命令是用于定位某个"命令"的二进制文件、源文件和手册文件的路径。
[root@jock ~]# whereis --help Usage: whereis [options] [-BMS <dir>... -f] <name> Locate the binary, source, and manual-page files for a command. Options: -b search only for binaries -B <dirs> define binaries lookup path -m search only for manuals and infos -M <dirs> define man and info lookup path -s search only for sources -S <dirs> define sources lookup path -f terminate <dirs> argument list -u search for unusual entries -l output effective lookup paths -h, --help display this help -V, --version display version
使用示例:
[root@jock ~]# whereis cp cp: /usr/bin/cp /usr/share/man/man1/cp.1.gz /usr/share/man/man1p/cp.1p.gz [root@jock ~]# whereis ls ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz [root@jock ~]# whereis cd cd: /usr/bin/cd /usr/share/man/man1/cd.1.gz /usr/share/man/man1p/cd.1p.gz
9.6.2 which
用于查找并显示给定的"命令"的绝对路径,它会在环境变量 $PATH 设置的目录里查找符合条件的文件。
[root@jock ~]# which --help Usage: /usr/bin/which [options] [--] COMMAND [...] Write the full path of COMMAND(s) to standard output. --version, -[vV] Print version and exit successfully. --help, Print this help and exit successfully. --skip-dot Skip directories in PATH that start with a dot. --skip-tilde Skip directories in PATH that start with a tilde. --show-dot Don't expand a dot to current directory in output. --show-tilde Output a tilde for HOME directory for non-root. --tty-only Stop processing options on the right if not on tty. --all, -a Print all matches in PATH, not just the first --read-alias, -i Read list of aliases from stdin. --skip-alias Ignore option --read-alias; don't read stdin. --read-functions Read shell functions from stdin. --skip-functions Ignore option --read-functions; don't read stdin.
使用示例:
[root@jock ~]# echo $PATH /root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin [root@jock ~]# which cd /usr/bin/cd [root@jock ~]# which ls alias ls='ls --color=auto' /usr/bin/ls [root@jock ~]# which find /usr/bin/find
9.6.3 locate
这个命令是在系统中按照文件名称查找符合条件的文件,当执行搜索时,它会通过搜索 /var/lib/mlocate/mlocate.db 这个数据库文件中进行查找。
[root@jock mlocate]# locate --help Usage: locate [OPTION]... [PATTERN]... Search for entries in a mlocate database. -A, --all only print entries that match all patterns -b, --basename match only the base name of path names -c, --count only print number of found entries -d, --database DBPATH use DBPATH instead of default database (which is /var/lib/mlocate/mlocate.db) -e, --existing only print entries for currently existing files -L, --follow follow trailing symbolic links when checking file existence (default) -h, --help print this help -i, --ignore-case ignore case distinctions when matching patterns -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries -m, --mmap ignored, for backward compatibility -P, --nofollow, -H don't follow trailing symbolic links when checking file existence -0, --null separate entries with NUL on output -S, --statistics don't search for entries, print statistics about each used database -q, --quiet report no error messages about reading databases -r, --regexp REGEXP search for basic regexp REGEXP instead of patterns --regex patterns are extended regexps -s, --stdio ignored, for backward compatibility -V, --version print version information -w, --wholename match whole path name (default)
使用示例:
[root@jock ~]# cd /var/lib/mlocate/ [root@jock mlocate]# ll total 3412 -rw-r-----. 1 root slocate 3491805 Feb 22 08:58 mlocate.db # 要使用这个命令之前,我们最好更新一个这个数据库文件 [root@jock ~]# updatedb [root@jock ~]# locate file2 /root/dir2/file2 [root@jock ~]# locate -i "*.conf" # 限制显示的条数 [root@jock ~]# locate -l 3 "*.conf" /boot/loader/entries/5c5bb57619564f628a3f3f51cb63f773-0-rescue.conf /boot/loader/entries/5c5bb57619564f628a3f3f51cb63f773-5.14.0-284.11.1.el9_2.x86_64.conf /etc/anthy-unicode.conf
9.6.4 find
这个命令是用于通过条件匹配在指定目录下查找对应文件或目录。可以按文件大小、时间、权限、类型以及属者/组来搜索。
[root@jock ~]# find --help Usage: find [-H] [-L] [-P] [-Olevel] [-D debugopts] [path...] [expression] default path is the current directory; default expression is -print expression may consist of: operators, options, tests, and actions: operators (decreasing precedence; -and is implicit where no others are given): ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2 EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2 positional options (always true): -daystart -follow -regextype normal options (always true, specified before other expressions): -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf --version -xautofs -xdev -ignore_readdir_race -noignore_readdir_race tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE -nouser -nogroup -path PATTERN -perm [-/]MODE -regex PATTERN -readable -writable -executable -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N -used N -user NAME -xtype [bcdpfls] -context CONTEXT actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ; -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ; Valid arguments for -D: exec, opt, rates, search, stat, time, tree, all, help Use '-D help' for a description of the options, or see find(1)
在工作中常用的选项有如下:
1. -name:根据文件名称来进行搜索
2. -path:根据文件路径来进行搜索
3. -size:根据文件大小来进行搜索(+50K表示超过50K的文件,-50K表示小于50K的文件)
4. -mtime:[+|-]n 表示匹配修改内容的时间
5. -newer f1 !f2:匹配比文件f1新但比f2旧的文件
6. -perm:匹配权限
7. -user:匹配所属者
8. -group:匹配所属组
9. -type:匹配文件类型
使用示例:
# 查找以 .txt 结尾的文件 [root@jock ~]# find / -name *.txt # 可以指定查找的最大深度为2 [root@jock ~]# find / -maxdepth 2 -name *.txt
9.7 压缩
zip、unzip、gzip、gunzip、bzip2、bunzip2、xz、unxz、tar
# zip unzip [root@jock ~]# mkdir test [root@jock ~]# mv file file1 file11 test/ [root@jock ~]# ll total 4 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test [root@jock ~]# ls test file file1 file11 [root@jock ~]# zip test.zip test/ adding: test/ (stored 0%) [root@jock ~]# ll total 8 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip [root@jock ~]# unzip -v test.zip Archive: test.zip Length Method Size Cmpr Date Time CRC-32 Name -------- ------ ------- ---- ---------- ----- -------- ---- 0 Stored 0 0% 02-22-2024 10:53 00000000 test/ -------- ------- --- ------- 0 0 0% 1 file # gzip gunzip [root@jock ~]# ll total 8 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip [root@jock ~]# gzip file12 [root@jock ~]# ll total 12 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 27 Feb 21 11:48 file12.gz -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip [root@jock ~]# gunzip file12.gz [root@jock ~]# ll total 8 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip # bzip2 bunzip2 [root@jock ~]# ll total 8 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip [root@jock ~]# bzip2 file13 [root@jock ~]# ll total 12 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 14 Feb 21 11:48 file13.bz2 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip [root@jock ~]# bunzip2 file13.bz2 [root@jock ~]# ll total 8 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 58 Feb 22 10:05 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip # tar [root@jock ~]# [root@jock ~]# tar -cvf hah.tar file12 file13 file12 file13 [root@jock ~]# ls dir dir1 dir2 file12 file13 hah.tar passwd1 test test.zip [root@jock ~]# tar -xvf hah.tar -C dir2/ file12 file13
10. 用户和组
10.1 分类
在 linux 中用户分为三类:
-
超级用户,0
-
系统用户,1~999
-
普通用户,1000~65535
这些信息是保存在 /etc/login.defs 文件中的。
对于组来说也分为以下两类:
-
基本组,也叫私有组,它只能有一个
-
附加组,也叫公有组,它是可以有多个的,多个之间用逗号分隔
对于用户和组来说,它们的信息是存储在如下的文件中的:
-
用户账号信息:/etc/passwd
-
用户的密码:/etc/shadow
-
用户组信息:/etc/group
-
用户组密码:/etc/gshadow
-
家目录下的隐藏文件:/etc/skel
-
用户默认信息:/etc/default/useradd
对 /etc/passwd 文件内容说明:
[root@jock ~]# vim /etc/passwd root:x:0:0:root:/root:/bin/bash 账号名称:密码占位符:uid:gid:个人信息:家目录:可执行的shell
对 /etc/shadow 文件内容说明:
[root@jock ~]# vim /etc/shadow root:$6$w.4NX9m.wQ/s9qV7$x4a39kSlTgm5jITx9RV46nNib1c/d3Qn3nRc69g8KaIJR3Qkl65E1S3yDV2rczu71tS.uLwJRQf3dj7t8w3a01::0:99999:7::: 用户名称:加密密码:最后一次修改时间:最小时间间隔:最大时间间隔:警告时间:不活动时间(宽限期):失效时间:标志
对 /etc/group 文件内容说明:
[root@jock ~]# vim /etc/group root:x:0: 用户名:组密码占位符:gid:附加组信息
对 /etc/gshadow 文件内容说明:
[root@jock ~]# vim /etc/gshadow root::: 用户名:组密码:组管理员的用户名:组中附加用户
10.2 用户管理
# 添加用户 [root@jock ~]# useradd zhangsan [root@jock ~]# id zhangsan uid=1001(zhangsan) gid=1001(zhangsan) groups=1001(zhangsan) # 给创建好的用户设置密码 [root@jock ~]# passwd zhangsan Changing password for user zhangsan. New password: BAD PASSWORD: The password is shorter than 8 characters Retype new password: passwd: all authentication tokens updated successfully. # 使用下面的方式来设置密码也是可以的 [root@jock ~]# echo redhat | passwd --stdin zhangsan # 删除用户 [root@jock ~]# userdel -r zhangsan
10.3 组管理
# 创建组 [root@jock ~]# groupadd lisi [root@jock ~]# useradd xiaowang -G lisi [root@jock ~]# id xiaowang uid=1001(xiaowang) gid=1002(xiaowang) groups=1002(xiaowang),1001(lisi) # 修改组 [root@jock ~]# groupmod -n haha lisi # 删除组 [root@jock ~]# groupdel lisi groupdel: group 'lisi' does not exist [root@jock ~]# groupdel haha
10.4 查看用户
# 查看当前登录用户 [root@jock ~]# users root # 列表当前与过去登录的系统用户信息 [root@jock ~]# last root pts/1 192.168.72.1 Thu Feb 22 11:15 still logged in redhat pts/1 192.168.72.120 Thu Feb 22 10:03 - 10:04 (00:00) root pts/0 192.168.72.1 Thu Feb 22 08:58 - 11:15 (02:16) reboot system boot 5.14.0-284.11.1. Thu Feb 22 08:58 still running root pts/1 192.168.72.1 Wed Feb 21 14:13 - 14:24 (00:11) root pts/0 192.168.72.1 Wed Feb 21 09:42 - 16:30 (06:48) reboot system boot 5.14.0-284.11.1. Wed Feb 21 09:41 - 16:30 (06:49) root pts/0 192.168.72.1 Mon Feb 19 10:17 - 11:49 (01:32) root pts/0 192.168.72.1 Mon Feb 19 09:16 - 09:19 (00:03) root tty2 tty2 Mon Feb 19 09:15 - down (02:34) root seat0 login screen Mon Feb 19 09:15 - down (02:34) reboot system boot 5.14.0-284.11.1. Mon Feb 19 09:15 - 11:49 (02:34) root pts/0 192.168.72.1 Mon Feb 19 09:10 - 09:15 (00:04) root tty2 tty2 Mon Feb 19 09:08 - down (00:07) root seat0 login screen Mon Feb 19 09:08 - down (00:07) reboot system boot 5.14.0-284.11.1. Mon Feb 19 09:05 - 09:15 (00:09) root pts/0 192.168.72.1 Thu Jan 25 14:31 - 16:28 (01:56) reboot system boot 5.14.0-284.11.1. Thu Jan 25 14:31 - 16:28 (01:57) redhat tty2 tty2 Sun Oct 15 19:53 - down (00:02) redhat seat0 login screen Sun Oct 15 19:53 - down (00:02) reboot system boot 5.14.0-284.11.1. Sun Oct 15 19:45 - 19:55 (00:10) wtmp begins Sun Oct 15 19:45:11 2023 # 查看账号用户信息 [root@jock ~]# w 11:37:42 up 2:39, 1 user, load average: 0.00, 0.00, 0.00 USER TTY LOGIN@ IDLE JCPU PCPU WHAT root pts/1 11:15 0.00s 0.09s 0.01s w [root@jock ~]# who root pts/1 2024-02-22 11:15 (192.168.72.1)
11. 文件系统权限
11.1 普通权限
[root@jock ~]# ls -l total 20 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 19 Feb 22 09:44 dir1 drwxr-xr-x. 3 root root 86 Feb 22 11:04 dir2 -rw-r--r--. 1 root root 0 Feb 21 11:48 file12 -rw-r--r--. 1 root root 0 Feb 21 11:48 file13 -rw-r--r--. 1 root root 10240 Feb 22 11:03 hah.tar -rw-r--r--. 1 root root 2224 Feb 21 16:26 passwd1 drwxr-xr-x. 2 root root 45 Feb 22 10:53 test -rw-r--r--. 1 root root 160 Feb 22 10:54 test.zip rwx r-x r-x 所属用户权限(u) 所属组权限(g) 其他用户权限(o) - 表示没有权限 对应的数值 0 x 表示可执行权限 对应的数值 1 w 表示可写权限 对应的数值 2 r 表示可读权限 对应的数值 4 --- 0 --x 1 -w- 2 -wx 3 r-- 4 r-x 5 rw- 6 rwx 7
要修改文件或目录的权限,我们需要使用 chmod 命令,这个命令的格式为:
[root@jock ~]# chmod --help Usage: chmod [OPTION]... MODE[,MODE]... FILE... or: chmod [OPTION]... OCTAL-MODE FILE... or: chmod [OPTION]... --reference=RFILE FILE... Change the mode of each FILE to MODE. With --reference, change the mode of each FILE to that of RFILE. -c, --changes like verbose but report only when a change is made -f, --silent, --quiet suppress most error messages -v, --verbose output a diagnostic for every file processed --no-preserve-root do not treat '/' specially (the default) --preserve-root fail to operate recursively on '/' --reference=RFILE use RFILE's mode instead of MODE values -R, --recursive change files and directories recursively --help display this help and exit --version output version information and exit Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'. ugoa 表示设置权限会针对所有的,即包括所属者(u)、所属组(g)以及其他用户(o) a = u+g+o -+= 表示设置权限的动作,+ 表示添加某个权限,- 表示取消某个权限,= 表示只赋予给定的权限 rwxXst 表示用字符形式来设置权限 0-7 表示用三位数字来设置权限 r=4 w=2 x=1 -=0
使用示例:
[root@jock ~]# ll total 20 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir drwxr-xr-x. 2 root root 45 Feb 22 10:53 test # 给所属者取消w权限 [root@jock ~]# chmod u-w test [root@jock ~]# ll total 20 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir dr-xr-xr-x. 2 root root 45 Feb 22 10:53 test # 给所属组添加w权限 [root@jock ~]# chmod g+w test [root@jock ~]# ll total 20 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir dr-xrwxr-x. 2 root root 45 Feb 22 10:53 test # 给所属者取消x权限,所属组赋予r权限,其他用户添加w权限 [root@jock ~]# chmod u-x,g=r,o+w test [root@jock ~]# ll total 20 drwxr-xr-x. 3 root root 31 Feb 22 09:46 dir -rw-r--r--. 1 root root 10240 Feb 22 11:03 hah.tar # 使用数字的形式来设置权限 [root@jock ~]# ll -d test dr--r--rwx. 2 root root 45 Feb 22 10:53 test [root@jock ~]# chmod 644 test [root@jock ~]# ll -d test drw-r--r--. 2 root root 45 Feb 22 10:53 test
11.2 特殊权限
11.2.1 SUID权限
SUID 特殊权限仅适用于可执行文件,所具有的功能是:只要用户对设有 SUID 的文件有执行权限,那么当用户执行此文件时,会以文件所有者的身份去执行此文件,一旦文件执行结束,身份的切换也随之消失。
[root@jock ~]# which passwd /usr/bin/passwd [root@jock ~]# ll /usr/bin/passwd -rwsr-xr-x. 1 root root 32648 Aug 10 2021 /usr/bin/passwd [root@jock ~]# chmod u-s /usr/bin/passwd [root@jock ~]# ll /usr/bin/passwd -rwxr-xr-x. 1 root root 32648 Aug 10 2021 /usr/bin/passwd [root@jock ~]# su - redhat [redhat@jock ~]$ passwd Changing password for user redhat. Current password: Current Password: passwd: Authentication token manipulation error
11.2.2 SGID权限
与 SUID 不同的是,SGID 既可以对文件进行配置,也可以对目录进行配置。
-
对于文件:SGID 只针对可执行文件有效,换句话说,只有可执行文件才可以被赋予 SGID 权限,普通文件赋予 SGID 没有意义。同时,用户需要对此可执行文件有 x 权限。用户在执行具有 SGID 权限的可执行文件时,用户的群组身份会变为文件所属群组。SGID 权限赋予用户改变组身份的效果,只在可执行文件运行过程中有效。
其实,SGID 和 SUID 的不同之处就在于,SUID 赋予用户的是文件所有者的权限,而 SGID 赋予用户的是文件所属组的权限,就这么简单。
-
对于目录:当一个目录被赋予 SGID 权限后,进入此目录的普通用户,其有效群组会变为该目录的所属组,这就使得用户在创建文件(或目录)时,该文件(或目录)的所属组将不再是用户的所属组,而使用的是目录的所属组。
也就是说,只有当普通用户对具有 SGID 权限的目录有 rwx 权限时,SGID 的功能才能完全发挥。比如说,如果用户对该目录仅有 rx 权限,则用户进入此目录后,虽然其有效群组变为此目录的所属组,但由于没有 x 权限,用户无法在目录中创建文件或目录,SGID 权限也就无法发挥它的作用。
[root@jock ~]# cd /tmp [root@jock tmp]# mkdir dtest [root@jock tmp]# ll total 0 srwxrwxrwx. 1 gdm gdm 0 Feb 22 08:58 dbus-gSR0hvnLMy drwxr-xr-x. 2 root root 6 Feb 22 14:03 dtest [root@jock tmp]# chmod g+s dtest [root@jock tmp]# ll total 0 srwxrwxrwx. 1 gdm gdm 0 Feb 22 08:58 dbus-gSR0hvnLMy drwxr-sr-x. 2 root root 6 Feb 22 14:03 dtest [root@jock tmp]# chmod g+w,o+s dtest [root@jock tmp]# ll -d test ls: cannot access 'test': No such file or directory [root@jock tmp]# ll -d dtest drwxrwsr-x. 2 root root 6 Feb 22 14:03 dtest [root@jock tmp]# chmod o+w dtest [root@jock tmp]# ll -d dtest drwxrwsrwx. 2 root root 6 Feb 22 14:03 dtest [root@jock tmp]# su - redhat [redhat@jock ~]$ cd /tmp/dtest [redhat@jock dtest]$ touch ab [redhat@jock dtest]$ ll total 0 -rw-r--r--. 1 redhat root 0 Feb 22 14:08 ab [redhat@jock dtest]$ mkdir haha [redhat@jock dtest]$ ll total 0 -rw-r--r--. 1 redhat root 0 Feb 22 14:08 ab drwxr-sr-x. 2 redhat root 6 Feb 22 14:09 haha
11.2.3 SBIT权限
Sticky Bit (SBit) 当前只针对目录有效, 对文件没有效果。其对目录的作用是:在具有 SBit 的目录下, 用户若在该目录下具有 w 及 x 权限 , 则当用户在该目录下建立文件或目录时, 只有文件拥有者与 root 才有权力删除。
也就是说,当甲用户以目录所属组或其他人的身份进入 A 目录时,如果甲对该目录有 w 权限,则表示对于 A 目录中任何用户创建的文件或子目录,甲都可以进行修改甚至删除等操作。但是,如果 A 目录设定有 SBIT 权限,那就大不一样啦,甲用户只能操作自己创建的文件或目录,而无法修改甚至删除其他用户创建的文件或目录。
[redhat@jock tmp]$ ll -d /tmp drwxrwxrwt. 19 root root 4096 Feb 22 14:09 /tmp # 创建 data 目录 [root@jock /]# mkdir /data [root@jock /]# ll -d /data drwxr-xr-x. 2 root root 6 Feb 22 14:14 /data # 设置可写可执行权限 [root@jock /]# chmod 777 /data [root@jock /]# ll -d /data drwxrwxrwx. 2 root root 6 Feb 22 14:14 /data # 创建两个用户 [root@jock /]# useradd tmp1 [root@jock /]# useradd tmp2 # 切换用户并创建文件 [root@jock /]# su - tmp1 [tmp1@jock ~]$ cd /data [tmp1@jock data]$ touch a [tmp1@jock data]$ touch b [tmp1@jock data]$ mkdir c [tmp1@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 b drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c # 再切换到另一个用户 [root@jock /]# su - tmp2 [tmp2@jock ~]$ cd /data [tmp2@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 b drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c [tmp2@jock data]$ rm -f b [tmp2@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c # 发现 tmp2 用户是可以删除 tmp1 用户所创建的文件的。但是我们不希望 tmp2 用户能够删除 tmp1 用户所创建的文件,如何实现? # 这时就需要给 /data 目录设置 sbit 权限。 [root@jock /]# chmod o+t /data [root@jock /]# ll -d /data drwxrwxrwt. 3 root root 24 Feb 22 14:17 /data # 两次切换用户然后进行删除,发现就不能删除别人创建的文件了,只能删除自己创建的文件 [root@jock /]# su - tmp2 [tmp2@jock ~]$ cd /data [tmp2@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c [tmp2@jock data]$ rm -f a rm: cannot remove 'a': Operation not permitted [tmp2@jock data]$ touch dd [tmp2@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c -rw-r--r--. 1 tmp2 tmp2 0 Feb 22 14:21 dd [tmp2@jock data]$ rm -f dd [tmp2@jock data]$ ll total 0 -rw-r--r--. 1 tmp1 tmp1 0 Feb 22 14:16 a drwxr-xr-x. 2 tmp1 tmp1 6 Feb 22 14:16 c
11.3 ACL权限
ACL 权限分配:给指定的用户指定目录分配指定的权限。
11.3.1 设置ACL权限
这需要使用 setfacl 命令,它的语法如下:
[root@jock data]# setfacl --help setfacl 2.3.1 -- set file access control lists Usage: setfacl [-bkndRLP] { -m|-M|-x|-X ... } file ... -m, --modify=acl modify the current ACL(s) of file(s) -M, --modify-file=file read ACL entries to modify from file -x, --remove=acl remove entries from the ACL(s) of file(s) -X, --remove-file=file read ACL entries to remove from file -b, --remove-all remove all extended ACL entries -k, --remove-default remove the default ACL --set=acl set the ACL of file(s), replacing the current ACL --set-file=file read ACL entries to set from file --mask do recalculate the effective rights mask -n, --no-mask don't recalculate the effective rights mask -d, --default operations apply to the default ACL -R, --recursive recurse into subdirectories -L, --logical logical walk, follow symbolic links -P, --physical physical walk, do not follow symbolic links --restore=file restore ACLs (inverse of `getfacl -R') --test test mode (ACLs are not modified) -v, --version print version and exit -h, --help this help text
工作中常用的选项:
-m 设置acl权限,设置的格式为 `u:用户名:权限`,或者 `g:组名:权限`
-x 删除指定的 acl 权限
-b 删除所有的 acl 权限
-d 设置默认的 acl 权限,只对目录生效
-k 删除默认的 acl 权限
-R 递归设置 acl 权限
使用示例:
# 创建目录 [root@jock /]# mkdir /openlab [root@jock /]# ll -d /openlab drwxr-xr-x. 2 root root 6 Feb 22 14:28 /openlab # 设置普通权限 [root@jock /]# chmod 770 /openlab/ [root@jock /]# ll -d /openlab/ drwxrwx---. 2 root root 6 Feb 22 14:28 /openlab/ # 创建两个用户和一个组 [root@jock /]# useradd zs [root@jock /]# useradd lisi [root@jock /]# groupadd hehe # 给这个组设置用户列表 [root@jock /]# gpasswd -M zs,lisi hehe # 修改目录的所属组 [root@jock /]# chown root:hehe /openlab/ [root@jock /]# ll -d /openlab/ drwxrwx---. 2 root hehe 6 Feb 22 14:28 /openlab/ # 再次创建一个用户并设置密码 [root@jock /]# useradd ww [root@jock /]# passwd ww Changing password for user ww. New password: BAD PASSWORD: The password is shorter than 8 characters Retype new password: passwd: all authentication tokens updated successfully. [root@jock /]# ll -d /openlab/ drwxrwx---. 2 root hehe 6 Feb 22 14:28 /openlab/ # 为用户设置 acl 权限 [root@jock /]# setfacl -m u:ww:rx /openlab [root@jock /]# ll -d /openlab/ drwxrwx---+ 2 root hehe 6 Feb 22 14:28 /openlab/ [root@jock /]# su - ww [ww@jock ~]$ cd /openlab/ [ww@jock openlab]$ touch aa touch: cannot touch 'aa': Permission denied # 为了演示,我们再创建了一个 xixi 组 [root@jock /]# groupadd xixi # 然后为这个 xixi 组设置 acl 权限 [root@jock /]# setfacl -m g:xixi:rwx /openlab/ [root@jock /]# ll -d /openlab/ drwxrwx---+ 2 root hehe 6 Feb 22 14:28 /openlab/
11.3.2 查看ACL权限
查看 ACL 权限是通过 getfacl 命令来实现的。语法:
[root@jock /]# getfacl --help getfacl 2.3.1 -- get file access control lists Usage: getfacl [-aceEsRLPtpndvh] file ... -a, --access display the file access control list only -d, --default display the default access control list only -c, --omit-header do not display the comment header -e, --all-effective print all effective rights -E, --no-effective print no effective rights -s, --skip-base skip files that only have the base entries -R, --recursive recurse into subdirectories -L, --logical logical walk, follow symbolic links -P, --physical physical walk, do not follow symbolic links -t, --tabular use tabular output format -n, --numeric print numeric user/group identifiers --one-file-system skip files on different filesystems -p, --absolute-names don't strip leading '/' in pathnames -v, --version print version and exit -h, --help this help text
使用示例:
[root@jock /]# getfacl /openlab/ getfacl: Removing leading '/' from absolute path names # file: openlab/ # owner: root # group: hehe user::rwx user:ww:r-x group::rwx group:xixi:rwx mask::rwx other::---
11.3.3 删除ACL权限
实现这个功能,还是使用 setfacl 命令,只是通过 -x 或 -b 选项来实现
[root@jock /]# setfacl -x u:ww /openlab/ [root@jock /]# getfacl /openlab/ getfacl: Removing leading '/' from absolute path names # file: openlab/ # owner: root # group: hehe user::rwx group::rwx group:xixi:rwx mask::rwx other::--- [root@jock /]# setfacl -b /openlab/ [root@jock /]# getfacl /openlab/ getfacl: Removing leading '/' from absolute path names # file: openlab/ # owner: root # group: hehe user::rwx group::rwx other::---
12. 网络管理
12.1 nmcli
网络管理我们只需要记住 nmcli 命令就好。查看命令的格式:
[root@jock /]# nmcli --help Usage: nmcli [OPTIONS] OBJECT { COMMAND | help } OPTIONS -a, --ask ask for missing parameters -c, --colors auto|yes|no whether to use colors in output -e, --escape yes|no escape columns separators in values -f, --fields <field,...>|all|common specify fields to output -g, --get-values <field,...>|all|common shortcut for -m tabular -t -f -h, --help print this help -m, --mode tabular|multiline output mode -o, --overview overview mode -p, --pretty pretty output -s, --show-secrets allow displaying passwords -t, --terse terse output -v, --version show program version -w, --wait <seconds> set timeout waiting for finishing operations OBJECT g[eneral] NetworkManager's general status and operations n[etworking] overall networking control r[adio] NetworkManager radio switches c[onnection] NetworkManager's connections d[evice] devices managed by NetworkManager a[gent] NetworkManager secret agent or polkit agent m[onitor] monitor NetworkManager changes
使用示例:
# 查看网络信息 [root@jock /]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 00:0c:29:08:da:ba brd ff:ff:ff:ff:ff:ff altname enp3s0 inet 192.168.72.120/24 brd 192.168.72.255 scope global noprefixroute ens160 valid_lft forever preferred_lft forever inet 192.168.72.128/24 brd 192.168.72.255 scope global secondary dynamic noprefixroute ens160 valid_lft 1501sec preferred_lft 1501sec inet6 fe80::20c:29ff:fe08:daba/64 scope link noprefixroute valid_lft forever preferred_lft forever # 设置IP nmcli c modify ens160 ipv4.addresses 192.168.72.120/24 # 设置为手动方式 nmcli c modify ens160 ipv4.method manual # 配置dns nmcli c modify ens160 ipv4.dns 114.114.114.114 # 配置网关 nmcli c modify ens160 ipv4.gateway 192.168.72.2 # 设置自动连接 nmcli c modify ens160 connection.autoconnect yes # 更新会话 nmcli c up ens160 # 增加一个新的 IP 地址 [root@jock ~]# nmcli c modify ens160 +ipv4.addresses 192.168.72.121/24 [root@jock ~]# nmcli c up ens160 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/5) [root@jock ~]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 00:0c:29:08:da:ba brd ff:ff:ff:ff:ff:ff altname enp3s0 inet 192.168.72.120/24 brd 192.168.72.255 scope global noprefixroute ens160 valid_lft forever preferred_lft forever inet 192.168.72.121/24 brd 192.168.72.255 scope global secondary noprefixroute ens160 valid_lft forever preferred_lft forever inet6 fe80::20c:29ff:fe08:daba/64 scope link noprefixroute valid_lft forever preferred_lft forever # 删除一个 IP [root@jock ~]# nmcli c modify ens160 -ipv4.addresses 192.168.72.121/24 [root@jock ~]# nmcli c up ens160 Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/6) [root@jock ~]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 00:0c:29:08:da:ba brd ff:ff:ff:ff:ff:ff altname enp3s0 inet 192.168.72.120/24 brd 192.168.72.255 scope global noprefixroute ens160 valid_lft forever preferred_lft forever inet6 fe80::20c:29ff:fe08:daba/64 scope link noprefixroute valid_lft forever preferred_lft forever
12.2 主机映射
[root@jock ~]# ping jock ^C [root@jock ~]# ping 192.168.72.120 PING 192.168.72.120 (192.168.72.120) 56(84) bytes of data. 64 bytes from 192.168.72.120: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.72.120: icmp_seq=2 ttl=64 time=0.071 ms 64 bytes from 192.168.72.120: icmp_seq=3 ttl=64 time=0.076 ms ^C --- 192.168.72.120 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2039ms rtt min/avg/max/mdev = 0.071/0.073/0.076/0.002 ms
我们如果希望通过 ping 主机名称也能够 ping 通,则需要对主机名和 IP 地址进行映射。好处是我们在后续使用时,就通过主机名来使用而不是通过 IP 地址。
要想两者可以进行映射,我们就需要修改 /etc/hosts 文件,在这个文件中去添加映射关系。
[root@jock ~]# vim /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.72.120 jock
映射好后,就可以 ping 通过了
[root@jock ~]# ping jock PING jock (192.168.72.120) 56(84) bytes of data. 64 bytes from jock (192.168.72.120): icmp_seq=1 ttl=64 time=0.047 ms 64 bytes from jock (192.168.72.120): icmp_seq=2 ttl=64 time=0.073 ms 64 bytes from jock (192.168.72.120): icmp_seq=3 ttl=64 time=0.073 ms 64 bytes from jock (192.168.72.120): icmp_seq=4 ttl=64 time=0.067 ms
13. 磁盘管理
[root@jock ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS sr0 11:0 1 8.9G 0 rom nvme0n1 259:0 0 50G 0 disk ├─nvme0n1p1 259:1 0 1G 0 part /boot └─nvme0n1p2 259:2 0 49G 0 part ├─rhel_bogon-root 253:0 0 44G 0 lvm / └─rhel_bogon-swap 253:1 0 5G 0 lvm [SWAP] nvme0n2 259:3 0 20G 0 disk
要使用一个新的磁盘,我们需要做如下的步骤:
1)查看磁盘 lsblk
2)对磁盘进行分区 fdisk 格式为 fdisk 设置名称(如:/dev/nvme0n2)
[root@jock ~]# fdisk /dev/nvme0n2 Command (m for help): n # 输入n 来创建新分区 Partition type p primary (0 primary, 0 extended, 4 free) e extended (container for logical partitions) Select (default p): p # 创建主分区 Partition number (1-4, default 1): # 第一个主分区 First sector (2048-41943039, default 2048): # 指定扇区大小,默认就好 Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-41943039, default 41943039): +5G # 指定分区大小 Created a new partition 1 of type 'Linux' and of size 5 GiB. Command (m for help): n # 再创建一个新分区 Partition type p primary (1 primary, 0 extended, 3 free) e extended (container for logical partitions) Select (default p): p Partition number (2-4, default 2): First sector (10487808-41943039, default 10487808): +15G Value out of range. First sector (10487808-41943039, default 10487808): Last sector, +/-sectors or +/-size{K,M,G,T,P} (10487808-41943039, default 41943039): Created a new partition 2 of type 'Linux' and of size 15 GiB. Command (m for help): w # 保存分区 The partition table has been altered. Calling ioctl() to re-read partition table. Syncing disks.
3)对分区进行格式化,使用 mkfs.xfs 命令
# 查看分区号 [root@jock ~]# blkid /dev/mapper/rhel_bogon-swap: UUID="c40a1d4e-8acc-4aa6-af02-773c878f5588" TYPE="swap" /dev/nvme0n1p1: UUID="98e55bfe-116c-411f-956c-d3e925b515c5" TYPE="xfs" PARTUUID="d366e00e-01" /dev/nvme0n1p2: UUID="gklf44-wXFJ-G8dL-qAtd-eo50-onCK-5qz24M" TYPE="LVM2_member" PARTUUID="d366e00e-02" /dev/sr0: UUID="2023-04-13-16-58-02-00" LABEL="RHEL-9-2-0-BaseOS-x86_64" TYPE="iso9660" PTUUID="d3d1f9a5" PTTYPE="dos" /dev/nvme0n2p1: PARTUUID="6bf53a97-01" /dev/nvme0n2p2: PARTUUID="6bf53a97-02" /dev/mapper/rhel_bogon-root: UUID="a673e989-57a6-4257-be10-bb807f7153d7" TYPE="xfs" # 对分区号为 /dev/nvme0n2p1 进行格式化 [root@jock ~]# mkfs.xfs /dev/nvme0n2p1 meta-data=/dev/nvme0n2p1 isize=512 agcount=4, agsize=327680 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=1, sparse=1, rmapbt=0 = reflink=1 bigtime=1 inobtcount=1 data = bsize=4096 blocks=1310720, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0, ftype=1 log =internal log bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 # 对分区号为 /dev/nvme0n2p2 进行格式化 [root@jock ~]# mkfs.xfs /dev/nvme0n2p2 meta-data=/dev/nvme0n2p2 isize=512 agcount=4, agsize=982976 blks = sectsz=512 attr=2, projid32bit=1 = crc=1 finobt=1, sparse=1, rmapbt=0 = reflink=1 bigtime=1 inobtcount=1 data = bsize=4096 blocks=3931904, imaxpct=25 = sunit=0 swidth=0 blks naming =version 2 bsize=4096 ascii-ci=0, ftype=1 log =internal log bsize=4096 blocks=2560, version=2 = sectsz=512 sunit=0 blks, lazy-count=1 realtime =none extsz=4096 blocks=0, rtextents=0 # 再次查看分区信息 [root@jock ~]# blkid /dev/mapper/rhel_bogon-swap: UUID="c40a1d4e-8acc-4aa6-af02-773c878f5588" TYPE="swap" /dev/nvme0n1p1: UUID="98e55bfe-116c-411f-956c-d3e925b515c5" TYPE="xfs" PARTUUID="d366e00e-01" /dev/nvme0n1p2: UUID="gklf44-wXFJ-G8dL-qAtd-eo50-onCK-5qz24M" TYPE="LVM2_member" PARTUUID="d366e00e-02" /dev/sr0: UUID="2023-04-13-16-58-02-00" LABEL="RHEL-9-2-0-BaseOS-x86_64" TYPE="iso9660" PTUUID="d3d1f9a5" PTTYPE="dos" /dev/mapper/rhel_bogon-root: UUID="a673e989-57a6-4257-be10-bb807f7153d7" TYPE="xfs" /dev/nvme0n2p1: UUID="8a3f6aff-dafe-4257-9046-454f0ee8eca1" TYPE="xfs" PARTUUID="6bf53a97-01" /dev/nvme0n2p2: UUID="f8ba088d-3816-4e05-9172-6577fb6155a5" TYPE="xfs" PARTUUID="6bf53a97-02"
4)挂载,使用 mount 命令
命令格式:
#mount [-t 文件系统类型] 设备名 挂载点目录
mount [-t vfstype] [-o options] device dir
1、-t vfstype 指定文件系统的类型,通常不必指定,mount 会自动选择正确的类型。
光盘或光盘镜像:iso9660
DOS fat16文件系统:msdos
Windows 9x fat32文件系统:vfat
Windows NT ntfs文件系统:ntfs
Mount Windows文件网络共享:smbfs
UNIX(LINUX) 文件网络共享:nfs
2、-o options 主要用来描述设备或档案的挂接方式。
loop:用来把一个文件当成硬盘分区挂接上系统
ro:采用只读方式挂接设备
rw:采用读写方式挂接设备
iocharset:指定访问文件系统所用字符集
3、device 要挂接(mount)的设备。
4、dir设备在系统上的挂接点(mount point)。
使用示例:
# 创建挂载点 [root@jock ~]# mkdir /opt/mydisk # 将格式化好的磁盘挂载到挂载点上 [root@jock ~]# mount /dev/nvme0n2p1 /opt/mydisk/ # 查看磁盘信息 [root@jock ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS sr0 11:0 1 8.9G 0 rom nvme0n1 259:0 0 50G 0 disk ├─nvme0n1p1 259:1 0 1G 0 part /boot └─nvme0n1p2 259:2 0 49G 0 part ├─rhel_bogon-root 253:0 0 44G 0 lvm / └─rhel_bogon-swap 253:1 0 5G 0 lvm [SWAP] nvme0n2 259:3 0 20G 0 disk ├─nvme0n2p1 259:6 0 5G 0 part /opt/mydisk └─nvme0n2p2 259:7 0 15G 0 part
以上的挂载方式是临时的,当系统启动后,这个挂载就会失效,要想使用,我们还需要重新挂载。如果希望永久生效,则需要修改 /etc/fstab 文件,并在这个文件中添加内容
[root@jock ~]# vim /etc/fstab # 添加如下内容 /dev/mapper/rhel_bogon-root / xfs defaults 0 0 UUID=98e55bfe-116c-411f-956c-d3e925b515c5 /boot xfs defaults 0 0 /dev/mapper/rhel_bogon-swap none swap defaults 0 0 /dev/nvme0n2p2 /opt/mydisk2 xfs defaults 0 0 # 磁盘名称 挂载点 文件类型
[root@jock ~]# mkdir /opt/mydisk2 [root@jock ~]# mount /dev/nvme0n2p2 /opt/mydisk2 [root@jock ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS sr0 11:0 1 8.9G 0 rom nvme0n1 259:0 0 50G 0 disk ├─nvme0n1p1 259:1 0 1G 0 part /boot └─nvme0n1p2 259:2 0 49G 0 part ├─rhel_bogon-root 253:0 0 44G 0 lvm / └─rhel_bogon-swap 253:1 0 5G 0 lvm [SWAP] nvme0n2 259:3 0 20G 0 disk ├─nvme0n2p1 259:6 0 5G 0 part /opt/mydisk └─nvme0n2p2 259:7 0 15G 0 part /opt/mydisk2