linux基础命令汇总

说明

本文仅仅对一些基础命令做演示,不涉及过多的原理性,以及概念性的东西,
示例中仅仅列出常用的选项,对于不常用的选项不做介绍以及演示。
其中部分帮助信息是来源于man查寻结果,未作翻译,请谅解。


enable(内置命令)

命令示例

enable -a  显示所有激活和禁用的内置命令
enable -n  显示所有已经禁用的内置命令
enable -n echo  禁用内置命令 echo

命令演示

禁用命令

[root@centos6 ~]#enable -n echo       
[root@centos6 ~]#enable -a | grep echo
enable -n echo
[root@centos6 ~]#enable -n echo 
[root@centos6 ~]#enable -n 
enable -n echo
[root@centos6 ~]#enable -n type
[root@centos6 ~]#enable -n
enable -n echo
enable -n type

启用命令

[root@centos6 ~]#enable echo
[root@centos6 ~]#enable -a | grep echo
enable echo

type 显示命令的类型(内置命令)

语法

type: type [-afptP] name [name ...]

Options:
    -a   # 显示所有的命令类型,包括别名、内置命令、函数、(不使用-p选项的情况下)
    -f   # suppress shell function lookup
    -P   # 强制返回命令的路径,即使后跟的是别名、内置命令、函数;针对既是内置命令又是外部命令的,返回的是外部命令的路径(如echo)
    -p   # 只返回是外部命令的路径,如果 `type -t NAME' 返回的不是file类型,结果为空。
    -t   # 返回单个的类型字符,如 `alias', `keyword',`function', `builtin', `file'
Arguments:
    NAME # Command name to be interpreted.

命令示例

type ls
type cd
type httpd
type -t ls
type -t cd
type -t httpd
type -P httpd
type -P echo
type echo
type -p cd
type -p httpd

返回具体路径的都是外部命令

[root@centos6 ~]# type free
free is /usr/bin/free
[root@centos6 ~]#type httpd
httpd is /web/httpd/bin/httpd

返回shell builtin的都是bash内部命令

[root@centos6 ~]# type cd
cd is a shell builtin
[root@centos6 ~]# 

返回的是别名

[root@centos6 ~]#type ls
ls is aliased to `ls --color=auto'

短格式返回命令的类型

[root@centos6 ~]#type -t ls
alias
[root@centos6 ~]#type -t cd
builtin
[root@centos6 ~]#type -t httpd
file

强制返回类型

[root@centos6 ~]#type -P httpd
/web/httpd/bin/httpd
[root@centos6 ~]#type -P echo
/bin/echo
[root@centos6 ~]#type echo
echo is a shell builtin

只返回外部命令

[root@centos6 ~]#type -p cd
[root@centos6 ~]#type -p httpd
/web/httpd/bin/httpd

hash 查看设置外部命令路劲缓存(内置命令)

语法

[root@centos7-scm ~]#help hash
hash: hash [-lr] [-p pathname] [-dt] [name ...]
    Remember or display program locations.
    
    Determine and remember the full pathname of each command NAME.  If
    no arguments are given, information about remembered commands is displayed.
    
    Options:
      -d                forget the remembered location of each NAME
      -l                display in a format that may be reused as input
      -p pathname       use PATHNAME is the full pathname of NAME
      -r                forget all remembered locations
      -t                print the remembered location of each NAME, preceding
                each location with the corresponding NAME if multiple
                NAMEs are given
    Arguments:
      NAME              Each NAME is searched for in $PATH and added to the list
                of remembered commands.
    
    Exit Status:
    Returns success unless NAME is not found or an invalid option is given.

示例

hash  查看所有命令的路径缓存
hash -r  清空所有命令的路径缓存
hash -d command1 [command2 ...]  清空指定的命令路径缓存
hash command1 [command2 ...]  清空commands的hits计数器
hash -l  以单行形式显示所有,以便作为输入使用

演示

查看所有的命令路径缓存

[root@centos7-scm ~]#hash
hits    command
   7    /usr/sbin/ifconfig
   1    /usr/bin/ls
   2    /usr/bin/tree

清除所有的命令路径缓存

[root@centos7-scm ~]#hash -r
[root@centos7-scm ~]#hash
hash: hash table empty

清空htis计数器

[root@centos6 ~]#hash 
hits    command
   1    /sbin/ifconfig
   1    /bin/ls
[root@centos6 ~]#hash ls ifconfig
[root@centos6 ~]#hash 
hits    command
   0    /sbin/ifconfig
   0    /bin/ls

以单行形式显示,以便作为输入使用

[root@centos6 ~]#hash -l 
builtin hash -p /sbin/ifconfig ifconfig
builtin hash -p /bin/ls ls

清空指定的命令路径缓存

[root@centos6 ~]#hash 
hits    command
   1    /sbin/ifconfig
   1    /bin/ls
[root@centos6 ~]#hash -d ls ifconfig
[root@centos6 ~]#hash
hash: hash table empty

alias 定义以及显示命令别名(内置明命令)

语法

alias: alias [-p] [name[=value] ... ]
    没有参数的时候,会以 alias NAME=VALUE 的形式显示所有的别名    
Options:
    -p        Print all defined aliases in a reusable format (默认选项)

命令示例

alias    # 显示所有的命令别名
alias rm='mv -i -t /trash/'  # 定义别名
alias netdir='cd /etc/sysconfig/network-scripts/'  # 定义别名

演示

alias & alias -p

[root@centos6 ~]#alias
alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
[root@centos6 ~]#
[root@centos6 ~]#alias -p
alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
[root@centos6 ~]#

alias rm='mv -i -t /trash/'

[root@centos6 ~]#alias rm='mv -i -t /trash/'
[root@centos6 ~]#mkdir /trash
[root@centos6 ~]#ls test.log
test.log
[root@centos6 ~]#rm test.log 
[root@centos6 ~]#ls test.log
ls: cannot access test.log: No such file or directory
[root@centos6 ~]#ls /trash/
test.log
[root@centos6 ~]#

alias cdnet='cd /etc/sysconfig/network-scripts/'

[root@centos6 ~]#alias cdnet='cd /etc/sysconfig/network-scripts/'
[root@centos6 ~]#cdnet
[root@centos6 network-scripts]#pwd
/etc/sysconfig/network-scripts

unalias 取消别名定义

语法

unalias: unalias [-a] name [name ...]
    Remove each NAME from the list of defined aliases.
    
Options:
    -a        remove all alias definitions(不建议使用哦)

命令示例

unalias cdnet

命令演示

[root@centos6 ~]#alias | grep cdnet
alias cdnet='cd /etc/sysconfig/network-scripts/'
[root@centos6 ~]#unalias cdnet
[root@centos6 ~]#alias | grep cdnet
[root@centos6 ~]#

date 查看设置系统时间(外部命令)

Linux的两种时钟

  • 系统时钟:由Linux内核通过CPU的工作频率进行的
  • 硬件时钟:主板

date

date 显示和设置系统时间
date        # 查看当前系统当地时间
date -u     # 查看当前系统格林尼治时间
date --utc  # 查看当前系统格林尼治时间
date 010312302017.10            # 设置时间为2017年01月1日12点30分10秒
date -s '2016-07-08 09:10:11'   # 通过字符串设置时间
date -s '3 day'                 # 设置时间为3天后的时间
date -s '-3 day'                # 设置时间为3天前的时间
date -d '20170809 3:05:6'       # 通过字符串显示显示时间(不是当前的时间)
date -d "2 days ago"            # 显示两天前的时间
date -d "2 hours ago"           # 显示两小时前的时间
date -d '2 days'                # 两天以后的时间
date -d '2 weeks'               # 两周以后的时间
date +%s                        # 显示当前时间点到1970年1月1日00:00:00的秒数
date -d @1509536033             # 显示当前时间点到1970年1月1日00:00:00的秒数1509536033转化为时间
date --date="@1509536033"       # 同上
date "+%Y-%m-%d %H:%M:%S"       # 格式化显示时间
date +%Y-%m-%d\ %H:%M:%S        # 同上(不使用引号就要用\将空格转译)
date -d @1509536033 "+%Y-%m-%d %H:%M:%S"  # 显示当前时间点到1970年1月1日00:00:00的秒数1509536033转化为时间并格式化显示
date 关于时间显示的其他方式【可以通过 info date 查看到详细的范例】
今天:
date
date -d today
date -d now
明天:
date -d tomorrow
date -d next-day
date -d next-days
date -d "next day"
date -d "next days"
date -d "+1 day"
date -d "+1 days"
date -d "1 day"
date -d "1 days"
date -d "-1 day ago"
date -d "-1 days ago"
昨天:
date -d yesterday
date -d last-day
date -d last-days
date -d "last day"
date -d "last days"
date -d "-1 day"
date -d "-1 days"
date -d "1 day ago"
date -d "1 days ago"
前天:
date -d "2 day ago"
date -d "2 days ago"
date -d "-2 day"
date -d "-2 days"
大前天:
date -d "3 day ago"
date -d "3 days ago"
date -d "-3 day"
date -d "-3 days"
上周,一周前:
date -d "1 week ago"
date -d "1 weeks ago"
上个星期五(不是上周五):
date -d "last-friday"
date -d "last friday"
上月,一月前:
date -d last-month
date -d last-months
date -d "-1 month"
date -d "-1 months"
下月,一月后:
date -d next-month
date -d next-months
date -d "+1 month"
date -d "+1 months"
去年,一年前:
date -d last-year
date -d last-years
date -d "-1 year"
date -d "-1 years"
明年,一年后:
date -d next-year
date -d next-years
date -d "+1 year"
date -d "+1 years"
一小时前:
date -d "last-hour"
date -d "last-hours"
date -d "1 hour ago"
date -d "1 hours ago"
一小时后:
date -d "1 hour"
date -d "1 hours"
一分钟前:
date -d "1 minute ago"
date -d "1 minutes ago"
一分钟后:
date -d "1 minute"
date -d "1 minutes"
一秒前:
date -d "1 second ago"
date -d "1 seconds ago"
一秒后:
date -d "1 second"
date -d "1 seconds"

date的几个简单练习

1、显示当前时间,格式:2016-06-18 10:20:30
2、显示前天是星期几
3、设置当前日期为2019-08-07 06:05:10
  • 显示当前时间,格式:2016-06-18 10:20:30
[root@centos7 ~]# date "+%F %T"
2018-11-13 15:04:15
[root@centos7 ~]# date "+%Y-%m-%d %H:%M:%S"
2018-11-13 15:04:46
[root@centos7 ~]#
  • 显示前天是星期几
[root@centos7 ~]# date -d "2 days ago" "+%w"
0    # %u     day of week (1..7); 1 is Monday
[root@centos7 ~]# date -d "2 days ago" "+%u"
7    # %w     day of week (0..6); 0 is Sunday
[root@centos7 ~]$date -d "2 days ago" "+%A"
Sunday  
  • 设置当前日期为2019-08-07 06:05:10
[root@centos7 ~]# date -s '2019-08-07 06:05:10'
Wed Aug  7 06:05:10 CST 2019
[root@centos7 ~]# date
Wed Aug  7 06:05:10 CST 2019
[root@centos7 ~]# 

hwclock & clock(外部命令)

hwclockclock: 显示硬件时钟

clock 是 hwclock 的软链接

[root@centos6 ~]#ll `which clock`
lrwxrwxrwx. 1 root root 7 Nov  9 07:10 /sbin/clock -> hwclock

选项

-s, --hctosys以硬件时钟为准,校正系统时钟
-w, --systohc以系统时钟为准,校正硬件时钟

命令示例

# 将硬件时间覆盖系统时间
clock -s
hwclock -s
# 将系统时间覆盖硬件时间
clock -w
hwclock -w

命令演示

用硬件时间覆盖系统时间

[root@centos6 ~]#date
Fri Dec 28 07:54:27 CST 2018
[root@centos6 ~]#clock
Sun 30 Dec 2018 02:04:35 AM CST  -0.592602 seconds
[root@centos6 ~]#clock -s
[root@centos6 ~]#date
Sun Dec 30 02:07:14 CST 2018

用系统时间覆盖硬件时间

[root@centos6 ~]#date
Sun Dec 30 02:08:22 CST 2018  # 系统时间是上午的 02:08:22
[root@centos6 ~]#ntpdate ntp1.aliyun.com  # 同步系统时间
30 Dec 14:10:53 ntpdate[19775]: step time server 120.25.115.20 offset 43334.969693 sec
[root@centos6 ~]#date
Sun Dec 30 14:10:55 CST 2018   # 系统时间更新为下午的 14:10:55
[root@centos6 ~]#clock
Sun 30 Dec 2018 02:08:49 AM CST  -0.418304 seconds  # 硬件时间是上午的02:08:49
[root@centos6 ~]#clock -w  # 用系统时间设置硬件时间
[root@centos6 ~]#clock
Sun 30 Dec 2018 02:11:30 PM CST  -0.555817 seconds  # 硬件时间和系统是时间一致了。

linux命令行日历cal(外部命令)

帮助

[root@centos6 ~]# man cal
CAL(1)                    BSD General Commands Manual                   CAL(1)

NAME
     cal - displays a calendar

SYNOPSIS
     cal [-smjy13] [[[day] month] year]

DESCRIPTION
     Cal displays a simple calendar.  If arguments are not specified, the current month is displayed.  The options are as
     follows:
     -1      Display single month output.  (This is the default.)
     -3      Display prev/current/next month output.
     -s      Display Sunday as the first day of the week.
     -m      Display Monday as the first day of the week.
     -j      Display Julian dates (days one-based, numbered from January 1).
     -y      Display a calendar for the current year.
     -V      Display version information and exit.

使用范例

默认显示当一个月的日历(默认是前月的日历)

[root@centos6 ~]# cal
    November 2018   
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

[root@centos6 ~]# cal -1
    November 2018   
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

显示当前季度的日历

[root@centos6 ~]# cal -3
    October 2018          November 2018         December 2018   
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6               1  2  3                     1
 7  8  9 10 11 12 13   4  5  6  7  8  9 10   2  3  4  5  6  7  8
14 15 16 17 18 19 20  11 12 13 14 15 16 17   9 10 11 12 13 14 15
21 22 23 24 25 26 27  18 19 20 21 22 23 24  16 17 18 19 20 21 22
28 29 30 31           25 26 27 28 29 30     23 24 25 26 27 28 29
                                            30 31               
[root@centos6 ~]# 

显示当前月的日历(周一为每周的第一天格式)

[root@centos6 ~]# cal -m
    November 2018   
Mo Tu We Th Fr Sa Su
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

显示当前月的日历(周日为每周的第一天格式)

[root@centos6 ~]# cal -s
    November 2018   
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30

以天数形式显示当月日历

[root@centos6 ~]# cal -j
       November 2018       
Sun Mon Tue Wed Thu Fri Sat
                305 306 307
308 309 310 311 312 313 314
315 316 317 318 319 320 321
322 323 324 325 326 327 328
329 330 331 332 333 334

显示整年的日历

[root@centos6 ~]# cal -y
                               2018                               

       January               February                 March       
Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6                1  2  3                1  2  3
 7  8  9 10 11 12 13    4  5  6  7  8  9 10    4  5  6  7  8  9 10
14 15 16 17 18 19 20   11 12 13 14 15 16 17   11 12 13 14 15 16 17
21 22 23 24 25 26 27   18 19 20 21 22 23 24   18 19 20 21 22 23 24
28 29 30 31            25 26 27 28            25 26 27 28 29 30 31

        April                   May                   June        
Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7          1  2  3  4  5                   1  2
 8  9 10 11 12 13 14    6  7  8  9 10 11 12    3  4  5  6  7  8  9
15 16 17 18 19 20 21   13 14 15 16 17 18 19   10 11 12 13 14 15 16
22 23 24 25 26 27 28   20 21 22 23 24 25 26   17 18 19 20 21 22 23
29 30                  27 28 29 30 31         24 25 26 27 28 29 30

        July                  August                September     
Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7             1  2  3  4                      1
 8  9 10 11 12 13 14    5  6  7  8  9 10 11    2  3  4  5  6  7  8
15 16 17 18 19 20 21   12 13 14 15 16 17 18    9 10 11 12 13 14 15
22 23 24 25 26 27 28   19 20 21 22 23 24 25   16 17 18 19 20 21 22
29 30 31               26 27 28 29 30 31      23 24 25 26 27 28 29
                                              30
       October               November               December      
Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa   Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6                1  2  3                      1
 7  8  9 10 11 12 13    4  5  6  7  8  9 10    2  3  4  5  6  7  8
14 15 16 17 18 19 20   11 12 13 14 15 16 17    9 10 11 12 13 14 15
21 22 23 24 25 26 27   18 19 20 21 22 23 24   16 17 18 19 20 21 22
28 29 30 31            25 26 27 28 29 30      23 24 25 26 27 28 29
                                              30 31

显示日历的版本

[root@centos6 ~]# cal -V
cal from util-linux-ng 2.17.2

显示日历的帮助信息

[root@centos6 ~]# cal -h
cal: invalid option -- 'h'
usage: cal [-13smjyV] [[[day] month] year]
[root@centos6 ~]#

查看指定的日期

输入图片说明


shutdown 关机

帮助信息

Usage: shutdown [OPTION]... TIME [MESSAGE]
Bring the system down.

Options:
  -r                          reboot after shutdown 关机后重启
  -h                          halt or power off after shutdown 关机后断掉电源
  -H                          halt after shutdown (implies -h) 关机后断掉电源
  -P                          power off after shutdown (implies -h) 关机后断掉电源
  -c                          cancel a running shutdown  取消正在执行的关机
  -k                          only send warnings, don't shutdown  仅仅发送警告消息不关机
  -q, --quiet                 reduce output to errors only  静默模式,仅仅输出关机过程中的错误信息
  -v, --verbose               increase output to include informational messages 输出关机的详细信息
      --help                  display this help and exit  显示帮助信息
      --version               output version information and exit  查看命令版本信息

TIME:无指定,默认相当于+1
now: 立刻,相当于+0
+m: 相对时间表示法,几分钟之后;例如+3
hh:mm: 绝对时间表示,指明具体时间

示例

reboot -r  关机后重启
reboot -h  关机后断掉电源
reboot -H  关机后断掉电源
reboot -P  关机后断掉电源
shutdown 1 m 'test'  1分钟以后将关机,并发送提示信息'test'
shutdown -c 取消关机操作(需要在另外一个终端上操作)

1分钟后关机

取消关机


w 显示已经登陆的用户以及在这些用户正在干什么

语法

Show who is logged on and what they are doing

w: invalid option -- '-'
usage: w -hlsufV [user]
    -h    skip header
    -l    long listing (default)
    -s    short listing
    -u    ignore uid of processes
    -f    toggle FROM field (default on)
    -i    display IP address instead of hostname (if possible)
    -V    display version

命令演示

默认输出

[root@centos6 ~]#w
 14:37:02 up 1 day, 23:58,  5 users,  load average: 0.60, 0.40, 0.32
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1     :0               Wed08    4days 41.01s 41.01s /usr/bin/Xorg :0 -br -verbose -audit 4 -auth /var/run/gdm/auth-for-gdm-Br5nSW/database -n
root     pts/0    :0.0             Wed08    2days  0.71s  0.47s ssh 127.0.0.1
root     pts/1    127.0.0.1        Wed08    2days  0.34s  0.34s -bash
root     pts/2    192.168.27.2     Fri04    2days  0.41s  0.10s vim /etc/init.d/httpd
root     pts/3    192.168.27.2     Fri06    0.00s  0.38s  0.00s w

-h 不显示头部信息

[root@centos6 ~]#w -h
root     tty1     :0               Wed08    4days 41.01s 41.01s /usr/bin/Xorg :0 -br -verbose -audit 4 -auth /var/run/gdm/auth-for-gdm-Br5nSW/database -n
root     pts/0    :0.0             Wed08    2days  0.71s  0.47s ssh 127.0.0.1
root     pts/1    127.0.0.1        Wed08    2days  0.34s  0.34s -bash
root     pts/2    192.168.27.2     Fri04    2days  0.41s  0.10s vim /etc/init.d/httpd
root     pts/3    192.168.27.2     Fri06    0.00s  0.38s  0.00s w -h

-s 短格式显示

[root@centos6 ~]#w -s
 14:38:53 up 2 days, 0 min,  5 users,  load average: 0.24, 0.33, 0.30
USER     TTY      FROM               IDLE WHAT
root     tty1     :0                4days /usr/bin/Xorg :0 -br -verbose -audit 4 -auth /var/run/gdm/auth-for-gdm-Br5nSW/database -nolisten tcp vt1
root     pts/0    :0.0              2days ssh 127.0.0.1
root     pts/1    127.0.0.1         2days -bash
root     pts/2    192.168.27.2      2days vim /etc/init.d/httpd
root     pts/3    192.168.27.2      0.00s w -s

-u 参数演示

[root@centos6 ~]#w -u
 14:40:13 up 2 days, 1 min,  5 users,  load average: 0.32, 0.32, 0.30
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1     :0               Wed08    4days 41.03s 41.03s /usr/bin/Xorg :0 -br -verbose -audit 4 -auth /var/run/gdm/auth-for-gdm-Br5nSW/database -n
root     pts/0    :0.0             Wed08    2days  0.71s  0.47s ssh 127.0.0.1
root     pts/1    127.0.0.1        Wed08    2days  0.34s  0.34s -bash
root     pts/2    192.168.27.2     Fri04    2days  0.41s  0.10s vim /etc/init.d/httpd
root     pts/3    192.168.27.2     Fri06    0.00s  0.39s  0.00s w -u

who 显示当前所有的系统登陆会话

命令示例

who -a   # 相当于 who -bdprtTu --login
who -d   # 显示死的登陆会话
who -H   # 显示头部信息
who -l   # 显示系统登陆进程
who --login  # 显示系统登陆进程
who -m   # 只显示和登陆用户相关的登陆信息
who -q   # 统计所有的登陆用户以及登陆的数量
who -r   # 查看运行级别
who -s   # 短格式显示(默认)

命令演示

[root@centos6 ~]#who
root     tty1         2018-12-26 08:26 (:0)
root     pts/0        2018-12-26 08:26 (:0.0)
root     pts/1        2018-12-26 08:45 (127.0.0.1)
root     pts/2        2018-12-28 04:16 (192.168.27.2)
root     pts/3        2018-12-28 06:54 (192.168.27.2)
[root@centos6 ~]#who -a
           system boot  2018-12-26 08:26
           run-level 5  2018-12-26 08:26
LOGIN      tty2         2018-12-26 08:26              2193 id=2
LOGIN      tty3         2018-12-26 08:26              2195 id=3
LOGIN      tty4         2018-12-26 08:26              2198 id=4
LOGIN      tty5         2018-12-26 08:26              2205 id=5
LOGIN      tty6         2018-12-26 08:26              2208 id=6
root     + tty1         2018-12-26 08:26  old         2398 (:0)
root     + pts/0        2018-12-26 08:26  old         2776 (:0.0)
root     + pts/1        2018-12-26 08:45  old         2987 (127.0.0.1)
root     + pts/2        2018-12-28 04:16  old        19075 (192.168.27.2)
root     + pts/3        2018-12-28 06:54   .         19528 (192.168.27.2)
           pts/4        2018-12-28 03:36             18280 id=ts/4  term=0 exit=0
           pts/5        2018-12-28 01:04              8284 id=ts/5  term=0 exit=0
           pts/6        2018-12-28 03:08             13670 id=ts/6  term=0 exit=0
           pts/7        2018-12-28 01:04             17388 id=ts/7  term=0 exit=0
           pts/8        2018-12-28 00:59             16753 id=ts/8  term=0 exit=0

头部信息显示

[root@centos6 ~]#who -H
NAME     LINE         TIME             COMMENT   # <==头部信息
root     tty1         2018-12-26 08:26 (:0)
root     pts/0        2018-12-26 08:26 (:0.0)
root     pts/1        2018-12-26 08:45 (127.0.0.1)
root     pts/2        2018-12-28 04:16 (192.168.27.2)
root     pts/3        2018-12-28 06:54 (192.168.27.2)

显示登陆进程

[root@centos6 ~]#who -l
LOGIN    tty2         2018-12-26 08:26              2193 id=2
LOGIN    tty3         2018-12-26 08:26              2195 id=3
LOGIN    tty4         2018-12-26 08:26              2198 id=4
LOGIN    tty5         2018-12-26 08:26              2205 id=5
LOGIN    tty6         2018-12-26 08:26              2208 id=6
[root@centos6 ~]#
[root@centos6 ~]#who --login
LOGIN    tty2         2018-12-26 08:26              2193 id=2
LOGIN    tty3         2018-12-26 08:26              2195 id=3
LOGIN    tty4         2018-12-26 08:26              2198 id=4
LOGIN    tty5         2018-12-26 08:26              2205 id=5
LOGIN    tty6         2018-12-26 08:26              2208 id=6

只显示和登陆用户相关的登陆信息相当于who am i

[root@centos6 ~]#who -maH
NAME       LINE         TIME             IDLE          PID COMMENT  EXIT
root     + pts/3        2018-12-28 06:54   .         19528 (192.168.27.2)

[root@centos6 ~]#who -m
root     pts/3        2018-12-28 06:54 (192.168.27.2)
[root@centos6 ~]#who am i
root     pts/3        2018-12-28 06:54 (192.168.27.2)

统计所有的登陆用户以及登陆的数量

[ming@centos6 ~]$who  -q
root root root root root ming
# users=6

查看运行级别

[root@centos6 ~]#who -r
         run-level 5  2018-12-26 08:26

whoami 打印有效UID

[root@centos6 ~]#whatis whoami  
whoami               (1)  - print effective userid
[root@centos6 ~]#whoami
root

screen

通过screen实现远程协助

我们在工作中有时候会遇到这样的情况:我们遇到一个问题搞不定,需要他人运程协助。在windows中实现的方法有很多,但是在linux系统命令行怎么来实现呢?这里我们来介绍一个命令screen来实现这样的需求。
前提所有人都连接到同一台机器

screen命令可能没有安装,需要自己安装一下

yum install screen -y 

screen命令示例

screen –S [SESSION]       创建新screen会话 ,`SESSION` 就是一个名字,可以自定义
screen –x [SESSION]       加入screen会话
exit     退出并关闭screen会话
Ctrl+a,d        剥离当前screen会话
screen -ls      显示所有已经打开的screen会话
screen -r [SESSION]       恢复某screen会话

用法示例

  • 在一个窗口创建一个会话 scm(模拟第一个用户)
screen -S scm
  • 在另外一个窗口查看会话 (模拟第二个用户)
[root@centos6 ~]# screen -ls
There is a screen on:
        32081.scm       (Attached)
1 Socket in /var/run/screen/S-root.

[root@centos6 ~]# 
  • 第二个用户加入到会话中
screen -x scm
  • 此时可以实现两个用户的操作是实时同步的,就实现了我们的需求

  • 我们还可加入任意多个用户来实时分享所有的操作

通过screen实现防止终端退出导致命令执行失败

场景:
我们在执行一些备份命令的时候,可能执行的时间会很长,但是有可能会在命令执行过程中由于网络等原因导致我们的CRT 终端连接断开,
此时我们再连接到服务器的时候,还要重新执行同样的命令。
我们这时候就可以通过screen命令来解决此问题。

执行命令前先执行screen -S 会话名创建一个会话
screen -S ping-test # 也可以只使用 screen
screen -ls
通过ping演示长时间备份命令的执行
ping 8.8.8.8
关掉终端,演示故障
重新连接到服务器,执行screen -r 会话名恢复会话,可以看到命令还在执行

查看会话

[root@centos7-scm ~]#screen -ls
There is a screen on:
        55641.ping-test (Detached)
1 Socket in /var/run/screen/S-root.

恢复会话

screen -r ping-test

恢复效果

[root@centos7-scm ~]#screen -r ping-test
64 bytes from 8.8.8.8: icmp_seq=53 ttl=37 time=59.2 ms
64 bytes from 8.8.8.8: icmp_seq=54 ttl=37 time=66.0 ms
64 bytes from 8.8.8.8: icmp_seq=55 ttl=37 time=59.0 ms
64 bytes from 8.8.8.8: icmp_seq=56 ttl=37 time=60.1 ms
64 bytes from 8.8.8.8: icmp_seq=57 ttl=37 time=59.7 ms
64 bytes from 8.8.8.8: icmp_seq=58 ttl=37 time=63.7 ms
64 bytes from 8.8.8.8: icmp_seq=59 ttl=37 time=58.3 ms
64 bytes from 8.8.8.8: icmp_seq=60 ttl=37 time=61.6 ms
64 bytes from 8.8.8.8: icmp_seq=61 ttl=37 time=62.0 ms
64 bytes from 8.8.8.8: icmp_seq=62 ttl=37 time=66.3 ms
64 bytes from 8.8.8.8: icmp_seq=63 ttl=37 time=60.1 ms
64 bytes from 8.8.8.8: icmp_seq=64 ttl=37 time=70.2 ms
64 bytes from 8.8.8.8: icmp_seq=65 ttl=37 time=106 ms
64 bytes from 8.8.8.8: icmp_seq=66 ttl=37 time=61.0 ms
64 bytes from 8.8.8.8: icmp_seq=67 ttl=37 time=62.3 ms
64 bytes from 8.8.8.8: icmp_seq=68 ttl=37 time=59.2 ms

echo 显示一行文本信息

语法

NAME
       echo - display a line of text(显示一行文本信息)
语法
       echo [SHORT-OPTION]... [STRING]...    # 短格式
       echo LONG-OPTION     # 长格式

选项说明
       Echo the STRING(s) to standard output.(将字符串保准输出)

       -n     不输出结尾的换行(结尾不换行)
       -e     启用 \ 转义
       -E     禁用 \ (默认)
       --help 显示帮助信息
       --version 显示版本信息

下面是使用 -e 参数时支持的转义项:

       \\     backslash    输出反斜杠 \
       \a     alert (BEL)  报警声
       \b     backspace   
       \c     produce no further output  不再输出 \c 后面的字符串
       \e     escape     跳过后面的一个字符在输出
       \f     form feed   换页输出
       \n     new line   换行输出
       \r     carriage return  回车
       \t     horizontal tab  水平制表符
       \v     vertical tab  垂直制表符
       \0NNN  byte with octal value NNN (1 to 3 digits)
       \xHH   byte with hexadecimal value HH (1 to 2 digits)

       NOTE: 不同的shell支持的echo会有不同,以上是基于bash的echo.

演示

[root@centos6 ~]#echo 'test'
test
[root@centos6 ~]#
[root@centos6 ~]#echo -n  'test'
test[root@centos6 ~]#
[root@centos6 ~]#echo -e '123\b45'
1245
[root@centos6 ~]#echo -e '123\b\b45'
145
[root@centos6 ~]#echo -e '123\b\b\b45'
453
[root@centos6 ~]#echo -e '123\b\b\b4567'
4567
[root@centos6 ~]#echo -e 'test\c'
test[root@centos6 ~]#
[root@centos6 ~]#echo -e 'test\csfsfsdfsdf'
test[root@centos6 ~]#
[root@centos6 ~]#echo -e '123\e4567'    
123567
[root@centos6 ~]#echo -e '123\e4\e567'
12367
[root@centos6 ~]#
[root@centos6 ~]#echo -e '123\f4567'  
123
   4567
[root@centos6 ~]#echo -e '123\f\f4567'
123

   4567
[root@centos6 ~]#echo -e '123\f\f\f4567'
123


   4567
[root@centos6 ~]#echo -e '123\f\f\f45\f67'
123


   45
     67
[root@centos6 ~]#
[root@centos6 ~]#echo -e '123\n4567'      
123
4567
[root@centos6 ~]#echo -e '123\r4567'
4567
[root@centos6 ~]#echo -e '123\r456\r7'
756
[root@centos6 ~]#
[root@centos6 ~]#echo -e '123\t4567'  
123     4567
[root@centos6 ~]#echo -e '123\v4567'
123
   4567
[root@centos6 ~]#

{} 花括号的用法

备份

[root@centos6 app]# touch test.log
[root@centos6 app]# ls
test.log
[root@centos6 app]# 
[root@centos6 app]# cp test.log{,.bak}
[root@centos6 app]# ls
test.log  test.log.bak
[root@centos6 app]#

连续

[root@centos6 app]# echo file{1..2}
file1 file2
[root@centos6 app]# echo file{1..10}
file1 file2 file3 file4 file5 file6 file7 file8 file9 file10
[root@centos6 app]# echo file{001..10}
file001 file002 file003 file004 file005 file006 file007 file008 file009 file010
[root@centos6 app]# echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@centos6 app]# echo {A..Z}
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

倒序

[root@centos6 app]# echo {9..1}
9 8 7 6 5 4 3 2 1
[root@centos6 app]# echo {z..a}
z y x w v u t s r q p o n m l k j i h g f e d c b a
[root@centos6 app]# echo {Z..A}
Z Y X W V U T S R Q P O N M L K J I H G F E D C B A
[root@centos6 app]# 

步进

[root@centos6 app]# echo file{001..10..2}
file001 file003 file005 file007 file009
[root@centos6 app]# echo file{001..10..3}
file001 file004 file007 file010
[root@centos6 app]#
[root@centos6 app]# echo {9..1..3}
9 6 3
[root@centos6 app]# 

自由组合1(连续和非连续的)

mkdir -p /testdir/dir1/{x..y}/{a..b}
mkdir -p /testdir/dir1/{x,y}/{a,b}
mkdir -p /testdir/dir2/{x/{a..b},y}
mkdir -p /testdir/dir{3,4,5/dir{6..7}}

自由组合2(非连续的)

touch {a,d,g}.{log,txt}
[root@centos7 app]$touch {a,d,g}.{log,txt}
[root@centos7 app]$ls
a.log  a.txt  d.log  d.txt  g.log  g.txt
[root@centos7 app]$

自由组合3(连续的)

touch {1..9}.{a..c}
[root@centos7 app]$
[root@centos7 app]$touch {1..9}.{a..c}
[root@centos7 app]$ll
total 0
-rw-r--r--. 1 root root 0 Nov 17 11:22 1.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 1.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 1.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 2.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 2.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 2.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 3.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 3.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 3.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 4.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 4.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 4.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 5.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 5.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 5.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 6.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 6.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 6.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 7.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 7.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 7.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 8.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 8.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 8.c
-rw-r--r--. 1 root root 0 Nov 17 11:22 9.a
-rw-r--r--. 1 root root 0 Nov 17 11:22 9.b
-rw-r--r--. 1 root root 0 Nov 17 11:22 9.c
[root@centos7 app]$

history 显示和操作命令历史列表(内置命令)

命令行历史介绍

  • 保存你输入的命令历史。可以用它来重复执行命令
  • 登录shell时,会读取命令历史文件中记录下的命令 ~/.bash_history
  • 登录进shell后新执行的命令只会记录在缓存中;这些命令会用户退出时“追加”至命令历史文件中

history的使用技巧

重复前一个命令,有4种方法:
重复前一个命令使用上方向键,并回车执行
按!! 并回车执行
输入!-1 并回车执行
按Ctrl+p 并回车执行

!:0            # 执行前一条命令(去除参数)
Ctrl + n       # 显示当前历史中的下一条命令,但不执行
Ctrl + j       # 执行当前命令
!n             # 执行history命令输出对应序号n的命令
!-n            # 执行history历史中倒数第n个命令

!string        # 重复前一个以“string”开头的命令
!?string       # 重复前一个包含string的命令
!string:p      # 仅打印命令历史,而不执行
!$:p           # 打印输出!$ (上一条命令的最后一个参数)的内容
!*:p           # 打印输出!*(上一条命令的所有参数)的内容
^string        # 删除上一条命令中的第一个string
^string1^string2      # 将上一条命令中的第一个string1替换为string2
!:gs/string1/string2  # 将上一条命令中所有的string1都替换为string2

使用up(向上)和down(向下)键来上下浏览从前输入的命令

ctrl-r         # 来在命令历史中搜索命令
•(reverse-i-search)`’:

Ctrl+g         # 从历史搜索模式退出

要重新调用前一个命令中最后一个参数:
!$ 表示
Esc, .(点击Esc键后松开,然后点击. 键)
Alt+ .(按住Alt键的同时点击. 键) 如果是在xshell 或者crt中需要设置 "将ALT用作Meta键"

command !^     # 利用上一个命令的第一个参数做cmd的参数
command !$     # 利用上一个命令的最后一个参数做cmd的参数
command !*     # 利用上一个命令的全部参数做cmd的参数
command !:n    # 利用上一个命令的第n个参数做cmd的参数
command !n:^   # 调用第n条命令的第一个参数
command !n:$   # 调用第n条命令的最后一个参数
command !n:m   # 调用第n条命令的第m个参数
command !n:*   # 调用第n条命令的所有参数
command !string:^    # 从命令历史中搜索以string 开头的命令,并获取它的第一个参数
command !string:$    # 从命令历史中搜索以string 开头的命令,并获取它的最后一个参数
command !string:n    # 从命令历史中搜索以string 开头的命令,并获取它的第n个参数
command !string:*    # 从命令历史中搜索以string 开头的命令,并获取它的所有参数

history 帮助

history [-c] [-d offset] [n]
history -anrw [filename]
history -psarg [arg...]
-c: 清空命令历史
-d offset: 删除历史中指定的第offset个命令
n: 显示最近的n条历史
-a: 追加本次会话新执行的命令历史列表至历史文件
-r: 读历史文件附加到历史列表
-w: 保存历史列表到指定的历史文件
-n: 读历史文件中未读过的行到历史列表
-p: 展开历史参数成多行,但不存在历史列表中
-s: 展开历史参数成一行,附加在历史列表后

相关的环境变量

HISTSIZE:命令历史记录的条数
HISTFILE:指定历史文件,默认为~/.bash_history
HISTFILESIZE:命令历史文件记录历史的条数
HISTTIMEFORMAT="%F %T " 显示时间
HISTIGNORE="str1:str2*:… " 忽略str1命令,str2开头的历史

控制命令历史的记录方式:

环境变量:HISTCONTROL
ignoredups    默认,忽略重复的命令,连续且相同为“重复”
ignorespace    忽略所有以空白开头的命令
ignoreboth    相当于ignoredups, ignorespace的组合
erasedups    删除重复命令
export 变量名="值“
存放在/etc/profile 或~/.bash_profile

passwd 设置更改用户口令

语法

Usage: passwd [OPTION...] <accountName> 修改指定用户的密码,仅root用户权限
       passwd: 修改自己的密码
  -k, --keep-tokens       keep non-expired authentication tokens
  -d, --delete            delete the password for the named account (root only)
  -l, --lock              lock the password for the named account (root only)锁定指定用户
  -u, --unlock            unlock the password for the named account (root only)解锁指定用户
  -e, --expire            expire the password for the named account (root only)强制用户下次登录修改密码
  -f, --force             force operation
  -x, --maximum=DAYS      maximum password lifetime (root only)最大使用期限
  -n, --minimum=DAYS      minimum password lifetime (root only)指定最短使用期限
  -w, --warning=DAYS      number of days warning users receives before password expiration (root only)提前多少天开始警告
  -i, --inactive=DAYS     number of days after password expiration when an account becomes disabled (root only)非活动期限
  -S, --status            report password status on the named account (root only)
  --stdin                 read new tokens from stdin (root only)从标准输入接收用户密码

Help options:
  -?, --help              Show this help message
  --usage                 Display brief usage message

命令示例

echo your_password | passwd --stdin user_name     非交互修改口令
passwd -e user_name      使口令及时失效 同 chage -d 0 user_name

口令及时过期演示

[root@centos6 ~]#passwd -e ming
Expiring password for user ming.
passwd: Success
[root@centos6 ~]#

更改后
[root@centos6 ~]#getent shadow ming
ming:$6$FWNaz5q4$C5tswES6V3urxvObtSPNOnHVbVm8/I2itoXPFRP/WmG3Noqpmk4UyAQsAV5emKEF.SGWQc3ZlBX/fQh3b.y7P1:0:3:30:7:::

输入图片说明

登录后就会提示马上更改口令

输入图片说明


getent 查看用户信息配置文件

使用cat查看配置文件 /etc/passwd /etc/shadow /etc/group /etc/gshadow 但是查看的所有的用户以及组的信息
我们可以用 getent 命令查看指定用户和组的信息

命令示例

getent passwd root
getent passwd ming

getent shadow root
getent shadow ming

getent group  root
getent group  ming

getent gshadow root
getent gshadow ming

命令演示

[root@centos6 ~]$getent passwd ming
ming:x:500:500::/home/ming:/bin/bash
[root@centos6 ~]$getent passwd root
root:x:0:0:root:/root:/bin/bash
[root@centos6 ~]$
[root@centos6 app]$getent shadow root
root:$6$9FCrfWe.KlL3nFxg$HYX/Fm3jOTmw7YMHrcqAT4vT0nCtBMKmCf7Fqbxi5lp7Lkkz.4eU7/umHLUCBuK5WoXY/fq.OvvJ1H0ftOXjp0:17843:0:99999:7:::
[root@centos6 app]$getent shadow ming
ming:$6$dYa0fuUeOjo/7dLr$wjpGXLBjqeaD0IMclF4LIQyGS9JRAIQAmTKz.J1eID5OpWaHrlAmkr7UICDHJTApFmsafFL0Mt2.fk/OYys4I.:17843:0:99999:7:::
[root@centos6 app]$
[root@centos6 app]$getent group  root
root:x:0:
[root@centos6 app]$getent group  ming
ming:x:500:
[root@centos6 app]$
[root@centos6 app]$getent gshadow root
root:::
[root@centos6 app]$getent gshadow ming
ming:!!::
[root@centos6 app]$

pwd 打印当前工作目录名称(内置命令)

语法

pwd: pwd [-LP]
    
Options:
    -L        print the value of $PWD if it names the current working directory
    -P        print the physical directory, without any symbolic links 显示真实路径而不是链接文件的路径
    
  By default, `pwd' behaves as if `-L' were specified.
    
  Exit Status:
  Returns 0 unless an invalid option is given or the current directory cannot be read

对应的系统变量是 $PWD

echo $PWD

演示

[root@centos6 ~]#echo $PWD
/root
[root@centos6 ~]#ls -l /tmp/
total 84
lrwxrwxrwx. 1 root root    22 Nov 22 06:15 dir_link -> ../app/dir1/dir2/dir3/
[root@centos6 ~]#cd /tmp/dir_link/
[root@centos6 dir_link]#
[root@centos6 dir_link]#pwd
/tmp/dir_link
[root@centos6 dir_link]#
[root@centos6 dir_link]#pwd -P
/app/dir1/dir2/dir3
[root@centos6 dir_link]#

basename 显示文件的基名

语法

SYNOPSIS
       basename NAME [SUFFIX]
       basename OPTION

EXAMPLES
       basename /usr/bin/sort
              Output "sort".

       basename include/stdio.h .h
              Output "stdio".

演示

[root@centos6 test]#basename dosometing.sh 
dosometing.sh
[root@centos6 test]#basename dosometing.sh .sh
dosometing

dirname 返回文件路径的路径名称

语法

SYNOPSIS
       dirname NAME
       dirname OPTION

DESCRIPTION
       Print NAME with its trailing /component removed; if NAME contains no /’s, output ‘.’ (meaning the current directory).

       --help display this help and exit

       --version
              output version information and exit

EXAMPLES
       dirname /usr/bin/sort
              Output "/usr/bin".

       dirname stdio.h
              Output ".".

演示

[root@centos6 test]#dirname /test/dosometing.sh
/test

ls 列出当前目录的内容或指定目录

语法

ls [options] [files_or_dirs]        

ls -a   包含隐藏文件
ls -A   不包含隐藏文件
ls -l   显示额外的信息
ls -R   目录递归通过
ls -ld  目录和符号链接信息
ls -1   文件分行显示(竖着显示)
ls –S   按从大到小排序
ls –t   按mtime排序
ls –u   配合 -t 选项,显示并按atime从新到旧排序
ls –c   配合 -t 选项,显示并按ctime从新到旧排序
ls –U   按目录存放顺序显示(文件生成的顺序)
ls –X   按文件后缀排序
ls -l --time=ctime  显示文件的元数据时间
ls -l --time=status 同 ls -l --time=ctime
ls -l --time=atime  显示文件的访问时间
ls -l --time=mtime  显示文件的修改时间
-I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
ls -a --ignore=[^.]*
ls -a -I "[^.]*"

I"[^.]*" 之间不能有东西
l.ls -d .* 只支持当前目录, ls -a -I "[^.]*"ls -a -I "[^.]*" 支持任意目录

[root@centos6 ~]$ls -a --ignore=[^.]*
.              .bashrc    .gconf          .gvfs            .pulse
..             .cache     .gconfd         .ICEauthority    .pulse-cookie
.abrt          .config    .gnome2         .imsettings.log  .ssh
.bash_history  .cshrc     .gnote          .lesshst         .tcshrc
.bash_logout   .dbus      .gnupg          .local           .viminfo
.bash_profile  .esd_auth  .gtk-bookmarks  .nautilus
[root@centos6 ~]$
[root@centos6 ~]$ls -a -I "[^.]*"
.              .bashrc    .gconf          .gvfs            .pulse
..             .cache     .gconfd         .ICEauthority    .pulse-cookie
.abrt          .config    .gnome2         .imsettings.log  .ssh
.bash_history  .cshrc     .gnote          .lesshst         .tcshrc
.bash_logout   .dbus      .gnupg          .local           .viminfo
.bash_profile  .esd_auth  .gtk-bookmarks  .nautilus
[root@centos6 ~]$

示例

[root@centos6 ~]$ls -l /etc/hosts
-rw-r--r--. 1 root root 158 Jan 12  2010 /etc/hosts
[root@centos6 ~]$ls -l --time=ctime  /etc/hosts
-rw-r--r--. 1 root root 158 Nov  9 07:05 /etc/hosts
[root@centos6 ~]$ls -l --time=status  /etc/hosts
-rw-r--r--. 1 root root 158 Nov  9 07:05 /etc/hosts
[root@centos6 ~]$
[root@centos6 ~]$ls -l --time=atime  /etc/hosts
-rw-r--r--. 1 root root 158 Nov 13 22:03 /etc/hosts
[root@centos6 ~]$

仅仅显示目录

-d*/ 配合

[root@centos6 ~]$ls -d */
1/  Desktop/  Documents/  Downloads/  Music/  Pictures/  Public/  Templates/  Videos/
[root@centos6 ~]$ls -d ./*/
./1/  ./Desktop/  ./Documents/  ./Downloads/  ./Music/  ./Pictures/  ./Public/  ./Templates/  ./Videos/

stat 查看文件元数据

命令帮助

Usage: stat [OPTION]... FILE...
Display file or file system status.

  -L, --dereference     follow links
  -Z, --context         print the SELinux security context 
  -f, --file-system     display file system status instead of file status
  -c  --format=FORMAT   use the specified FORMAT instead of the default;
                          output a newline after each use of FORMAT
      --printf=FORMAT   like --format, but interpret backslash escapes,
                          and do not output a mandatory trailing newline.
                          If you want a newline, include \n in FORMAT.
  -t, --terse           print the information in terse form
      --help     display this help and exit
      --version  output version information and exit

The valid format sequences for files (without --file-system):

  %a   Access rights in octal
  %A   Access rights in human readable form
  %b   Number of blocks allocated (see %B)
  %B   The size in bytes of each block reported by %b
  %C   SELinux security context string
  %d   Device number in decimal
  %D   Device number in hex
  %f   Raw mode in hex
  %F   File type
  %g   Group ID of owner
  %G   Group name of owner
  %h   Number of hard links
  %i   Inode number
  %n   File name
  %N   Quoted file name with dereference if symbolic link
  %o   I/O block size
  %s   Total size, in bytes
  %t   Major device type in hex
  %T   Minor device type in hex
  %u   User ID of owner
  %U   User name of owner
  %x   Time of last access
  %X   Time of last access as seconds since Epoch
  %y   Time of last modification
  %Y   Time of last modification as seconds since Epoch
  %z   Time of last change
  %Z   Time of last change as seconds since Epoch

Valid format sequences for file systems:

  %a   Free blocks available to non-superuser
  %b   Total data blocks in file system
  %c   Total file nodes in file system
  %d   Free file nodes in file system
  %f   Free blocks in file system
  %C   SELinux security context string
  %i   File System ID in hex
  %l   Maximum length of filenames
  %n   File name
  %s   Block size (for faster transfers)
  %S   Fundamental block size (for block counts)
  %t   Type in hex
  %T   Type in human readable form

NOTE: your shell may have its own version of stat, which usually supersedes
the version described here.  Please refer to your shell's documentation
for details about the options it supports.

Report stat bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'stat invocation'

文件数据分为两种:metadata, data

三个时间戳

  • access time:访问时间,atime,读取文件内容
  • modify time: 修改时间, mtime,改变文件内容(数据)
  • change time: 改变时间, ctime,元数据发生改变

示例

[root@centos6 ~]$stat /etc/hosts
  File: `/etc/hosts'
  Size: 158         Blocks: 8          IO Block: 4096   regular file
Device: 802h/2050d  Inode: 2490400     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2018-11-13 22:03:52.045107766 +0800
Modify: 2010-01-12 21:28:22.000000000 +0800
Change: 2018-11-09 07:05:44.217999104 +0800
[root@centos6 ~]$

直接查看文件的权限

stat -c %A  f1     # 以模式方式显示权限
stat -c %a  f1     # 以数字方式显示权限
[root@centos6 app]#stat -c %A  f1
-rw-r--r--
[root@centos6 app]#stat -c %a  f1
644
[root@centos6 app]#

关于 atime 的更新

按照atime的概念,每一次访问文件后,atime都会变化,这样就会只有磁盘的次额操作(元数据变换也是要记录到磁盘上的),
但是频繁的访问一个文件,势必会造成频繁的 atime 变化,造成磁盘IO,降低系统性能。默认centos6系统之后启用了 relatime 选项。只有atime 时间超过一天或者 mtime 的时间新于 atime,这时候 atime 才会更新。

查看 relatime

[root@centos7 ~]$mount | tail -1
-hosts on /net type autofs (rw,relatime,fd=13,pgrp=42869,timeout=300,minproto=5,maxproto=5,indirect,pipe_ino=521933)

屏蔽 relatime 实现系统性能的提升

通过 chattr +A 屏蔽 relatime 实现系统性能的提升(有人测试过可以提高 5%)

chattr +A file_name
chattr -A file_name

cat 文本文件查看

语法

cat [OPTION]... [FILE]...

    -E:  显示行结束符 $
    -n:  对显示出的每一行进行编号(空行也加行号)
    -A:  显示所有控制符
    -b:  非空行编号(空行不加行号)
    -s:  压缩连续的空行成一行

tac倒序查看文件(将行倒序):tac

[root@centos6 app]#cat test 
aaa
bbb
ccc
[root@centos6 app]#tac test    
ccc
bbb
aaa
[root@centos6 app]#

rev 反向输出字符串(将列倒序)

[root@centos6 app]#cat test       
123
abc
[root@centos6 app]#rev test         
321
cba
[root@centos6 app]#
[root@centos6 app]#echo 1234 | rev
4321

more 分页查看文件内容

语法

more [OPTIONS...] FILE...
-d: 显示翻页及退出提示

less:一页一页地查看文件或STDIN输出

查看时有用的命令包括:
/文本搜索文本
n/N跳到下一个或上一个匹配
less命令是man命令使用的分页器

head 输出文件的前部信息

语法

SYNOPSIS
       head [OPTION]... [FILE]...
DESCRIPTION
       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=[-]K  
    打印文件的前 K个字节,如果前面使用 "-" 就是打印除了最后K个字节的所有内容。
-n, --lines=[-]K
    打印文件的前 K行内容,默认是前10行,使用"-" 就是打印除了最后K行的所有行。
-q, --quiet, --silent
    不打印文件名作为头部(默认选项)
-v, --verbose
    打印文件名作为头部
--help display this help and exit
    显示帮助信息
--version
    显示head的版本信息

演示

[root@centos7-scm data]#head -2 -q f1    
1
2
[root@centos7-scm data]#head -2 -v f1
==> f1 <==
1
2
[root@centos6 ~]#echo 速度哦上的 | head -c 1
3m[root@centos6 ~]#echo 速度哦上的 | head -c 2
33m[root@centos6 ~]#echo 速度哦上的 | head -c 3
速[root@centos6 ~]#echo 速度哦上的 | head -c 4
速3m[root@centos6 ~]#echo 速度哦上的 | head -c 5
速33m[root@centos6 ~]#echo 速度哦上的 | head -c 6
速度[root@centos6 ~]#
[root@centos6 ~]#echo abcdef | head -c 6            
abcdef[root@centos6 ~]#echo abcdef | head -c 1
a[root@centos6 ~]#echo abcdef | head -c 2
ab[root@centos6 ~]#echo abcdef | head -c 3
abc[root@centos6 ~]#
[root@centos6 app]#openssl rand -base64 30| head -c 30
OFIe7D0dT9WQos2NMTk9k+VFVgxFwj[root@centos6 app]#
[root@centos6 app]#cat /dev/urandom | tr -dc '[:alnum:]'| head -c 30
rLT7fSpUlsYwY9CLtoTEtWFvYxfAVY[root@centos6 app]#
[root@centos6 app]#tr -dc '[:alnum:]' < /dev/urandom| head -c 30
NCMutboEiMXjq6eHHZsxDg8rY7iI46[root@centos6 app]#

tail 输出文件的结尾部分

语法

SYNOPSIS
       tail [OPTION]... [FILE]...

DESCRIPTION
       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=K
    输出文件中最后的 K 字节,使用-c +K 输出每个文件第 K 字节以及之后的内容。
-f, --follow[={name|descriptor}]
    文件增长时,输出追加到文件中的数据,-f, --follow, and --follow=descriptor 是以一样的
-F
    同 --follow=name 或 --retry, 跟踪文件名字(文件删除后,还可以实现跟踪)
--retry
    当文件不存在的时候,始终尝试打开文件,配合 --follow=name 使用。
-n, --lines=K
    输出最后的 K行,使用 -n +K 表示输出从第 K 行以及之后的行
--pid=PID
    配合 -f 使用,进程ID或PID死掉后停止使用。
-q, --quiet, --silent
    不输出文件名(默认选项)
-s, --sleep-interval=N
    配置 -f 使用,指定输出的时间间隔(默认是1秒)。
-v, --verbose
    始终出文件名
--help
    输出帮助信息
--version
    输出版本信息

命令示例

tail -f /var/log/messages
tail --follow /var/log/secure
tail --follow=name /var/log/messages
tail --follow=descriptor /var/log/messages

tail -f -v /var/log/messages
tail -f -q /var/log/messages

演示

[root@centos6 app]#tail -f -v /var/log/messages
==> /var/log/messages <==
Dec 26 08:56:54 centos6 kernel: device eth0 left promiscuous mode
Dec 26 09:41:21 centos6 kernel: hrtimer: interrupt took 3716021 ns
[root@centos6 app]#tail -f -q /var/log/messages
Dec 26 08:56:54 centos6 kernel: device eth0 left promiscuous mode
Dec 26 09:41:21 centos6 kernel: hrtimer: interrupt took 3716021 ns

实现只看最后一行,并且不影响前台执行其他命令,有些内容就显示出来

tail -f -n0 filename &

tailf 跟踪日志文件的增量内容

语法

SYNOPSIS
       tailf [OPTION] file

DESCRIPTION
       tailf 将打印文件的最后的10行,并等待文件增长,很像 tail -f的效果,但是文件不增长的时候是不会访问文件的。
       所以它不会更新文件的访问时间,从而当日志文件没有发生变化的时候,不会有频繁的文件系统的刷新,减少磁盘的IO。

-n, --lines N, -N   # 输出最后的N行,默认是10行。

仅支持一个文件


按列抽取文本cut

cut 语法

cut [OPTION]... [FILE]...
    -d DELIMITER: 指明分隔符,默认tab
    -f FILEDS:
    #: 第#个字段
    #,#[,#]:离散的多个字段,例如1,3,6
    #-#:连续的多个字段, 例如1-6
    混合使用:1-3,7

    -b, --bytes=LIST   按字节切割
    -c, --characters=LIST  按字符切割
    --output-delimiter=STRING指定输出分隔符

命令汇总:显示文件或STDIN数据的指定列

cut -d: -f1 /etc/passwd
cat /etc/passwd|cut -d: -f7
cut -c 2-5 /usr/share/dict/words
cut -d: --output-delimiter='***' -f 1-3,7 /etc/passwd

echo abcdefg | cut -b 3
echo abcdefg | cut -b 1,3
echo abcdefg | cut -b 2-5
echo abcdefg | cut--bytes=1
echo abcdefg | cut--bytes1
echo abcdefg | cut--bytes=1,2
echo abcdefg | cut--bytes 1,2
echo abcdefg | cut --bytes=2-5
echo abcdefg | cut --bytes 2-5

echo abcdefg | cut --characters=1,2
echo abcdefg | cut --characters 1,2
echo abcdefg | cut --characters=3-5
echo abcdefg | cut --characters 3-5

echo 飞流直下三千尺 | cut --characters=3
echo 飞流直下三千尺 | cut --characters 3
echo 飞流直下三千尺 | cut --characters=1,2
echo 飞流直下三千尺 | cut --characters 1,2
echo 飞流直下三千尺 | cut --characters=2-5
echo 飞流直下三千尺 | cut --characters 2-5

ifconfig eth0| grep -w 'inet addr'| tr -s ' ' : | cut -d: -f4        # centos6
ifconfig ens33 | grep -w 'inet' | tr -s ' ' | cut -d' ' -f 3         # centos7

cut 配合 tr -s 示例

cut 只能指定单独的分隔符,所以遇到连续的分隔符还要配合 tr -s <分隔符> 将连续的分隔符压缩成单个的分隔符再用cut指定

取IP

[root@centos6 ~]#ss -an | tail -2
ESTAB      0      96             192.168.27.6:22            192.168.27.2:57211 
ESTAB      0      0              192.168.27.6:22            192.168.27.2:51361 
[root@centos6 ~]#ss -an | tail -2 | tr -s ' ' | cut -d ' ' -f 5| cut -d: -f1
192.168.27.2
192.168.27.2
[root@centos6 ~]#
[root@centos6 ~]#ss -an| tail -1 |tr -s  ' ' : | cut -d : -f 6
192.168.27.2
[root@centos6 ~]#ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:0C:29:C7:4C:8A  
          inet addr:192.168.27.6  Bcast:192.168.27.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fec7:4c8a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6174 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4025 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:700847 (684.4 KiB)  TX bytes:896700 (875.6 KiB)

[root@centos6 ~]#ifconfig eth0| grep 'inet addr'| tr -s ' ' : | cut -d: -f4
192.168.27.6
[root@centos6 ~]#
[root@centos7 ~]#ifconfig ens33 | awk -F"[ ]+" 'NR==2{print $3}'
192.168.27.7

取磁盘利用率

[root@centos6 ~]#df
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda2       50264772 4411140  43293632  10% /
tmpfs             953652      72    953580   1% /dev/shm
/dev/sda3       20027260   44980  18958280   1% /app
/dev/sda1         999320   38824    908068   5% /boot
[root@centos6 ~]#df | grep /dev/sd | tr -s ' ' % | cut -d% -f 5
10
1
5
[root@centos6 ~]#

-b, --bytes=LIST 参数示例

[root@centos7-scm ~]#echo abcdefg | cut -b 1
a
[root@centos7-scm ~]#echo abcdefg | cut -b 2
b
[root@centos7-scm ~]#echo abcdefg | cut -b 3
c
[root@centos7-scm ~]#echo abcdefg | cut -b 1,3
ac
[root@centos7-scm ~]#echo abcdefg | cut -b 1,3,6
acf
[root@centos7-scm ~]#echo abcdefg | cut -b 1-3
abc
[root@centos7-scm ~]#
[root@centos7-scm ~]#echo abcdefg | cut -b 2-5
bcde
[root@centos7-scm ~]#echo abcdefg | cut --bytes=1,3,5
ace
[root@centos7-scm ~]#echo abcdefg | cut --bytes=2-5  
bcde

-c, --characters=LIST 参数示例

[root@centos7-scm ~]#echo abcdefg | cut --characters=1,2
ab
[root@centos7-scm ~]#echo abcdefg | cut --characters=3-5
cde
[root@centos7-scm ~]#echo abcdefg | cut --characters 3-5
cde
[root@centos7-scm ~]#echo abcdefg | cut --characters 1,2
ab
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters=3
直
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters 3
直
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters=1,2
飞流
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters 1,2
飞流
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters=2-5
流直下三
[root@centos7-scm ~]#echo 飞流直下三千尺 | cut --characters 2-5
流直下三

paste 合并两个文件同行号的列到一行

提示:
如果仅仅是将两个文件追加合并,使用 cat 命令就可以实现,cat可以实现行的合并
paste 实现的是针对列的合并

语法

paste [OPTION]... [FILE]...
    -d     分隔符:指定分隔符(单个分隔符),默认用TAB
    -s     所有行合成一行显示(类似于excel中的转置粘贴)
paste f1 f2
paste -d '=' f1 f2
paste -s f1 f2

演示数据

[root@centos6 app]#cat  f1
1
2
3
4
[root@centos6 app]#cat  f2
a
b
c
d
[root@centos6 app]#

命令用法演示

[root@centos6 app]#paste f1 f2
1       a
2       b
3       c
4       d
[root@centos6 app]#paste -d= f1 f2
1=a
2=b
3=c
4=d
[root@centos6 app]#paste -s f1
1       2       3       4

[root@centos6 app]#paste -s f1 f2
1       2       3       4
a       b       c       d
[root@centos6 app]#

收集文本统计数据wc

常用选项

  -l    只计数行数
  -w    只计数单词总数
  -c    只计数字节总数
  -m    只计数字符总数
  -L    显示文件中最长行的长度
  • 计数单词总数、行总数、字节总数和字符总数
  • 可以对文件或STDIN中的数据运行

    演示

wc   story.txt
39    23    71901    story.txt
行数  字数  字节数

文本排序sort

  • 把整理过的文本显示在STDOUT,不改变原始文件
  • 默认是按字符顺序排序的
sort [options] file(s)

常用选项

  -r    执行反方向(由上至下)整理
  -n    执行按数字大小整理
  -f    选项忽略(fold)字符串中的字符大小写
  -u    选项(独特,unique)删除输出中的重复行
  -t c  选项使用c做为字段界定符
  -k X  选项按照使用c字符分隔的X列来整理能够使用多次

/etc/passwd 中的 username,UID 列,按 UID 从大到小排列

[root@centos6 app]#cut -d: -f1,3 /etc/passwd | sort -nr -t: -k2
nfsnobody:65534
tom:503
alice:502
scm:501
ming:500
rtkit:499
saslauth:498
pulse:497
abrt:173
avahi-autoipd:170
usbmuxd:113
nobody:99
postfix:89
dbus:81
sshd:74
tcpdump:72
vcsa:69
haldaemon:68
apache:48
gdm:42
ntp:38
rpc:32
rpcuser:29
mysql:27
ftp:14
gopher:13
games:12
operator:11
uucp:10
mail:8
halt:7
shutdown:6
sync:5
lp:4
adm:3
daemon:2
bin:1
root:0

去重 uniq

uniq命令:从输入中删除前后相接的重复的行

语法

uniq [OPTION]... [FILE]...
    -c: 显示每行重复出现的次数
    -d: 仅显示重复过的行
    -u: 仅显示不曾重复的行
    连续且完全相同方为重复

演示

常和sort 命令一起配合使用:

sort userlist.txt | uniq -c
cut -d ' ' -f 1  access_log| sort | uniq -c | sort -nr -t" " -k1 | head -10
[root@centos6 app]#cut -d ' ' -f 1  access_log| sort | uniq -c | sort -nr -t" " -k1
 159091 172.18.56.3
   3981 192.168.27.6
     24 172.18.0.100
      5 192.168.27.66
      3 192.168.27.4
      3 192.168.27.36
      2 192.168.27.62
      2 192.168.27.55
      2 192.168.27.46
      1 192.168.27.9
      1 192.168.27.82
      1 192.168.27.68
      1 192.168.27.67
      1 192.168.27.63
      1 192.168.27.35
      1 192.168.27.116
[root@centos6 app]#cut -d ' ' -f 1  access_log| sort | uniq -c | sort -nr -t" " -k1 | head -10
 159091 172.18.56.3
   3981 192.168.27.6
     24 172.18.0.100
      5 192.168.27.66
      3 192.168.27.4
      3 192.168.27.36
      2 192.168.27.62
      2 192.168.27.55
      2 192.168.27.46
      1 192.168.27.9
[root@centos6 app]#

diff 比较文件

比较两个文件之间的区别

演示

diff foo.conf foo2.conf
5c5
< use_widgets=no
---
> use_widgets=yes

注明第5行有区别(改变)

patch 复制对文件改变

  • diff 命令的输出被保存在一种叫做"补丁"的文件中

    • 使用 -u 选项来输出 "统一的(unified)" diff格式文件,最适用于补丁文件
  • patch 复制在其它文件中进行的改变(要谨慎使用)

    • 使用 -b 选项来自动备份改变了的文件
diff -u foo.conf foo2.conf > foo.patch
patch -b foo.conf foo.patch

演示

[root@centos6 app]#cat f3
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#cat f4
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#diff f3 f4
2c2
< ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
---
> 10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#
[root@centos6 app]#diff -u f3 f4 > f3_f4.diff
[root@centos6 app]#cat f3_f4.diff 
--- f3  2018-11-24 18:52:27.921991499 +0800
+++ f4  2018-11-24 18:53:22.698994732 +0800
@@ -1,2 +1,2 @@
 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
-::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
+10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#
[root@centos6 app]#rm -f f4
[root@centos6 app]#ls f4
ls: cannot access f4: No such file or directory
[root@centos6 app]#ls f3
f3
[root@centos6 app]#patch f3 f3_f4.diff  # 通过 f3 和 f3_f4.diff 恢复 f4
patching file f3
[root@centos6 app]#ls f3 f4
ls: cannot access f4: No such file or directory
f3
[root@centos6 app]#cat f3 # f4 内容已经恢复,但是名字是f3
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#

-b 备份演示

[root@centos6 app]#cat f3
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#cat f3_f4.diff 
--- f3  2018-11-24 18:52:27.921991499 +0800
+++ f4  2018-11-24 18:53:22.698994732 +0800
@@ -1,2 +1,2 @@
 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
-::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
+10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#
[root@centos6 app]#ls f4
ls: cannot access f4: No such file or directory
[root@centos6 app]#
[root@centos6 app]#patch -b f3 f3_f4.diff 
patching file f3
[root@centos6 app]#
[root@centos6 app]#ls f3
f3
[root@centos6 app]#ls f4
ls: cannot access f4: No such file or directory
[root@centos6 app]#ls f3.orig   # 备份的文件
f3.orig
[root@centos6 app]#
[root@centos6 app]#ls f3_f4.diff 
f3_f4.diff
[root@centos6 app]#
[root@centos6 app]#cat f3.orig # 备份的文件 f3
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#cat f3  # 恢复的文件 f4(名字是f3)
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
10.0.0.10   localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@centos6 app]#

练习

  • 1、找出ifconfig “网卡名”命令结果中本机的IPv4地址
ifconfig eth0| grep -w 'inet addr'| tr -s ' ' : | cut -d: -f4        # centos6
ifconfig ens33 | grep -w 'inet' | tr -s ' ' | cut -d' ' -f 3         # centos7
ifconfig eth0 | awk -F"[ :]+" 'NR==2{print $4}'         # centos6
ifconfig ens33 | awk -F"[ ]+" 'NR==2{print $3}'         # centos7
  • 2、查出分区空间使用率的最大百分比值
[root@centos6 app]#df | grep '/dev/sd' | tr -s ' ' %| cut -d% -f5
10
1
5
  • 3、查出用户UID最大值的用户名、UID及shell类型
[root@centos6 app]#cut -d: -f1,3,7 /etc/passwd | sort -nr -t: -k2 | head -1
nfsnobody:65534:/sbin/nologin
  • 4、查出/tmp的权限,以数字方式显示
[root@centos6 app]#stat -c %a /tmp/
1777
[root@centos6 app]#stat /tmp/ | grep -i uid | cut -d"(" -f 2| cut -d/ -f1
1777
  • 5、统计当前连接本机的每个远程主机IP的连接数,并按从大到小排序
[root@centos6 app]#ss -nt | grep -i estab| tr -s " " : | cut -d: -f6 | sort | uniq -c | sort -nr | head -10
      1 192.168.27.2

grep:文本过滤(模式:pattern)工具

grep, egrep, fgrep(不支持正则表达式搜索)
grep: Global search REgularexpression and Print out the line

作用:文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查;打印匹配到的行
模式:由正则表达式字符及文本字符所编写的过滤条件

语法

grep [OPTIONS] PATTERN [FILE...]
               PATTERN 就是要过滤的字符串后正则表达式

Options:
--color=auto: 对匹配到的文本着色显示
-v: 显示不被pattern匹配到的行
-i: 忽略字符大小写
-n:显示匹配的行号
-c: 统计匹配的行数
-o: 仅显示匹配到的字符串
-q: 静默模式,不输出任何信息
-A #: after, 后#行
-B #: before, 前#行
-C #:context, 前后各#行
-e:实现多个选项间的逻辑or关系
        grep –e 'cat' -e 'dog' file
-w:匹配整个单词(数字、字母、下划线 不能作为单词的分隔符)
-E:使用ERE
-F:相当于fgrep,不支持正则表达式

命令示例

grep root /etc/passwd
grep "$USER" /etc/passwd
grep '$USER' /etc/passwd
grep `whoami` /etc/passwd

正则表达式

  • REGEXP:由一类特殊字符及文本字符所编写的模式,其中有些字符(元字符)不表示字符字面意义,而表示控制或通配的功能
  • 程序支持:grep,sed,awk,vim, less,nginx,varnish等

  • 分两类:

    • 基本正则表达式:BRE
    • 扩展正则表达式:ERE grep -E, egrep
  • 正则表达式引擎:

    • 采用不同算法,检查处理正则表达式的软件模块
    • PCRE(Perl Compatible Regular Expressions)
  • 元字符分类:字符匹配、匹配次数、位置锚定、分组
  • man 7 regex

基本正则表达式元字符

  • 字符匹配:
. 匹配任意单个字符
[] 匹配指定范围内的任意单个字符
[^] 匹配指定范围外的任意单个字符
[:alnum:] 字母和数字
[:alpha:] 代表任何英文大小写字符,亦即A-Z, a-z
[:lower:] 小写字母[:upper:] 大写字母
[:blank:] 空白字符(空格和制表符)
[:space:] 水平和垂直的空白字符(比[:blank:]包含的范围广)
[:cntrl:] 不可打印的控制字符(退格、删除、警铃...)
[:digit:] 十进制数字[:xdigit:]十六进制数字
[:graph:] 可打印的非空白字符
[:print:] 可打印字符
[:punct:] 标点符号
  • 匹配次数:用在要指定次数的字符后面,用于指定前面的字符要出现的次数
*   匹配前面的字符任意次,包括0次
    贪婪模式:尽可能长的匹配
.*  任意长度的任意字符
\?  匹配其前面的字符0或1次
\+  匹配其前面的字符至少1次
\{n\}  匹配前面的字符n次
\{m,n\}  匹配前面的字符至少m次,至多n次
\{,n\}  匹配前面的字符至多n次
\{n,\}  匹配前面的字符至少n次
  • 位置锚定:定位出现的位置
^  行首锚定,用于模式的最左侧
$  行尾锚定,用于模式的最右侧
^PATTERN$  用于模式匹配整行
^$  空行
^[[:space:]]*$  空白行
\< 或\b  词首锚定,用于单词模式的左侧
\> 或\b  词尾锚定;用于单词模式的右侧
\<PATTERN\>  匹配整个单词
  • 分组:() 将一个或多个字符捆绑在一起,当作一个整体进行处理,如:(root)+
  • 分组括号中的模式匹配到的内容会被正则表达式引擎记录于内部的变量中,这些变量的命名方式为: \1, \2, \3, ...
  • \1表示从左侧起第一个左括号以及与之匹配右括号之间的模式所匹配到的字符
  • 示例:
\(string1\+\(string2\)*\)
\1 :string1\+\(string2\)*
\2 :string2
  • 后向引用:引用前面的分组括号中的模式所匹配字符,而非模式本身
  • 或者:|
#### 示例:
a\|b: a或b C\|cat: C或cat \(C\|c\)at: Cat或cat
元字符 定义
^ 行首
$ 行尾
. 任意单一字符
[] []内任意单一字符
[^] 除[]内任意单一字符
* *前面字符重复不确定次数
+ +前面字符重复一次以上不确定次数
? ?前面字符重复0或1次
\ 转义符
.* 任意长度字符
{n} 前面字符重复n次
{n,} 前面字符重复n次以上
{m,n} 前面字符重复m次和n次之间
[:alnum:] 字母和数字
[:alpha:] 代表任何英文大小写字符,亦即A-Z, a-z
[:lower:] 小写字母
[:upper:] 大写字母
[:blank:] 水平空白字符(空格和制表符)
[:space:] 所有水平和垂直的空白字符(比[:blank:]包含的范围广)
[:cntrl:] 不可打印的控制字符(退格、删除、警铃...)
[:digit:] 十进制数字
[:graph:] 可打印的非空白字符
[:print:] 可打印字符
[:punct:] 标点符号
[:xdigit:] 十六进制数字
grep "root" /etc/passwd
grep "r..t" /etc/passwd

grep "r[adfo][to]t" /etc/passwd
echo 'ratt' | grep r[adfo][to]t
echo 'rbtt' | grep r[^adfo][to]t


判断 centos6或centos7的主版本号
grep -o "[0-9]\{1,\}" /etc/centos-release
grep -o "[0-9]\{1,\}" /etc/centos-release| head -1
grep -o "[0-9]\+" /etc/centos-release
grep -o "[0-9]\+" /etc/centos-release| head -1
grep -o "[[:digit:]]\+" /etc/centos-release
grep -o "[[:digit:]]\+" /etc/centos-release| head -1
egrep -o "[0-9]+" /etc/centos-release
egrep -o "[0-9]+" /etc/centos-release | head -1
egrep -o "[[:digit:]]+" /etc/centos-release
egrep -o "[[:digit:]]+" /etc/centos-release | head -1

echo "a" | grep "a*"
echo "ab" | grep "a*"
echo "abb" | grep "a*"

在centos7上 grep 好像有些bug:centos6上没有出现问题,建议加上引号
ls | grep a* 可能会将 ls 的结果作为 grep 操作的文件名(当成通配符了),在这些文件中依次去找带有 a 的行 (不进入目录中)
所以在使用正则表达的时候建议加上引号 ls | grep "a*" ,这样就会将 ls的结果作为字符串

grep ro*t /etc/passwd
grep r.* /etc/passwd

echo "a" | grep "ab\?"
echo "ab" | grep "ab\?"
echo "abb" | grep "ab\?"
echo "abbb" | grep "ab\?"
echo 'aaaababbbbb' | grep 'ab\?'
echo 'b' | grep 'a\?'
echo 'ab' | grep 'b\+'
echo 'abbbbc' | grep 'b\{4\}'
echo 'abbbbc' | egrep 'b{4}'   
echo 'abbbbc' | grep -E 'b{4}'  

echo 'abbxx' | grep 'b\{3,5\}'  
echo 'abbbxx' | grep 'b\{3,5\}' 
echo 'abbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbbbbbxx' | grep 'b\{3,5\}'
echo 'abbbbbbbbbbbxx' | grep 'b\{3,5\}'


[root@centos6 app]#cat google.txt 
google
goooooooooooooooooogle
gogle
ggle
gooooooogle
goooooo00000gle

grep  google  google.txt
grep  go\?gle  google.txt
grep  "go\?gle"  google.txt
grep  "google"  google.txt
grep  "go\?gle"  google.txt

grep  "go\{2,\}gle"  google.txt  # 2 个 o 以上
grep  "gooo*gle"  google.txt     # 2 个 o 以上


行位置锚定
grep "^root" /etc/passwd    # 行首
grep "bash$" /etc/passwd    # 行尾

grep -v "^$" google.txt     # 显示非空行
grep -v "^[[:space:]]*$" google.txt     # 显示非空行或非空白行(这种一般比上面的方法更保险)

单词位置锚定
grep "\<f" google.txt
grep "\bf" google.txt
grep "f\>" google.txt
grep "f\b" google.txt

不建议使用 \b,以防止下面的歧义 
grep "f\bf" google.txt   # 不知道是词首还是词尾


\<PATTERN\>  匹配整个单词,相当于 -w
grep "\<f.*\>" google.txt
grep "\bf.*\b" google.txt

获取函数名
grep -o "^[[:alnum:]_]*[[:space:]]*()" /etc/init.d/functions
grep "^[^[:space:]].*{$" /etc/init.d/functions | tr -d '{'
grep -o "^[^[:space:]][[:alpha:]_]*[[:alpha:]_[:digit:][:space:]]*()" /etc/init.d/functions

grep -o "^[[:alnum:]_]\+[[:space:]]*()" /etc/init.d/functions | wc -l
grep "^[^[:space:]].*{$" /etc/init.d/functions | tr -d '{' | wc -l
grep -o "^[^[:space:]][[:alpha:]_]*[[:alpha:]_[:digit:][:space:]]*()" /etc/init.d/functions| wc -l


分组
echo "axx bxx cxx" | grep "\(a\|b\|c\)xx"
echo "rootrootroot" | grep "\(root\)\{2\}"
echo "rootrootroot" | grep "\(root\)\{2,\}"

分组+后向引用
echo "abcd abcd"|grep "\(a..d\).*\1"    # 有结果
echo "abcd abfd"|grep "\(a..d\).*\1"    # 无结果 \(a..d\) 匹配到以后就固定字符串了,后面的 \1就是引用前面固定的字符串。

练习

  • 1、显示/proc/meminfo文件中以大小s开头的行(要求:使用两种方法)
grep "^\(S\|s\)" /proc/meminfo
grep "\(^S.*\|^s\)" /proc/meminfo 
grep -i "^s" /proc/meminfo 
grep "^[Ss]" /proc/meminfo 
  • 2、显示/etc/passwd文件中不以/bin/bash结尾的行
grep -v "/bin/bash$" /etc/passwd
  • 3、显示用户rpc默认的shell程序
grep -w "^rpc" /etc/passwd | cut -d: -f7
grep "^rpc\>" /etc/passwd | cut -d: -f7
  • 4、找出/etc/passwd中的两位或三位数
grep -wo "[0-9]\{2,3\}" /etc/passwd
grep -o "\<[[:digit:]]\{2,3\}\>" /etc/passwd
  • 5、显示CentOS7的/etc/grub2.cfg文件中,至少以一个空白字符开头的且后面存非空白字符的行
grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg
grep "^[[:space:]]\+[^[:space:]]*$" /etc/grub2.cfg
  • 6、找出"netstat -tan"命令的结果中以"LISTEN"后跟任意多个空白字符结尾的行
netstat -tan | grep "LISTEN[[:space:]]*$"
  • 7、显示CentOS7上所有系统用户的用户名和UID
cut -d: -f1,3  /etc/passwd | grep -w "[0-9]\{1,3\}$"
cut -d: -f1,3  /etc/passwd | grep  "\<[0-9]\{1,3\}\>$"
cut -d: -f1,3  /etc/passwd | grep  "\<[0-9]\{1,3\}$"
cut -d: -f1,3  /etc/passwd | grep -w "[[:digit:]]\{1,3\}$"
cut -d: -f1,3  /etc/passwd | grep  "\<[[:digit:]]\{1,3\}\>$"
cut -d: -f1,3  /etc/passwd | grep  "\<[[:digit:]]\{1,3\}$"

grep -w "[0-9]\{1,3\}" /etc/passwd | cut -d: -f1,3     # 有问题,当新建用户 123 的时候
grep  "\<[0-9]\{1,3\}\>" /etc/passwd | cut -d: -f1,3    # 有问题,当新建用户 123 的时候
grep -w "[[:digit:]]\{1,3\}" /etc/passwd | cut -d: -f1,3   # 有问题,当新建用户 123 的时候
  • 8、添加用户bash、testbash、basher、sh、nologin(其shell为/sbin/nologin),找出/etc/passwd用户名同shell名的行(后向引用的用法)
useradd bash;useradd testbash;useradd basher;useradd sh;useradd nologin -s /sbin/nologin
grep  "^\(.*\):.*\<\1$" /etc/passwd   # 注意锚定词首
grep  "\<\(.*\)\>.*\<\1$" /etc/passwd   # 注意锚定词首词尾
grep  "^\(.*\):.*/\1$" /etc/passwd 
  • 9、利用df和grep,取出磁盘各分区利用率,并从大到小排序
df | grep "/dev/sd" | tr -s " " % | cut -d% -f5 | sort -nr
df | grep "/dev/sd" | grep -o "[0-9]\{1,\}%" | grep -o "[0-9]*"  | sort -nr

-10、匹配 ficonfig 输出的IP地址

ifconfig eth0| grep -ow  "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
ifconfig eth0| grep -o "\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}"

egrep及扩展的正则表达式

扩展的正则表达式和基本正则表达式的区别就是少了烦人的转义字符  ,支持的元字符以及功能上一样。
由于不同的命令支持的正则表达式不同,所以我们对两种正则表达式都要掌握。

  • egrep= grep -E
egrep [OPTIONS] PATTERN [FILE...]

扩展正则表达式的元字符:

  • 字符匹配:
. 任意单个字符
[] 指定范围的字符
[^] 不在指定范围的字符

次数匹配:

*:匹配前面字符任意次
?: 0或1次
+:1次或多次
{m}:匹配m次
{m,n}:至少m,至多n次

位置锚定:

^ :行首
$ :行尾
\<, \b :语首
\>, \b :语尾

分组:

()
后向引用:\1, \2, ...

或者:

a|b: a或b
C|cat: C或cat
(C|c)at: Cat或cat

练习

  • 1、显示三个用户root、mage、wang的UID和默认shell
egrep "^(root|wang|mage)"  /etc/passwd | cut -d: -f1,3,7
  • 2、找出/etc/rc.d/init.d/functions文件中行首为某单词(包括下划线)后面跟一个小括号的行
egrep -o "^([[:alpha:]_]*)\(\)" /etc/rc.d/init.d/functions
  • 3、使用egrep取出/etc/rc.d/init.d/functions中其基名
echo "/etc/rc.d/init.d/functions"  | egrep -o "\<[^/]+/?$" | egrep -o ".*[^/]"
echo "/etc/rc.d/init.d/functions/"  | egrep -o "\<[^/]+/?$" | egrep -o ".*[^/]"
[root@centos6 app]#echo "/etc/rc.d/init.d/functions/" | egrep -o "\<[^/]+/?$"  
functions/
[root@centos6 app]#echo "/etc/rc.d/init.d/functions" | egrep -o "\<[^/]+/?$" 
functions
[root@centos6 app]#echo "/etc/rc.d/" | egrep -o "\<[^/]+/?$"         
rc.d/
[root@centos6 app]#echo "/etc/rc.d" | egrep -o "\<[^/]+/?$" 
rc.d
[root@centos6 app]#echo "/etc/" | egrep -o "\<[^/]+/?$" 
etc/
[root@centos6 app]#echo "/etc" | egrep -o "\<[^/]+/?$" 
etc
  • 4、使用egrep取出上面路径的目录名
echo "/etc/rc.d/init.d/functions" | egrep -o ".*[[:alpha:]]*/"
  • 5、统计last命令中以root登录的每个主机IP地址登录次数
last | egrep "^root" |  egrep -v ":0" | egrep -wo  "([0-9]{1,3}\.){1,3}[0-9]{1,3}" |sort -n | uniq -c
  • 6、利用扩展正则表达式分别表示0-9、10-99、100-199、200-249、250-255
seq 255| egrep -w "[[:digit:]]{1}"
seq 255| egrep -w "[[:digit:]]{2}"
seq 255| egrep -w "^1[[:digit:]]{2}"
seq 255| egrep -w "2[01234][0-9]" 
seq 255| egrep -w "25[0-9]" 
  • 7、显示ifconfig命令结果中所有IPv4地址
ifconfig | egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}"
  • 8、将此字符串:welcome to magedu linux 中的每个字符去重并排序,重复次数多的排到前面
echo "welcome to magedu linux" | grep -o "[[:alpha:]]" | sort | uniq -c | sort -nr 
  • 9、用正则表达式表示固话号码、手机号码、邮箱、身份证号、QQ号码
固话
echo "0100712356" | egrep -w "(010|^02[0-9]|^0[3-9][0-9]{2})[0-9]{7}"

手机号
echo "15512345678" | grep -w "1[[:digit:]]\{10\}"
echo "15512345678" | egrep -w "1[[:digit:]]{10}" 

邮箱
echo '[email protected]' | egrep "\<[[:alnum:]._]+@[[:alnum:].\_]+\>"
echo '[email protected]' | egrep "\<[[:alnum:]._]+@[[:alnum:].\_]+\>"

身份证号
echo '130730198503122' | egrep "\<[0-9]{15}\>|\<[0-9]{18}\>|\<[0-9]{17}[xy]\>"
echo '13073019850312452x' | egrep "\<[0-9]{15}\>|\<[0-9]{18}\>|\<[0-9]{17}[xy]\>"
echo '130730199805264523' | egrep "\<[0-9]{15}\>|\<[0-9]{18}\>|\<[0-9]{17}[xy]\>"

QQ号码
echo '1234567890' | egrep "\<[0-9]{10}\>"

cp

语法

cp [OPTION]... [-T] SOURCE DEST
cp [OPTION]... SOURCE... DIRECTORY
cp [OPTION]... -t DIRECTORY SOURCE...

cp SRC DEST

SRC是文件:

  • 如果目标不存在:新建DEST,并将SRC中内容填充至DEST中
  • 如果目标存在:
    • 如果DEST是文件:将SRC中的内容覆盖至DEST中, 基于安全,建议为cp命令使用 -i 选项
    • 如果DEST是目录:在DEST下新建与原文件同名的文件,并将SRC中内容填充至新文件中

cp SRC... DEST

SRC...:多个文件

  • DEST必须存在,且为目录,其它情形均会出错;

cp SRC DEST

  • SRC是目录:此时使用选项:-r
    • 如果DEST不存在:则创建指定目录,复制SRC目录中所有文件至DEST中;
    • 如果DEST存在:
    • 如果DEST是文件:报错
    • 如果DEST是目录:

cp常用选项

-i        覆盖前提示  –n:不覆盖,注意两者顺序(i 要放在后面才会提示)
-r, -R    递归复制目录及内部的所有内容
-a        归档,相当于-dR --preserv=all
-d: --no-dereference --preserv=links 不复制原文件,只复制链接名
     如果创建软连接的时候使用的是绝对路径,拷贝后的文件是可以使用的
     如果创建软连接的时候使用的是相对路径,拷贝后的文件是失效的 (变红,找不到原来指向的文件)
--preserv[=ATTR_LIST]   ## 多个属性用逗号隔开
    mode         权限   
    ownership    属主属组
    timestamp    时间戳
    links
    xattr
    context
    all
-p        等同--preserv=mode,ownership,timestamp
-v: --verbose    ## 在使用 -a 的时候,如果文件夹很大,会一致等待,加上 -v 就会显示整个的复制过程。
-f: --force  ## if an existing destination file cannot be opened, remove it and try again 
                (redundant if the -n option is used)
             ## -f 一般只针对文件,文件存在且权限不够的时候会将改文件删除后,重新尝试拷贝。
                (使用-n选项的时候,-f不起作用)

-u: --update         只复制源比目标更新文件或目标不存在的文件
--backup=numbered    目标存在,覆盖前先备份加数字后缀【此参数一点放在最后】
                     --backup= 后面还有其他的参数:
                     none, off
                           never make backups (even if --backup is given)
                     numbered, t
                           make numbered backups
                     existing, nil
                           numbered if numbered backups exist, simple otherwise
                     simple, never
                           always make simple backups 只会称一个备份文件,循环覆盖

参数 --backup=numbered 的演示

[root@centos6 ming]$\cp  hosts testhosts  --backup=numbered
[root@centos6 ming]$ll testhosts*
-rw-r--r--. 1 root root 158 Nov 15 04:40 testhosts
-rw-r--r--. 1 root root 158 Nov 15 04:37 testhosts.~1~
-rw-r--r--. 1 root root 158 Nov 15 04:38 testhosts.~2~
[root@centos6 ming]$\cp  hosts testhosts  --backup=numbered
[root@centos6 ming]$\cp  hostll testhosts*
-rw-r--r--. 1 root root 158 Nov 15 04:41 testhosts
-rw-r--r--. 1 root root 158 Nov 15 04:37 testhosts.~1~
-rw-r--r--. 1 root root 158 Nov 15 04:38 testhosts.~2~
-rw-r--r--. 1 root root 158 Nov 15 04:40 testhosts.~3~
[root@centos6 ming]$

参数 --backup=simple 的演示,备份文件仅仅以 ~ 结尾

[root@centos6 ming]$\cp /etc/hosts testhosts --backup=simple
[root@centos6 ming]$ll testhosts*
-rw-r--r--. 1 root root 158 Nov 15 05:03 testhosts
-rw-r--r--. 1 root root 158 Nov 15 04:41 testhosts~   # 这个就是备份的文件,只会称一个备份文件,循环覆盖
-rw-r--r--. 1 root root 158 Nov 15 04:37 testhosts.~1~
-rw-r--r--. 1 root root 158 Nov 15 04:38 testhosts.~2~
-rw-r--r--. 1 root root 158 Nov 15 04:40 testhosts.~3~

提示

cp 不加参数一般只用于普通文件的复制,如果是对特殊文件,比如 设备文件的服饰复制,需要加 -a 参数。
否则复制就会出现问题,复制后的文件不是原来的文件了。

[root@centos6 app]$cp /dev/zero ./
^C
[root@centos6 app]$
[root@centos6 app]$ll
total 161948
-rw-r--r--. 1 root root 165834752 Nov 15 05:30 zero
[root@centos6 app]$
[root@centos6 app]$rm -f zero 
[root@centos6 app]$ls
[root@centos6 app]$
[root@centos6 app]$ll /dev/zero 
crw-rw-rw-. 1 root root 1, 5 Nov 12 22:00 /dev/zero
[root@centos6 app]$
[root@centos6 app]$cp -a /dev/zero ./
[root@centos6 app]$ll 
total 0
crw-rw-rw-. 1 root root 1, 5 Nov 12 22:00 zero
[root@centos6 app]$

[root@centos6 app]$cp -a /dev/sda1 ./
[root@centos6 app]$ll
total 0
brw-rw----. 1 root disk 8, 1 Nov 12 22:00 sda1
crw-rw-rw-. 1 root root 1, 5 Nov 12 22:00 zero
[root@centos6 app]$
[root@centos6 app]$ll /dev/sda1
brw-rw----. 1 root disk 8, 1 Nov 12 22:00 /dev/sda1
[root@centos6 app]$

练习

  • 1、定义别名命令baketc,每天将/etc/目录下所有文件,备份到/testdir独立的子目录下,并要求子目录格式为backupYYYY-mm-dd,备份过程可见
mkdir /testdir
alias baketc="cp -av /etc/ /testdir/backup`date +%F`"
将 baketc 添加到定时任务中
  • 2、创建/testdir/rootdir目录,并复制/root下所有文件到该目录内,要求保留原有权限
cp -r --preserv=mode /root /testdir/rootdir/
最直接的方法是
cp -a /root /testdir/rootdir/

touch 创建文件

语法

NAME
      change file timestamps

SYNOPSIS
      touch [OPTION]... FILE...

Options:
-a   仅改变atime和ctime
-m   仅改变mtime和ctime
-t [[CC]YY]MMDDhhmm[.ss]  指定atime和mtime的时间戳。
-c   如果文件不存在,则不予创建,常用于只想要更改文件的时间戳的场景。

如果不加任何选项,touch <file_name> ,会将文件的三种时间都改变:atime ctime mtime,可用通过 stat <file_name> 查看三种时间。


mv 移动或重命名文件

语法

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
      --help     display this help and exit
      --version  output version information and exit

常用选项

-i: 交互式
-f: 强制

rm 删除文件和目录

我们可以通过将 rm 定义为 mv 实现避免 rm 误操作

语法

rm[OPTION]... FILE...

常用选项:

-i: 交互式
-f: 强制删除
-r: 递归
--no-preserve-root  # centos6 和 centos7上默认已经禁止执行 rm -fr / ,如果手贱非要这么干就需要加这个参数。

示例:

rm -rf /

rm 设置别名为 mv 的演示

设置别名(要写在文件中 ~/.bashrc 中)
alias rm="mv -t /tmp"
rm 别名的实验
[root@centos6 app]$touch {1..9}
[root@centos6 app]$ls
1  2  3  4  5  6  7  8  9
[root@centos6 app]$
[root@centos6 app]$
[root@centos6 app]$rm {1..9}
[root@centos6 app]$ls
[root@centos6 app]$ls /tmp/
1  3  5  7  9               orbit-gdm   pulse-BBHWDR4XdT1Z  pulse-nnenwS2T1EpT  virtual-ming.cGlimt  yum.log
2  4  6  8  keyring-z0Kskk  orbit-root  pulse-fyiRR03PKq0L  pulse-NqfGHHo4wjxd  virtual-root.h9h9yY
[root@centos6 app]$

tree 显示目录树

选项

-d:         只显示目录
-L level:   指定显示的层级数目
-P pattern: 只显示由指定pattern (正则表达式)匹配到的路径

演示

[root@centos6 test]#tree
.
├── d1
│   └── d2
│       └── d3
│           └── d4
└── dosometing.sh

4 directories, 1 file
[root@centos6 test]#
[root@centos6 test]#tree -L 1
.
├── d1
└── dosometing.sh

1 directory, 1 file
[root@centos6 test]#tree -L 2
.
├── d1
│   └── d2
└── dosometing.sh

2 directories, 1 file
[root@centos6 test]#tree -L 3
.
├── d1
│   └── d2
│       └── d3
└── dosometing.sh

3 directories, 1 file
[root@centos6 test]#tree -L 4
.
├── d1
│   └── d2
│       └── d3
│           └── d4
└── dosometing.sh

4 directories, 1 file
[root@centos6 test]#

mkdir 创建目录

-p:        存在于不报错,且可自动创建所需的各目录
-v:        显示详细信息(创建的过程)
-m MODE:   创建目录时直接指定权限

练习

(1) 如何创建/testdir/dir1/x, /testdir/dir1/y, /testdir/dir1/x/a, /testdir/dir1/x/b, /testdir/dir1/y/a, /testdir/dir1/y/b

mkdir -p /testdir/dir1/{x..y}/{a..b}
或
mkdir -p /testdir/dir1/{x,y}/{a,b}

[root@centos7 app]$tree /testdir/
/testdir/
└── dir1
    ├── x
    │   ├── a
    │   └── b
    └── y
        ├── a
        └── b

7 directories, 0 files

(2) 如何创建/testdir/dir2/x,/testdir/dir2/y,/testdir/dir2/x/a,/testdir/dir2/x/b

mkdir -p /testdir/dir2/{x/{a..b},y}

[root@centos7 app]$tree /testdir/
/testdir/
└── dir2
    ├── x
    │   ├── a
    │   └── b
    └── y

5 directories, 0 files

(3) 如何创建/testdir/dir3, /testdir/dir4, /testdir/dir5, /testdir/dir5/dir6, /testdir/dir5/dir7

mkdir -p /testdir/dir{3,4,5/dir{6..7}}

[root@centos7 app]$tree /testdir/
/testdir/
├── dir3
├── dir4
└── dir5
    ├── dir6
    └── dir7

5 directories, 0 files

rmdir 删除空目录

注意: 只能删除空目录!!!

选项

-p: 递归删除父空目录(当父母目录为空的时候,也将父目录删除,其实和 mkdir 是相反的)
-v: 显示详细信息

ln 创建硬链接和软链接

NAME
       ln - make links between files

SYNOPSIS
       ln [OPTION]... [-T] TARGET LINK_NAME   (1st form)
       ln [OPTION]... TARGET                  (2nd form)
       ln [OPTION]... TARGET... DIRECTORY     (3rd form)
       ln [OPTION]... -t DIRECTORY TARGET...  (4th form)
  • 本质不同
    硬链接是同一个文件,软连接不是同一个文件
  • 删除
    硬链接不影响,软连接失效
  • 创建
    硬链接数加1,软连接不变
  • 跨分区
    硬链接不可以,软连接可以
  • 目录
    不能创建硬链接,可以创建软链接
  • 路径
    硬链接的创建,源文件和目的文件的路径,使用相对路径和绝对路径都是一样的,
    软链接的创建,源文件如果使用相对路径,要注意一定是相对于软连接文件的路径,而不是相对于当前工作目录的路径。

硬链接是不能跨分区设备的。

因为inode的本质是分区独立的,跨分区或者设备就是让一个文件同时载两个地方,这是反常理的,
就好比不能让一个人在同一个时刻同时在中国和美国一样。
只能在同一个分区上创建硬链接。

  • 演示
[root@centos6 app]$lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0     11:0    1 1024M  0 rom  
sda      8:0    0  200G  0 disk 
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0 48.8G  0 part /
├─sda3   8:3    0 19.5G  0 part /app
├─sda4   8:4    0    1K  0 part 
└─sda5   8:5    0    3G  0 part [SWAP]
[root@centos6 app]$ll /app/
total 4
-rw-r--r--. 1 root root 4096 Nov 17 18:08 f1
[root@centos6 app]$ln /app/f1 /boot/new_f1
ln: creating hard link `/boot/new_f1' => `/app/f1': Invalid cross-device link  ## 提示无效的跨设备链接
[root@centos6 app]$
[root@centos6 app]$ln /app/f1 /app/new_f1
[root@centos6 app]$ll -i
total 8
11 -rw-r--r--. 2 root root 4096 Nov 17 18:08 f1
11 -rw-r--r--. 2 root root 4096 Nov 17 18:08 new_f1
[root@centos6 app]$

想要实现跨设备就要通过软链接来实现了

ln -s /app/f1 /boot/new_f1
[root@centos6 app]$ln /app/f1 /boot/new_f1
ln: creating hard link `/boot/new_f1' => `/app/f1': Invalid cross-device link
[root@centos6 app]$
[root@centos6 app]$ln -s /app/f1 /boot/new_f1
[root@centos6 app]$ll /boot/new_f1 
lrwxrwxrwx. 1 root root 7 Nov 17 18:24 /boot/new_f1 -> /app/f1

软连接文件的大小其实就是源文件的路径的长度, 源文件/app/f1 的路径的长度是7个字符,所以最后的软连接 /boot/new_f1 大小就是 7个字节

[root@centos6 ~]$ll /app/test/scm 
-rw-r--r--. 1 root root 13 Nov 17 18:30 /app/test/scm
[root@centos6 ~]$ln -s /app/test/scm  /boot/scm_new
[root@centos6 ~]$ll /boot/scm_new 
lrwxrwxrwx. 1 root root 13 Nov 17 18:33 /boot/scm_new -> /app/test/scm

源文件/app/test/scm 的路径的长度是13个字符,所以最后的软连接 /boot/scm_new 大小就是 13个字节

关于软连接相对路径的写法

创建软连接的时候建议使用相对路径,因为使用相对路径,软件拷贝到别的路径下不会有问题。
使用绝对路径时,软件拷贝后由于环境的不同,就会出现路径不一致的问题。

软连接的相对路径,是相对于软连接的
  • 目录结构
[root@centos6 app]$tree
.
├── dir1
│   └── dir2
│       └── dir3
│           └── dir4
└── f1

4 directories, 1 file   
  • 错误写法
ln -s f1 dir1/dir2/dir3/dir4/f111

输入图片说明

  • 正确写法
ln -s ../../../../f1  dir1/dir2/dir3/dir4/f222

输入图片说明


tr 转换和删除字符

语法

tr [OPTION]... SET1 [SET2]

Options:
-c –C --complement      取字符集的补集(取反)
-d --delete             删除所有属于第一字符集的字符
-s --squeeze-repeats    把连续重复的字符以单独一个字符表示
-t --truncate-set1      将第一个字符集对应字符转化为第二字符集对应的字符

SETs are specified as strings of characters.  Most represent themselves.  Interpreted sequences are:
\NNN   character with octal value NNN (1 to 3 octal digits)  八进制表示
\\     backslash
\a     audible BEL
\b     backspace
\f     form feed
\n     new line
\r     return
\t     horizontal tab
\v     vertical tab

正则表示式匹配

[:alnum:]    字母和数字
[:alpha:]    字母
[:cntrl:]    控制(非打印)字符
[:digit:]    数字
[:graph:]    图形字符
[:lower:]    小写字母
[:print:]    可打印字符
[:punct:]    标点符号
[:space:]    空白字符
[:upper:]    大写字母
[:xdigit:]   十六进制字符

tr 默认是按位逐个替换的

tr 1 a         # 将后面输入的字符串中所有的 1 替换为 a
tr 135 abc     # 将后面输入的字符串中所有的 1 替换为 a, 3 替换为 b, 5 替换为 c
tr 1357 ab     # 将后面输入的字符串中 1 替换为a, 3、5和7 替换为 b
tr -t 1357 ab  # 将后面输入的字符串中1 替换为a, 3替换为 b, 5和7 不被替换
tr '1-9' 'a-i' # 将后面输入的字符串中1至9, 对应地替换为a至i的字母
tr -d 'a'      # 将后面输入的字符串中所有的 a 删除
tr 'a-z' 'A-Z' < test  # 将文件test中的 小写字母题替换为大写字母后输出(不会修改原文件的内容)
tr [:lower:] [:upper:] < test  # 将文件test中的 小写字母题替换为大写字母后输出(不会修改原文件的内容)
tr -d 'a-z' < test     # 将文件test中的 小写字母题删除后输出(不会修改原文件的内容)
tr -d 'a-z' < test >test2 # 将处理结果重定向到新的文件中(注意不能重定向到原文件中,会将原文件清空的)
tr -s 'a'      # 将后面输入的字符串中重复的 a 压缩成一个a
tr -s 'ab'     # 将后面输入的字符串中重复的 a 压缩成一个a, 连续的 b 压缩成一个 b
tr -sc 'ab'    # 将后面输入的字符串中非 a 非 b 的重复的字母压缩成一个字母
tr -dc 'a'     # 将后面输入的字符串中所有的 a 删除(比较特殊的是,换行符\n也被看作是字符,以ctrl + d 作为结束。)
tr -dc 'a\n'   # 将后面输入的字符串中所有的 a 删除
tr -d '\n' < f1       # 清除换行符 (多行合成以一行)
seq 10 | tr -d '\n'   # 清除换行符 (多行合成以一行)
seq 10 | tr '\n' '-'  # 将换行符更换为短横线 (多行合成以一行)
echo "1 2 3 4 5" | tr ' ' '\n'  # 一行合成多行

# # 处理字符串"xt.,l 1 jr#!$mn2 c*/fe3 uz4",只保留其中的数字和空格的几种种写法
echo "xt.,l 1 jr#newmn2 c*/fe3 uz4" | tr -dc ' [:digit:]' 
echo "xt.,l 1 jr#newmn2 c*/fe3 uz4" | tr -dc [:space:][:digit:]   
echo "xt.,l 1 jr#newmn2 c*/fe3 uz4" | tr -dc '[:space:][:digit:]'
echo "xt.,l 1 jr#newmn2 c*/fe3 uz4" | tr -dc "[:space:][:digit:]"

演示

[root@centos7 ~]$tr 1 a
53112112273
53aa2aa2273

[root@centos7 ~]$tr 135 abc
42513749
42cab749

[root@centos7 ~]$tr 1357 ab  
143517
a4bbab

[root@centos7 ~]$tr -t 1357 ab
143517
a4b5a7

[root@centos7 ~]$tr '1-9' 'a-i'
923187593450*$5&6
ibcahgeicde0*$e&f
[root@centos7 app]$tr -d 'a'  
dafara
dfr
[root@centos7 app]$tr 'a-z' 'A-Z' < test 
#
# /ETC/FSTAB
# CREATED BY ANACONDA ON SUN NOV 11 17:34:32 2018
#
# ACCESSIBLE FILESYSTEMS, BY REFERENCE, ARE MAINTAINED UNDER '/DEV/DISK'
# SEE MAN PAGES FSTAB(5), FINDFS(8), MOUNT(8) AND/OR BLKID(8) FOR MORE INFO
#
UUID=128C65F8-BA30-4831-A8BC-2CEB8E3397FF /                       XFS     DEFAULTS        0 0
UUID=35D4CE0D-B6E9-49C4-BB8B-B5A80E26C517 /APP                    XFS     DEFAULTS        0 0
UUID=C8372E06-B5AE-4AA7-BBF0-C54AD3D9FB8E /BOOT                   XFS     DEFAULTS        0 0
UUID=D27705E4-07AB-4707-AB11-18540442D425 SWAP                    SWAP    DEFAULTS        0 0
[root@centos7 app]$
[root@centos7 app]$cat test 

#
# /etc/fstab
# Created by anaconda on Sun Nov 11 17:34:32 2018
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
UUID=128c65f8-ba30-4831-a8bc-2ceb8e3397ff /                       xfs     defaults        0 0
UUID=35d4ce0d-b6e9-49c4-bb8b-b5a80e26c517 /app                    xfs     defaults        0 0
UUID=c8372e06-b5ae-4aa7-bbf0-c54ad3d9fb8e /boot                   xfs     defaults        0 0
UUID=d27705e4-07ab-4707-ab11-18540442d425 swap                    swap    defaults        0 0
[root@centos7 app]$
[root@centos7 app]$tr -d 'a-z' < test       

#
# //
# C    S N 11 17:34:32 2018
#
# A ,  ,    '//'
# S   (5), (8), (8) / (8)   
#
UUID=128658-30-4831-8-283397 /                                    0 0
UUID=3540-69-494-8-58026517 /                                 0 0
UUID=837206-5-47-0-54398 /                                0 0
UUID=277054-07-4707-11-18540442425                                 0 0
[root@centos7 app]$
[root@centos7 app]$tr -d 'a-z' < test >test2
[root@centos7 app]$cat test2

#
# //
# C    S N 11 17:34:32 2018
#
# A ,  ,    '//'
# S   (5), (8), (8) / (8)   
#
UUID=128658-30-4831-8-283397 /                                    0 0
UUID=3540-69-494-8-58026517 /                                 0 0
UUID=837206-5-47-0-54398 /                                0 0
UUID=277054-07-4707-11-18540442425                                 0 0
[root@centos7 app]$tr -s 'a'
aaagaafbbb
agafbbb

[root@centos7 app]$tr -s 'ab'
aaafababg
afababg

[root@centos7 app]$
[root@centos7 app]$tr -s 'ab'
aaafbbbgabab
afbgabab
[root@centos7 app]$tr -sc 'ab'
aaacccccccbbb    
aaacbbb
[root@centos7 app]$tr -dc 'a'
aaaabbccfff
rrraaaagagagatrg
ffhshsqa       # 这里想结束 按住 ctrl + d
aaaaaaaaaaaa[root@centos7 app]$


[root@centos7 app]$tr -dc 'a\n'
aldfgjalgjalgjalgalajglagag
aaaaaaaa       # 加上 "\n" 后支持 回车换行结束了
[root@centos7 app]$cat f1
aaa
bbb
ccc
ddd
[root@centos7 app]$
[root@centos7 app]$tr -d '\n' < f1
aaabbbcccddd[root@centos7 app]$
[root@centos7 app]$seq 10
1
2
3
4
5
6
7
8
9
10
[root@centos7 app]$
[root@centos7 app]$seq 10 | tr -d '\n'
12345678910[root@centos7 app]$
[root@centos7 app]$seq 10 | tr '\n' '-'
1-2-3-4-5-6-7-8-9-10-[root@centos7 app]$
[root@centos7 app]$echo "1 2 3 4 5" | tr ' ' '\n'
1
2
3
4
5

利用 tr 将 windows 格式的文本文件 转换为 linux 格式的文本文件

输入图片说明

tr -d '\r' < win.txt > new-win.txt
[root@centos7 app]$hexdump -C win.txt 
00000000  61 0d 0a 62 0d 0a 63                              |a..b..c|
00000007
[root@centos7 app]$tr -d '\r' < win.txt > new-win.txt
[root@centos7 app]$
[root@centos7 app]$hexdump -C new-win.txt
00000000  61 0a 62 0a 63                                    |a.b.c|
00000005
[root@centos7 app]$

水平制表符和垂直制表符的演示

cat test
hexdump -c test 
hexdump -C test 
tr '\n' '\t' < test > new_test
cat new_test 
hexdump -c new_test 
hexdump -C new_test 
tr '\n' '\v' < test > new_test
cat new_test 
hexdump -c new_test
hexdump -C new_test

演示

图片名称

练习

  • 1、将/etc/issue文件中的内容转换为大写后保存至/tmp/issue.out文件中
tr [:lower:] [:upper:] < /etc/issue > /tmp/issue.out
tr 'a-z' 'A-Z' < /etc/issue > /tmp/issue.out
  • 2、将当前系统登录用户的信息转换为大写后保存至/tmp/who.out文件中
who | tr [:lower:] [:upper:]  > /tmp/who.out
who | tr 'a-z' 'A-Z'  >  /tmp/who.out
  • 3、一个linux用户给root发邮件,要求邮件标题为"help",邮件正文如下:

Hello, I am 用户名,The system version is here,please help me to check it ,thanks!
操作系统版本信息

mail -s "help" root <<EOF
Hello, I am $USER,The system version is here,please help me to check it ,thanks! 
操作系统版本信息  `uname -r`
EOF
  • 4、将/root/下文件列表,显示成一行,并文件名之间用空格隔开
ls /root/ | tr '\n' ' '
  • 5、计算1+2+3+..+99+100的总和
echo {1..100} | tr ' ' '+' | bc
seq -s + 100 | bc
  • 6、删除Windows文本文件中的'^M'字符
tr -d '\r' win.txt
或
tr -d '\15' < win.txt    # 15是回车符 \r 的八进制表示,可通过 echo 'ibase=16;obase=8;D' | bc 计算出来
或
dos2unix win.txt


查看命令
tr -d '\r' < win.txt  | hexdump -c
tr -d '\15' < win.txt | hexdump -c 
[root@centos7 app]$echo 'ibase=16;obase=8;D' | bc
15
[root@centos7 app]$
[root@centos7 app]$tr -d '\15' < win.txt | hexdump -c 
0000000   a  \n   b  \n   c                                            
0000005
[root@centos7 app]$
  • 7、处理字符串"xt.,l 1 jr#!$mn2 c*/fe3 uz4",只保留其中的数字和空格
echo 'xt.,l 1 jr#!$mn2 c*/fe3 uz4' | tr -dc ' [:digit:]'
echo 'xt.,l 1 jr#!$mn2 c*/fe3 uz4' | tr -dc [:space:][:digit:]
echo 'xt.,l 1 jr#!$mn2 c*/fe3 uz4' | tr -dc '[:space:][:digit:]'
echo 'xt.,l 1 jr#!$mn2 c*/fe3 uz4' | tr -dc "[:space:][:digit:]"
  • 8、将PATH变量每个目录显示在独立的一行
echo $PATH | tr ':' '\n'
  • 9、将指定文件中0-9分别替代成a-j
tr '0-9' 'a-j' < f1
  • 10、将文件中每个单词(由字母组成)显示在独立的一行,并无空行
tr -c '[:alpha:]' '\n' < f1 | tr -s '\n'
tr -sc '[:alpha:]' '\n' < f1

重定向到多个目标(tee)

应用场景:
我们在做重定向到文件的同时还需要在屏幕输出,以便对屏幕的输出做进一步的处理

语法

NAME
       tee - read from standard input and write to standard output and files

SYNOPSIS
       tee [OPTION]... [FILE]...

DESCRIPTION
       Copy standard input to each FILE, and also to standard output.

       -a, --append              # append to the given FILEs, do not overwrite
       -i, --ignore-interrupts   # ignore interrupt signals
       --help                    # display this help and exit
       --version                 # output version information and exit
       If a FILE is -, copy again to standard output.
  • 命令1 | tee [-a ] 文件名 | 命令2

    • 把命令1的STDOUT保存在文件中,做为命令2的输入
    • -a 追加 (默认是覆盖文件的)
  • 使用:

    • 保存不同阶段的输出
    • 复杂管道的故障排除
    • 同时查看和记录输出

演示1

[root@centos6 ~]$ls | tee test.log
anaconda-ks.cfg
Desktop
Documents
Downloads
install.log
install.log.syslog
Music
Pictures
Public
Templates
test.log
Videos
[root@centos6 ~]$cat test.log 
anaconda-ks.cfg
Desktop
Documents
Downloads
install.log
install.log.syslog
Music
Pictures
Public
Templates
test.log
Videos
[root@centos6 ~]$

演示2 对输出做进一步处理(默认是覆盖文件的)

[root@centos6 ~]$hostname | tee test.log | tr 'a-z' 'A-Z'
CENTOS6.MAGEDU.COM
[root@centos6 ~]$cat test.log 
centos6.magedu.com
[root@centos6 ~]$

演示3 追加选项的演示

[root@centos6 ~]$hostname cat test.log 
centos6.magedu.com
[root@centos6 ~]$uname -r | tee -a test.log | tr 'a-z' 'A-Z'        
2.6.32-642.EL6.X86_64
[root@centos6 ~]$cat test.log 
centos6.magedu.com
2.6.32-642.el6.x86_64
[root@centos6 ~]$

useradd 添加用户

语法

useradd [options] LOGIN

Options:
-u    UID
-o    配合 -u 选项,不检查UID的唯一性 (用于两个用户对应同一个UID,但是登陆后只显示前面的账户名)
-g    GID:指明用户所属基本组(主组),可为组名,也可以GID,但是指定的组要事先存在
-c    "COMMENT":用户的注释信息
-d    HOME_DIR:以指定的路径(不存在)为家目录
-s    SHELL: 指明用户的默认shell程序,可用列表在/etc/shells文件中
-G    GROUP1[,GROUP2,...]:为用户指明附加组,组须事先存在
-N    不创建私用组做主组,使用users组做主组
-r    创建系统用户CentOS 6: ID<500,CentOS 7: ID<1000,使用 -r 创建用户是不会创建家目录的。
-m    创建家目录,用于系统用户
-M    不创建家目录,用于非系统用户
-p, --password PASSWORD  指定用户的密码
     (注意这里指定的密码字符串是认为是被加密过的,所以指定密码为123456,创建后使用123456是登陆不了的,所以组要指定加密码后的字符串)

默认值设定:/etc/default/useradd文件中

显示或更改默认设置

  • useradd -D
  • useradd –D -s SHELL
  • useradd –D –b BASE_DIR
  • useradd –D –g GROUP
[root@centos6 ~]#cat  /etc/default/useradd
# useradd defaults file
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel      # 当创建一个新的用户的时候,就将此目录中的文件拷贝到用户的家目录中。
CREATE_MAIL_SPOOL=yes

[root@centos6 ~]#

练习

  • 1、创建用户gentoo,附加组为bin和root,默认shell为/bin/csh,注释信息为"Gentoo Distribution"
[root@centos7 ~]#useradd -G bin,root -s /bin/csh -c "Gentoo Distribution" gentoo
[root@centos7 ~]#id gentoo
uid=1001(gentoo) gid=1001(gentoo) groups=1001(gentoo),0(root),1(bin)
[root@centos7 ~]#getent passwd gentoo
gentoo:x:1001:1001:Gentoo Distribution:/home/gentoo:/bin/csh
[root@centos7 ~]#
  • 2、创建下面的用户、组和组成员关系
    • 名字为admins 的组
    • 用户natasha,使用admins 作为附属组
    • 用户harry,也使用admins 作为附属组
    • 用户sarah,不可交互登录系统,且不是admins 的成员,natasha,harry,sarah密码都是centos
    groupadd admins
    useradd -G admins natasha
    useradd -G admins harry
    useradd -s /sbin/nologin sarah
    echo 'centos' | passwd --stdin natasha
    echo 'centos' | passwd --stdin harry
    echo 'centos' | passwd --stdin sarah

新建用户的相关文件和命令

  • /etc/default/useradd
  • /etc/skel/*
  • /etc/login.defs
  • newusers passwd格式文件 批量创建用户
  • chpasswd 批量修改用户口令

-p, --password PASSWORD 指定用户的密码的演示

生成加密口令

[root@centos6 ~]#openssl passwd -1   ## -1 是指基于md5加密的口令
Password: 
Verifying - Password: 
$1$J6t2q3Xe$7cAsGseVp4qgTvN7Pnpu7/
[root@centos6 ~]#

指定口令创建用户

useradd -p '$1$J6t2q3Xe$7cAsGseVp4qgTvN7Pnpu7/' user1

登陆验证

[root@centos6 ~]#useradd -p '$1$J6t2q3Xe$7cAsGseVp4qgTvN7Pnpu7/' user1
[root@centos6 ~]#su - ming
[ming@centos6 ~]$su - user1
Password: 
[user1@centos6 ~]$
[user1@centos6 ~]$logout
[ming@centos6 ~]$logout
[root@centos6 ~]#

usermod 更改用户账户

语法

Usage: usermod [options] LOGIN

Options:
  -c, --comment COMMENT
        修改用户的描述信息(一般是通过 chfn 命令修改的)
  -d, --home HOME_DIR           
        用户的新的家目录(配合 -m 选项的时候会自动创建不存在的家目录,包括家目录中的必要文件)当前没有家目录,就不会创建新的家目录。
  -e, --expiredate EXPIRE_DATE  
        用户过期时间(格式 YYYY-MM-DD),不设置就是无限期,依赖文件/etc/shadow,不存在会自动创建。
  -f, --inactive INACTIVE
        用户过期后且在永久不可用之前的天数,0 为只要过期用户马上不可用,-1 禁用此选项。依赖文件/etc/shadow,不存在会自动创建。
  -g, --gid GROUP               
        修改用户的主组(一个账号必须属于一个主组)
  -G, --groups GROUP1[,GROUP2,...[,GROUPN]]] 
        新附加组,原来的附加组将会被覆盖;若保留原有,则要同时使用-a选项
  -a, --append   
        专门用来配和 -G 选项使用,追加附加组的配置而不是覆盖原来附加组的配置。
  -h, --help   
        查看帮助信息
  -l, --login NEW_LOGIN         
        指定新的用户名(更改用户名)
  -L, --lock                    
        锁定账号,就是在文件 /etc/shadow 中密码的位置前加叹号 !
  -m, --move-home  
        移动家目录到指定的目录(只能和 -d 参数一起使用)
  -o, --non-unique              allow using duplicate (non-unique) UID
        允许不同的用户名使用同一个UID
  -p, --password PASSWORD       use encrypted password for the new password
        
  -R, --root CHROOT_DIR         directory to chroot into
        
  -s, --shell SHELL   
        修改用户的登录 shell 类型 (同 chsh -s 的用法)
  -u, --uid UID  
        指定用户的 UID
  -U, --unlock                  unlock the user account
        解锁账号,就是将文件 /etc/shadow 中密码之前的叹号!去掉
        空密码的用户默认有两个叹号,centos6以后不允许对没有设置密码的用户执行此操作,centos5以前是可以的。
  -Z, --selinux-user SEUSER     new SELinux user mapping for the user account

命令示例

usermod -d /home/ming ming    给用户家目录设置
usermod -md /app/ming ming    给用户家目录设置,并将原家目录中的文件移动到新家目录,新家目录不存在会自动创建
usermod -L ming     锁定用户账号
usermod -U ming     解锁用户账号
usermod -G mage1 ming     将用户 ming 指定辅助组为 mage1
usermod -aG mage2,mage3 ming   为用户 ming 添加辅助组为 mage2、mage3,会保留原来的辅助组 mage1
usermod -l new_name old_name  更改用户名(只改用户名,密码、组、权限等信息都不会变)
usermod -G '' user1      删除用户user1的所有附加组(也就是指定为空)
usermod -G 主组名 user1   删除用户user1的所有附加组(将主组指定为附加组就会将附加组清空,因为一个组不能既是主组又是附加组)  

演示

  • usermod -md /app/ming ming
[root@centos6 app]#ll /home/ming/
dead.letter  Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
[root@centos6 app]#
[root@centos6 app]#ll /app/
total 4
-rw-r--r--. 1 root root 956 Nov 19 12:59 f1
[root@centos6 app]#usermod -md /app/ming ming    
[root@centos6 app]#ls /app/ming/
dead.letter  Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
[root@centos6 app]# 
[root@centos6 app]#ls /home/ming
ls: cannot access /home/ming: No such file or directory
[root@centos6 app]#
  • 但是要将家目录重新移动到 /home下,是不行的,需要手工移动 mv。
mv /app/ming/ /home/
usermod -d /home/ming ming

锁定和解锁用户

使用useradd 添加用户是不指定密码,该用户也是不能以空密码登录的,原因是/etc/shadow中用户密码的部分是有 "!!",即锁定状态。
centos6以后,已经不建议使用 usermod -U username 解锁账户(使用空密码登录),因为不安全,防止误操作,centos5以前没有限制。

  • 锁定账号 usermod -L ming

锁定用户账号后,在配置文件 /etc/shadow 中的密码前面后有一个叹号 ! 用户是不可以登录的。

[root@centos6 ~]#getent shadow ming
ming:$6$mdd/8sYb$gulagv6y8wUdWisoqkzyEtM20ohsp7tJbyFAJdKxBQF06ZWUAqO1x8EoDRvq2eOZho4e4vuwZ7.uOm7Fcp.Ym0:17855:0:99999:7:::
[root@centos6 ~]#
[root@centos6 ~]#usermod -L ming
[root@centos6 ~]#getent shadow ming
ming:!$6$mdd/8sYb$gulagv6y8wUdWisoqkzyEtM20ohsp7tJbyFAJdKxBQF06ZWUAqO1x8EoDRvq2eOZho4e4vuwZ7.uOm7Fcp.Ym0:17855:0:99999:7:::
图片名称
  • 解锁账号 usermod -U ming

解锁用户账号后,在配置文件 /etc/shadow 中的密码前面的叹号 ! 就没有了,用户又可以登录了。

[root@centos6 ~]#getent shadow ming
ming:$6$mdd/8sYb$gulagv6y8wUdWisoqkzyEtM20ohsp7tJbyFAJdKxBQF06ZWUAqO1x8EoDRvq2eOZho4e4vuwZ7.uOm7Fcp.Ym0:17855:0:99999:7:::

输入图片说明


userdel 删除用户

语法

Usage: userdel [options] LOGIN

Options:
  -f, --force                   force some actions that would fail otherwise
                                e.g. removal of user still logged in
                                or files, even if not owned by the user
  -h, --help                    display this help message and exit
  -r, --remove                  remove home directory and mail spool
  -R, --root CHROOT_DIR         directory to chroot into
  -Z, --selinux-user            remove any SELinux user mapping for the user

-r 选项要慎用,因为用户账号不要了,不等于家目录下的数据不要了。数据是很重要的。

示例

[root@centos6 ~]#id teset
id: teset: No such user
[root@centos6 ~]#id test
id: test: No such user
[root@centos6 ~]#useradd test
[root@centos6 ~]#id test     
uid=504(test) gid=507(test) groups=507(test)
[root@centos6 ~]#ls /home/test/ -d
/home/test/
[root@centos6 ~]#ls /var/spool/mail/test 
/var/spool/mail/test
[root@centos6 ~]#userdel -r test
[root@centos6 ~]#ls /home/test/ -d       
ls: cannot access /home/test/: No such file or directory
[root@centos6 ~]#ls /var/spool/mail/test 
ls: cannot access /var/spool/mail/test: No such file or directory
[root@centos6 ~]#id test
id: test: No such user
[root@centos6 ~]#

groupadd 创建组

语法

groupadd [OPTION]... group_name

选项
-g GID    # 指明GID号;[GID_MIN, GID_MAX]
-p, --password PASSWORD   # 创建的时候指定组密码
-r        #创建系统组       
          #CentOS 6: ID<500        
          #CentOS 7: ID<1000

groupmod 修改和删除组

groupmod [OPTION]... GROUP

Options:
  -g, --gid GID                 change the group ID to GID
  -h, --help                    display this help message and exit
  -n, --new-name NEW_GROUP      change the name to NEW_GROUP
  -o, --non-unique              allow to use a duplicate (non-unique) GID
  -p, --password PASSWORD       change the password to this (encrypted)
                                PASSWORD
  -R, --root CHROOT_DIR         directory to chroot into

gpasswd

语法

administer /etc/group and /etc/gshadow

Usage: gpasswd [option] GROUP

Options:
  -a, --add USER                add USER to GROUP
  -d, --delete USER             remove USER from GROUP
  -h, --help                    display this help message and exit
  -Q, --root CHROOT_DIR         directory to chroot into
  -r, --delete-password         remove the GROUP's password
  -R, --restrict                restrict access to GROUP to its members
  -M, --members USER,...        set the list of members of GROUP
  -A, --administrators ADMIN,...
                                set the list of administrators for GROUP
Except for the -A and -M options, the options cannot be combined.

更改组密码

  • 组密码:gpasswd
  • gpasswd [OPTION] GROUP
-a user 将user添加至指定组中
-d user 从指定组中移除用户user
-A user1,user2,... 设置有管理权限的用户列表

命令示例

gpasswd -a user1 test   # 将user1添加到test组中
gpasswd -d user1 test   # 将user1从test组中删除
gpasswd -A ming test    # 设置ming用户为test组的管理员

演示

添加组成员

[root@centos6 test]#getent gshadow test        
test:!:ming:
[root@centos6 test]#gpasswd -a user1 test      
Adding user user1 to group test
[root@centos6 test]#getent gshadow test  
test:!:ming:user1

删除组成员

[root@centos6 test]#getent gshadow test
test:!:ming:user1
[root@centos6 test]#gpasswd -d user1 test
Removing user user1 from group test
[root@centos6 test]#getent gshadow test  
test:!:ming:

设置管理员

[root@centos6 test]#getent gshadow test
test:!::
[root@centos6 test]#gpasswd -A ming test
[root@centos6 test]#getent gshadow test 
test:!:ming:

口令及时过期的设置,墙强迫用户更改初始口令

  • 方法1
passwd -e ming
  • 方法2
chage -d 0 ming
[root@centos6 ~]#passwd -e ming
Expiring password for user ming.
passwd: Success
[root@centos6 ~]#

更改后
[root@centos6 ~]#getent shadow ming
ming:$6$FWNaz5q4$C5tswES6V3urxvObtSPNOnHVbVm8/I2itoXPFRP/WmG3Noqpmk4UyAQsAV5emKEF.SGWQc3ZlBX/fQh3b.y7P1:0:3:30:7:::

输入图片说明

登录后就会提示马上更改口令

输入图片说明


密码加密

  • 加密机制:
    • 加密:明文--> 密文
    • 解密:密文--> 明文
  • 单向加密:哈希算法,原文不同,密文必不同

    • 相同算法定长输出,获得密文不可逆推出原始数据
    • 雪崩效应:初始条件的微小改变,引起结果的巨大改变
      md5: message digest, 128bits # $1
      sha1: secure hash algorithm, 160bits
      sha224: 224bits
      sha256: 256bits # $5
      sha384: 384bits
      sha512: 512bits # $6
  • 更改加密算法 authconfig --passalgo=sha256 --update
    此命令实际上就是修改的配置文件 /etc/login.defs

密码的复杂性策略

  • 使用数字、大写字母、小写字母及特殊字符中至少3种
  • 足够长
  • 使用随机密码
  • 定期更换,不要使用最近曾经使用过的密码

密码期限

图片名称

id 查看用户相关的ID信息

语法

id [OPTION]... [USER]

Options:
-u    显示UID
-g    显示GID
-G    显示用户所属的组的ID
-n    显示名称,需配合ugG使用

su 切换用户或以其他用户身份执行命令

语法

su [options...] [-] [user [args...]]
  • 切换用户的方式:

    • su UserName:非登录式切换,即不会读取目标用户的配置文件,不改变当前工作目录
    • su - UserName:登录式切换,会读取目标用户的配置文件,切换至家目录,完全切换
  • root su至其他用户无须密码;非root用户切换时需要密码
  • 换个身份执行命令:
su [-] UserName -c 'COMMAND'
  • 选项:-l --login
su -l UserName 相当于 su - UserName

passwd设置密码

  • passwd [OPTIONS] UserName: 修改指定用户的密码,仅root用户权限
  • passwd: 修改自己的密码
  • 常用选项:
-l    锁定指定用户
-u    解锁指定用户
-e    强制用户下次登录修改密码
-n mindays      指定最短使用期限
-x maxdays      最大使用期限
-w warndays     提前多少天开始警告
-i inactivedays  非活动期限
--stdin         从标准输入接收用户密码
echo "PASSWORD" | passwd --stdin USERNAME

修改用户密码策略

  • 语法
chage [OPTION]... LOGIN
  • 选项
-d LAST_DAY
-E --expiredate EXPIRE_DATE
-I --inactive INACTIVE
-m --mindays MIN_DAYS
-M --maxdays MAX_DAYS
-W --warndays WARN_DAYS
–l 显示密码策略
  • 示例:
chage -d 0 tom 下一次登录强制重设密码
chage -m 0 –M 42 –W 14 –I 7 tom
chage -E 2016-09-10 tom

用户相关的其它命令

  • chfn 指定个人信息
  • chsh 指定shell
  • finger

newgrp命令:临时切换主组

如果用户本不属于此组,则需要组密码


groupmems 更改和查看组成员

语法

groupmems [options] [action]

options:
  -g, --group groupname更改为指定组(只有root)
Actions:
  -a, --add username 指定用户加入组
  -d, --delete username 从组中删除用户
  -p, --purge 从组中清除所有成员
  -l, --list 显示组成员列表

groups 查看用户所属组列表

groups [OPTION].[USERNAME]... 

演示

[root@centos6 test]#groups ming
ming : ming opts admins   # 用户ming的组有 ming opts admins

chown修改文件的属主和属组

语法

chown [OPTION]... [OWNER][:[GROUP]] FILE...

用法:
    OWNER
    OWNER:GROUP
    :GROUP
    命令中的冒号可用.替换
    -R: 递归
    chown [OPTION]... --reference=RFILE FILE...

修改文件的属组:chgrp

语法

chgrp [OPTION]... GROUP FILE...
chgrp [OPTION]... --reference=RFILE FILE...
                    参考 RFILE 的权限设置 FILE... 的权限
-R 递归

chmod 修改文件权限

语法

chmod [OPTION]... OCTAL-MODE FILE...
    -R: 递归修改权限

chmod [OPTION]... MODE[,MODE]... FILE...
  MODE:
    修改一类用户的所有权限:
        u= g= o= ug= a= u=,g=
    修改一类用户某位或某些位权限
        u+ u-g+ g-o+ o-a+ a-+ -

chmod [OPTION]... --reference=RFILE FILE...
    参考RFILE文件的权限,将FILE的修改为同RFILE

实验

1 删除haha的家目录,恢复之(权限,所有者组,默认数据)

cp -r /etc/skel /home/haha
chown -R haha:haha /home/haha
chmod 700 /home/haha

权限设置示例

chgrp sales testfile
chown root:admins testfile
chmod u+wx,g-r,o=rx file
chmod -R g+rwX /testdir
chmod 600 file
chown mage testfile

新建文件和目录的默认权限

  • umask值可以用来保留在创建文件权限
  • 新建FILE权限: 666-umask

    • 如果所得结果某位存在执行(奇数)权限,则将其权限+1
  • 新建DIR权限: 777-umask
  • 非特权用户umask是002
  • root的umask是022
  • umask: 查看
  • umask#: 设定

    • umask 002
  • umask–S 模式方式显示
  • umask–p 输出可被调用
  • 全局设置:/etc/bashrc 用户设置:~/.bashrc

练习

  • 1、当用户xiaoming对/testdir 目录无执行权限时,意味着无法做哪些操作?
    无法cd进去,无法查看文件,无法修改文件, 如果有目录的读权限可以查看文件列表但是不能查看文件属性
  • 2、当用户xiaoqiang对/testdir 目录无读权限时,意味着无法做哪些操作?
    无法查看文件列表,知道文件名的情况下可以查看文件属性信息和内容,对文件有写权限的时候可以修改文件
  • 3、当用户wangcai 对/testdir 目录无写权限时,该目录下的只读文件file1是否可修改和删除?
    不能(因为对目录没有写权限)
  • 4、当用户wangcai 对/testdir 目录有写和执行权限时,该目录下的只读文件file1是否可修改和删除?
    可以删除但不能修改
  • 5、复制/etc/fstab文件到/var/tmp下,设置文件所有者为wangcai读写权限,所属组为sysadmins组有读写权限,其他人无权限
cp /etc/fstab /var/tmp/
cd wangcai
chown wangcai:sysadmins fstab
chmod o+rw,g+rw,o= fstab
  • 6、误删除了用户wangcai的家目录,请重建并恢复该用户家目录及相应的权限属性
cp -r /etc/skel /home/wangcai
chown -R wangcai:wangcai /home/wangcai
chmod 700 /home/wangcai

可执行文件上SUID权限

SUID 权限就是让命令的发起者拥有命令的所有者的权限

4 代表SUID的权限

  • 任何一个可执行程序文件能不能启动为进程:取决发起者对程序文件是否拥有执行权限
  • 启动为进程之后,其进程的属主为原程序文件的属主
  • SUID只对二进制可执行程序有效
  • SUID设置在目录上无意义
  • 权限设定:
chmod u+s FILE...
chmod 4755 FILE...
chmod u-s FILE...
chmod 0755 FILE...

可执行文件上SGID权限

  • 任何一个可执行程序文件能不能启动为进程:取决发起者对程序文件是否拥有执行权限
  • 启动为进程之后,其进程的属组为原程序文件的属组
  • 权限设定:
chmod g+s FILE...
chmod g-s FILE...

目录上的SGID权限

2 代表GUID的权限

  • 默认情况下,用户创建文件时,其属组为此用户所属的主组
  • 一旦某目录被设定了SGID,则对此目录有写权限的用户在此目录中创建的文件所属的组为此目录的属组
  • 通常用于创建一个协作目录
  • 权限设定:
chmod g+s DIR...
chmod 2755 DIR...
chmod g-s DIR...
chmod 0755 DIR...

Sticky 位

1 代表Sticky的权限

  • 具有写权限的目录通常用户可以删除该目录中的任何文件,无论该文件的权限或拥有权
  • 在目录设置Sticky 位,只有文件的所有者或root可以删除该文件
  • sticky 设置在文件上无意义
  • 权限设定:
chmod o+t DIR...
chmod 1777 DIR...
chmod o-t DIR...
chmod 0755 DIR...
  • 例如:
ls -ld /tmp
drwxrwxrwt 12 root root 4096 Nov 2 15:44 /tmp

特殊权限数字法

  • SUID SGID STICKY
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
  • chmod 4777 /tmp/a.txt

权限位映射

  • SUID: user,占据属主的执行权限位
s: 属主拥有x权限
S:属主没有x权限
  • SGID: group,占据属组的执行权限位
s: group拥有x权限
S:group没有x权限
  • Sticky: other,占据other的执行权限位
t: other拥有x权限
T:other没有x权限

设定文件特定属性

  • chattr +i 不能删除,改名,更改
  • chattr +a 只能追加内容(只支持 echo >> 的追加模式 )
  • chattr +A 禁止文件的读时间戳更新
  • lsattr 显示特定属性

chattr对目录和文件都生效

访问控制列表

  • ACL:Access Control List,实现灵活的权限管理
  • 除了文件的所有者,所属组和其它人,可以对更多的用户设置权限
  • CentOS7默认创建的xfs和ext4文件系统具有ACL功能
  • CentOS7之前版本,默认手工创建的ext4文件系统无ACL功能,需手动增加,转系统时候的分区默认有ACL功能。
tune2fs –o acl /dev/sdb1
mount –o acl /dev/sdb1 /mnt/test

查看有没有acl功能

tune2fs -l /dev/sda3 | grep acl

输入图片说明

ACL权限生效顺序

所有者,(自定义用户,所属组|自定义组) 不能超过mask权限,other

  • ACL生效顺序:所有者,自定义用户,(所属组|自定义组),其他人
  • 为多用户或者组的文件和目录赋予访问权限rwx
mount -o acl /directory
getfacl file |directory
setfacl -m u:wang:rwx file|directory  <==>  setfacl -m wang:rwx file|directory (u可以省略,默认是针对用户的,组要通过g指定)
setfacl -m u:wang:- file|directory
setfacl -m u:wang:--- file|directory
setfacl -m u:wang:000 file|directory
setfacl -m u:wang:0 file|directory
setfacl -m mask::r file|directory   # 相当于 chmod u=r,g=r file|directory
setfacl -Rm g:sales:rwX directory   # g 不能省略,省略 g 就成了对用户设置了 -R表示递归
setfacl -M file.acl file|directory  # 通过文件定义权限(文件的格式就是形如 : u:wang:rwx)
setfacl -m g:salesgroup:rw file|directory
setfacl -m d:u:wang:rx directory    # d 是让directory下的文件或目录默认就有 u:wang:rx 的权限(也就是新建的文件或目录会递归继承)
setfacl -x u:wang file|directory      x 是删除权限
setfacl -X file.acl file|directory

-m 是指原理的基础上修改(添加)权限
--set 是指直接用新的权限覆盖旧的权限

--set

acl 文件中支持多条权限的设置规则

文件名和后缀随便

添加权限 acl 文件格式

删除用户的所有权限 acl 文件格

示例

[root@centos6 test]#ll
total 0
-rw-r--r--. 1 root opts 0 Nov 23 00:53 file1
[root@centos6 test]#setfacl -m u:ming:rw file1  
[root@centos6 test]#
[root@centos6 test]#ll
total 4
-rw-rw-r--+ 1 root opts 0 Nov 23 00:53 file1
[root@centos6 test]#
[root@centos6 test]#getfacl file1   
# file: file1
# owner: root
# group: opts
user::rw-     # 所有者(root)用户的权限
user:ming:rw-
group::r--    # 属组(opts组)的权限
mask::rw-     # chmod 更改的只是这里的权限,会影响除了user和other 之外的所有用户和组的最大权限
other::r--    # other 的权限


设置了ACL之后,户多一个 "+" 号, 通过 ls -l 查看到的租的权限已经不是真正组的权限,而是 mask的权限。 

ACL 中的mask影响的位置

ACL中的mask只影响 所有者和other之外的部分

mask影响的位置

如果对多个组设置了不同的权限,同一个用户同时属于这些组,该用户的权限是这些组的权限的并集

  • ACL文件上的group权限是mask 值(自定义用户,自定义组,拥有组的最大权限),而非传统的组权限
  • getfacl可看到特殊权限:flags
  • 通过ACL赋予目录默认x权限,目录内文件也不会继承x权限
  • base ACL 不能删除
  • setfacl -k dir 删除默认ACL权限 (-k 和 d 是相反的)
  • setfacl –b file1 清除所有ACL权限
  • getfacl file1 | setfacl --set-file=- file2 复制file1的acl权限给file2
  • mask只影响除所有者和other的之外的人和组的最大权限
    Mask需要与用户的权限进行逻辑与运算后,才能变成有限的权限(Effective Permission)
    • 用户或组的设置必须存在于mask权限设定范围内才会生效 setfacl -m mask::rx file
  • --set选项会把原有的ACL项都删除,用新的替代,需要注意的是一定要包含UGO的设置,不能象-m一样只是添加ACL就可以
  • 示例:
setfacl --set u::rw,u:wang:rw,g::r,o::- file1
  • 备份和恢复ACL
主要的文件操作命令cp和mv都支持ACL,只是cp命令需要加上-p 参数。但是tar等常见的备份工具是不会保留目录和文件的ACL信息

getfacl -R /tmp/dir1 > acl.txt
setfacl -R -b /tmp/dir1
setfacl -R --set-file=acl.txt /tmp/dir1  ## 注意:由于acl.txt中保存的是相对路径,所以一定要在相对路径中执行此命令。
setfacl --restore acl.txt    ## 注意:由于acl.txt中保存的是相对路径,所以一定要在相对路径中执行此命令。
getfacl -R /tmp/dir1

清除所有ACL权限

清除所有ACL权限

练习

  • 1、在/testdir/dir里创建的新文件自动属于g1组,组g2的成员如:alice能对这些新文件有读写权限,组g3的成员如:tom只能对新文件有读权限,其它用户(不属于g1,g2,g3)不能访问这个文件夹。
mkdir -p /testdir/dir
groupadd g1; groupadd g2; groupadd g3
useradd -g g2 alice
useradd -g g3 tom

chown :g1 /testdir/dir  # 或 chgrp g1 /testdir/dir
chmod g+s /testdir/dir   # 在/testdir/dir里创建的新文件自动属于g1组

setfacl -m d:g:g2:rw /testdir/dir
setfacl -m d:g:g3:r /testdir/dir
chmod o= /testdir/dir

getfacl -R /testdir/dir

演示

[root@centos6 dir]#rm -fr /testdir/
[root@centos6 dir]#
[root@centos6 dir]#mkdir -p /testdir/dir
[root@centos6 dir]#chown :g1 /testdir/dir
[root@centos6 dir]#ll /testdir/
total 4
drwxr-xr-x. 2 root g1 4096 Nov 23 05:26 dir
[root@centos6 dir]#chmod g+s /testdir/dir 
[root@centos6 dir]#ll /testdir/           
total 4
drwxr-sr-x. 2 root g1 4096 Nov 23 05:26 dir
[root@centos6 dir]#setfacl -m d:g:g2:rw /testdir/dir
[root@centos6 dir]#setfacl -m d:g:g3:r /testdir/dir
[root@centos6 dir]#chmod o= /testdir/dir
[root@centos6 dir]#
[root@centos6 dir]#getfacl -R /testdir/dir
getfacl: Removing leading '/' from absolute path names
# file: testdir/dir
# owner: root
# group: g1
# flags: -s-
user::rwx
group::r-x
other::---
default:user::rwx
default:group::r-x
default:group:g2:rw-
default:group:g3:r--
default:mask::rwx
default:other::r-x

[root@centos6 dir]#
[root@centos6 dir]#
[root@centos6 dir]#cd /testdir/dir/
[root@centos6 dir]#touch f1
[root@centos6 dir]#getfacl f1 
# file: f1
# owner: root
# group: g1
user::rw-
group::r-x                      #effective:r--
group:g2:rw-
group:g3:r--
mask::rw-
other::r--

[root@centos6 dir]#ll /testdir/
total 8
drwxr-s---+ 2 root g1 4096 Nov 23 05:28 dir
[root@centos6 dir]#
  • 2、备份/testdir/dir里所有文件的ACL权限到/root/acl.txt中,清除/testdir/dir中所有ACL权限,最后还原ACL权限
getfacl -R /testdir/dir > /root/acl.txt
setfacl -Rb /testdir/dir 
getfacl -R /testdir/dir 
cd /
setfacl --restore /root/acl.txt
getfacl -R /testdir/dir 
或
setfacl -R --set-file=/root/acl.txt /root/acl.txt
getfacl -R /testdir/dir 

sed 工具(Stream EDitor, 行编辑器)

sed简介

sed是一种流编辑器,它一次处理一行内容。处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。然后读入下行,执行下一个循环。如果没有使诸如‘D’的特殊命令,那会在两个循环之间清空模式空间,但不会清空保留空间。这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。

功能:主要用来自动编辑一个或多个文件,简化对文件的反复操作,编写转换程序等
参考: http://www.gnu.org/software/sed/manual/sed.html

语法

# 用法:
sed [option]... 'script' inputfile...

# 常用选项:
-n:不输出模式空间内容到屏幕,即不自动打印
-e:多点编辑
-f /PATH/SCRIPT_FILE:从指定文件中读取编辑脚本
-r:支持使用扩展正则表达式
-i.bak:备份文件并原处编辑

# script:
'地址命令'

地址定界

# (1) 不给地址:对全文进行处理

# (2) 单地址:
#:指定的行,$:最后一行
/pattern/:被此处模式所能够匹配到的每一行

# (3) 地址范围:
#,#
#,+#
/pat1/,/pat2/
#,/pat1/

# (4) ~:步进
1~2 奇数行
2~2 偶数行

编辑命令

d: 删除模式空间匹配的行,并立即启用下一轮循环
p: 打印当前模式空间的内容,追加到默认输出之后
a: [\]text: 在指定行的后面追加文本(支持使用\n实现多行追加)
i: [\]text: 在指定的行前面插入文本
c: [\]text: 替换为单行或多行文本
w: /path/somefile: 保存模式匹配的行至指定文件
r: /path/somefile: 读取指定文件的文本至模式空间中匹配到的行后.
=: 为模式空间中的行打印行号
!: 模式空间中匹配行取反处理
s///: 查找替换.支持使用其他分隔符, S@@@, s###

替换标记:

g: 行内全局替换
p: 显示替换成功的行
w /PATH/TO/SOMEFILE: 将替换成功的行保存至文件中

sed 示例

sed '2p' /etc/httpd/conf/httpd.conf 
sed -n '2p' /etc/httpd/conf/httpd.conf 
sed -n '1,4p' /etc/httpd/conf/httpd.conf 
sed -n '/root/p' /etc/httpd/conf/httpd.conf 
sed -n '2,/root/p' /etc/httpd/conf/httpd.conf 
sed -n '/^$/=' /etc/httpd/conf/httpd.conf   显示空行行号
sed -n -e '/^$/p' -e '/^$/=' /etc/httpd/conf/httpd.conf 
sed '/root/a\superman' <file>  行后添加
sed '/root/i\superman' <file>  行前添加
sed '/root/c\superman' <file>  代替行
sed '/^$/d' <file>
sed '1,10d' <file>
nl /etc/httpd/conf/httpd.conf | sed '2,5d'
nl /etc/httpd/conf/httpd.conf | sed '2a tea'
sed s/test/mytest/g' <file>
sed -n 's/root/&superman/p' /etc/passwd  单词后
sed -n 's/root/superman&/p' /etc/passwd  单词前
sed -e 's/dog/cat/' -e 's/hi/lo/' pets
sed -i.back 's/dog/cat/g' pets

sed 分组演示,取IP地址(centos7&centos6)

ifconfig eth0 | sed -rn '2s/.*inet (addr:)?(.*)  (Bcast|netmask).*/\2/p'
ifconfig eth0 | sed -n '2p' | sed -rn 's/.*inet (addr:)?(.*)  (Bcast|netmask).*/\2/p'
ifconfig eth0 | sed -n '2p' | sed -r 's/^.*inet(.*addr:)? ?//;s/  (Bcast|netmask).*//'
ifconfig eth0 | sed -n '2p' | sed -re 's/^.*inet(.*addr:)? ?//' -e 's/  (Bcast|netmask).*//'
ifconfig eth0 | sed -n '2p' | sed -r 's/^(.*inet )(addr:)?(.*)[:spcace:]*(Bcast|netmask).*/\3/g'
ifconfig eth0 | sed -n '2p' | sed -r 's#(.*inet (addr:)?)(.*)  (Bcast|netmask).*#\3#g'
ifconfig eth0 | sed -n '2p' | sed -r 's#[[:space:][:alpha:]:]+(.*)  (Bcast|netmask).*#\1#g'

awk 取IP地址

ifconfig eth0 | awk -F "[ ]+" 'NR==2 {print $3}'

修改 http 配置文件

1.单行删除注释
grep 'ServerName www.example.com' httpd.conf 
sed -i '/ServerName www.example.com/ s/#//' httpd.conf 
grep 'ServerName www.example.com' httpd.conf 
2.单行增加注释
grep 'ServerName www.example.com' httpd.conf 
sed -i '/ServerName www.example.com/ s/\(.*\)/#\1/' httpd.conf
grep 'ServerName www.example.com' httpd.conf 
3.多行删除注释
sed -i '/^#<Directory \/>/,/<\/Directory>/ s/#//g'  httpd.conf
grep -A 4 '<Directory />' httpd.conf 
4.多行增加注释
sed -i '/^<Directory \/>/,/<\/Directory>/ s/^/#/g'  httpd.conf
grep -A 4 '<Directory />' httpd.conf 

扩展正则表达式

.
[^wang.]
abc*
.*
abc?  == ab  abc
abc+  == abc abccccc
a{n}
abc{n}
a{n,}
a{,n}
a{m,n}

a|b
a|bxy
(a|b)xy  == axy  bxy

位置铆钉

^    行首
$    行尾
\< 或 \b   单词的词首
\> 或 \b   单词的词尾
^[[:space:]]*$   一行中全是空格

sed中使用变量

sed 中使用变量 要使用3个单引号 '''$USER'''
sed 's/bash/'''$USER'''/g' test

SED高级编辑命令

P: 打印模式空间开端至\n 内容,并追加到默认输出之前
h: 把模式空间中的内容覆盖至保持空间
H: 把模式空间中的内容追加至保持空间中
g: 从保持空间取出数据覆盖至模式空间
G: 从保持空间取出数据追加至模式空间
x: 把模式空间中的内容与保持空间中的内容进行互换
n: 读取匹配到的行的下一覆盖至模式空间
N: 读取匹配到的行的下一行追加至模式空间
d: 删除模式空间中的行
D: 如果模式空间包含换行符,则删除直到第一个换行符的模式空间中的文本,
   并不会读取新的输入行,而使用合成的模式空间重新启动循环。
   如果模式空间不包含换行符,则会像发出d命令那样启动正常的新循环

示例:【提示: 涉及到空间切换的时候会有隐式打印】

sed -n 'n;p' file    # 打印偶数行
sed -n 'N;p' file    # 打印所有行
sed '1!G;h;$!d' file # 倒序显示文本内容,$!d是为了暂时清除模式空间中的内容,因为不加 -n是默认打印模式空间的内容,就会将每次迭代的待续都打印出来。
sed 'N;D' scm        # 打印最后一行
sed '$!N;$!D' file   # 打印最后两行
sed '$!d' file       # 打印最后一行【取费要放在匹配的后面】
sed 'G' file         # 在每行的后面打印空行(涉及到空间切换的时候会有隐式打印)
sed 'g' file         # 打印与文件行数相同的空行
sed '/^$/d;G' file   # 在每行的后面打印空行(涉及到空间切换的时候会有隐式打印)
sed 'n;d' file       # 打印奇数行(注意d这一步只对最新读入的行操作)
sed -n '1!G;h;$p' file   # 倒序打印

通过体换的方式争端修改配置文件

[root@linux-node1 ~]# cat test
1{
    11111
};
2{
    22222
};
3{
    33333
};
[root@linux-node1 ~]# sed -n  '/^2/,/};/p' test
2{
    22222
};
[root@linux-node1 ~]# 
[root@linux-node1 ~]# sed -e  '/^2/,/};/c\2{\n    44444\n};\ntest' test
1{
    11111
};
2{
    44444
};
test
3{
    33333
};
[root@linux-node1 ~]# 
[root@linux-node1 ~]# sed -i '/^2/,/};/c\2{\n    44444\n};\ntest' test
[root@linux-node1 ~]# cat test
1{
    11111
};
2{
    44444
};
test
3{
    33333
};
[root@linux-node1 ~]#

取系统版本号

[root@linux-node1 ~]# sed -rn 's/.*release ([^.]+).*/\1/p' /etc/redhat-release 
7
[root@linux-node1 ~]#

取文件夹的基名和文件夹名

[root@linux-node1 ~]# echo "/etc" | sed -rn 's#(.*/)(.*)/?#\1#p'
/
[root@linux-node1 ~]# echo "/etc" | sed -rn 's#(.*/)(.*)/?#\2#p'
etc
[root@linux-node1 ~]# echo "/etc/sysconfig/network-scripts" | sed -rn 's#(.*/)(.*)/?#\1#p'
/etc/sysconfig/
[root@linux-node1 ~]# echo "/etc/sysconfig/network-scripts" | sed -rn 's#(.*/)(.*)/?#\2#p'
network-scripts
[root@linux-node1 ~]# 

ldd 显示命令依赖的库文件

语法

ldd 命令全路径

演示

[root@centos6 test]#ldd /bin/cat
        linux-vdso.so.1 =>  (0x00007ffdba7be000)
        libc.so.6 => /lib64/libc.so.6 (0x0000003a29e00000)
        /lib64/ld-linux-x86-64.so.2 (0x0000003a29a00000)

ldconfig

管理及查看本机装载的库文件
ldconfig 加载库文件
/sbin/ldconfig -p: 显示本机已经缓存的所有可用库文件名及文件路径映射关系
配置文件:/etc/ld.so.conf, /etc/ld.so.conf.d/*.conf
缓存文件:/etc/ld.so.cache

语法

Usage: ldconfig [OPTION...]
Configure Dynamic Linker Run Time Bindings.

  -c, --format=FORMAT        Format to use: new, old or compat (default)
  -C CACHE                   Use CACHE as cache file
  -f CONF                    Use CONF as configuration file
  -i, --ignore-aux-cache     Ignore auxiliary cache file
  -l                         Manually link individual libraries.
  -n                         Only process directories specified on the command
                             line.  Don't build cache.
  -N                         Don't build cache
  -p, --print-cache          Print cache
  -r ROOT                    Change to and use ROOT as root directory
  -v, --verbose              Generate verbose messages
  -X                         Don't generate links
  -?, --help                 Give this help list
      --usage                Give a short usage message
  -V, --version              Print program version

演示

[root@centos6 test]#ldconfig -p | wc -l
1139

rpm 包管理器

用法

安装:
rpm {-i|--install} [install-options] PACKAGE_FILE…
-v:verbose
-vv:
-h:以#显示程序包管理执行进度
rpm -ivh /PATH/TO/PACKAGE_FILE ...

rpm包安装

[install-options]
--test:测试安装,但不真正执行安装,即dry run模式
--nodeps:忽略依赖关系
--replacepkgs | replacefiles  # 用于rpm安装的部分文件丢失;如果不指定--replacepkgs,就会提示软件已经安装
--nosignature:不检查来源合法性
--nodigest:不检查包完整性
--noscripts:不执行程序包脚本
    %pre:安装前脚本; --nopre
    %post:安装后脚本; --nopost
    %preun:卸载前脚本; --nopreun
    %postun:卸载后脚本; --nopostun

rpm包升级

升级:
rpm {-U|--upgrade} [install-options] PACKAGE_FILE...
rpm {-F|--freshen} [install-options] PACKAGE_FILE...
    upgrade:安装有旧版程序包,则"升级"
          如果不存在旧版程序包,则"安装"
    freshen:安装有旧版程序包,则"升级"
          如果不存在旧版程序包,则不执行升级操作
    rpm -Uvh PACKAGE_FILE ...
    rpm -Fvh PACKAGE_FILE ...
    --oldpackage:降级
    --force: 强制安装

包查询

rpm {-q|--query} [select-options] [query-options]

[select-options]
-a:所有包
-f:查看指定的文件由哪个程序包安装生成
-p rpmfile:针对尚未安装的程序包文件做查询操作
--whatprovides CAPABILITY:查询指定的CAPABILITY由哪个包所提供
--whatrequires CAPABILITY:查询指定的CAPABILITY被哪个包所依赖

rpm -q --whatprovides bash
rpm -q --whatrequires bash

rpm2cpio 包文件|cpio –itv 预览包内文件
rpm2cpio 包文件|cpio –id "*.conf" 释放包内文件

示例
rpm2cpio tree-1.5.3-3.el6.x86_64.rpm | cpio -id ./usr/*

[query-options]
--changelog:查询rpm包的changelog
-c:查询程序的配置文件
-d:查询程序的文档
-i:information
-l:查看指定的程序包安装后生成的所有文件
--scripts:程序包自带的脚本
--provides:列出指定程序包所提供的CAPABILITY
-R:查询指定的程序包所依赖的CAPABILITY

常用查询用法:
-qi PACKAGE, -qf FILE, -qc PACKAGE, -ql PACKAGE, -qd PACKAGE
-qpi PACKAGE_FILE, -qpl PACKAGE_FILE, ...
-qa, -qp --scripts PACKAGE_FILE

包卸载

rpm {-e|--erase} [--allmatches] [--nodeps] [--noscripts] [--notriggers] [--test] PACKAGE_NAME ...

--allmatches  匹配到的所有版本的包全部卸载
--nodeps  忽略依赖性(有可能卸载不干净,类似安装的时候有同样的选项)
--noscripts  卸载的时候不运行rpm中的卸载相关的脚本
--notriggers  触发器
--test  假装卸载


提示:
卸载软件的时候,会将原来的配置文件命名为 .conf.rpmsave的备份文件。

包校验

rpm {-V|--verify} [select-options] [verify-options]

S file Size differs
M Mode differs (includes permissions and file type)
5 digest (formerly MD5 sum) differs
D Device major/minor number mismatch
L readLink(2) path mismatch
U User ownership differs
G Group ownership differs
T mTime differs
P capabilities differ

示例:
[root@centos7 ~]#rpm -V centos-release
S.5....T.  c /etc/issue
上面的例子中,S表示文件大小变化了,5 表示文件内容发生变化了,T表示文件的修改时间变化了。

#包来源合法性验正及完整性验正
完整性验正:SHA256
来源合法性验正:RSA

#公钥加密
对称加密:加密、解密使用同一密钥
非对称加密:密钥是成对儿的
public key: 公钥,公开所有人
secret key: 私钥, 不能公开

#导入所需要公钥
rpm -K|checksig rpmfile 检查包的完整性和签名
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
CentOS 7发行版光盘提供:RPM-GPG-KEY-CentOS-7
rpm -qa "gpg-pubkey*"

[root@centos7 ~]#rpm -qa "gpg-pubkey*"
gpg-pubkey-f4a80eb5-53a7ff4b

#卸载前面导入的公钥 gpg-pubkey-f4a80eb5-53a7ff4b
rpm -e gpg-pubkey-f4a80eb5-53a7ff4b

rpm数据库

#数据库重建:
/var/lib/rpm

#rpm {--initdb|--rebuilddb}
initdb: 初始化
    如果事先不存在数据库,则新建之
    否则,不执行任何操作
rebuilddb:重建已安装的包头的数据库索引目录

yum

CentOS: yum, dnf(未来的管理器)

YUM: Yellowdog Update Modifier,rpm的前端程序,可解决软件包相关依赖性,可在多个库之间定位软件包,up2date的替代工具
yum repository: yum repo,存储了众多rpm包,以及包的相关的元数据文件(放置于特定目录repodata下)
文件服务器:
http://
https://
ftp://  <-- ftp路径
file://   <-- 本地路径

yum配置文件

#yum客户端配置文件:
/etc/yum.conf:为所有仓库提供公共配置
/etc/yum.repos.d/*.repo:为仓库的指向提供配置

#仓库指向的定义:
[repositoryID]   # 仓库的ID,不能有空格
name=Some name for this repository  # 仓库的名字
baseurl=url1://path/to/repository/  # 这里的路径永远是repodata目录的父目录,baseurl可以有多个,实现高可用,但是要配合后面的failovermethod
        url2://path/to/repository/  # url可以是其中一种:http https ftp file
enabled={1|0}
gpgcheck={1|0}
gpgkey=URL
enablegroups={1|0}
failovermethod={roundrobin|priority}
    roundrobin:意为随机挑选,默认值
    priority:按顺序访问
cost=<优先级> 默认为1000

#baseurl 还可以换成 mirrorlist=文件,文件中存放的是baseurl的路径
mirrorlist=mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra

#光盘的 repo文件示例;base.repo
[base]
name=CentOS7-base
baseurl=file:///misc/cd
gpgcheck=1
gpgkey=file:///misc/cd/RPM-GPG-KEY-CentOS-7

yum仓库

#yum的repo配置文件中可用的变量:
$releasever:当前OS的发行版的主版本号
$arch:平台,i386,i486,i586,x86_64等
$basearch:基础平台;i386, x86_64
$YUM0-$YUM9:自定义变量

#实例:
http://server/centos/$releasever/$basearch/
http://server/centos/7/x86_64
http://server/centos/6/i384

yum命令

#yum命令的用法:
yum [options] [command] [package ...]
#显示仓库列表:
yum repolist [all|enabled|disabled]
#显示程序包:
yum list
yum list [all | glob_exp1] [glob_exp2] [...]
yum list {available|installed|updates} [glob_exp1] [...]
#安装程序包:
yum install package1 [package2] [...]
yum reinstall package1 [package2] [...] (重新安装)
#升级程序包:
yum update [package1] [package2] [...]
yum downgrade package1 [package2] [...] (降级)
#检查可用升级:
yum check-update
#卸载程序包:(不会卸载被其他软件依赖的包)
yum remove | erase package1 [package2] [...]
#查看程序包information:
yum info [...]
#查看指定的特性(可以是某文件)是由哪个程序包所提供:
yum provides | whatprovides feature1 [feature2] [...]
#清理本地缓存:
清除/var/cache/yum/$basearch/$releasever缓存
yum clean [ packages | metadata | expire-cache | rpmdb | plugins | all ]
#构建缓存:
yum makecache
#搜索:yum search string1 [string2] [...]
以指定的关键字搜索程序包名及summary信息
#查看指定包所依赖的capabilities:
yum deplist package1 [package2] [...]
#查看yum事务历史:
yum history [info|list|packages-list|packages-info|
summary|addon-info|redo|undo|
rollback|new|sync|stats]
yum history
yum history info 6
yum history undo 6
#日志 :/var/log/yum.log

#安装及升级本地程序包:
yum localinstall rpmfile1 [rpmfile2] [...]
(已经用install替代)
yum localupdate rpmfile1 [rpmfile2] [...]
(已经用update替代)
#包组管理的相关命令:
yum groupinstall group1 [group2] [...]
yum groupupdate group1 [group2] [...]
yum grouplist [hidden] [groupwildcard] [...]
yum groupremove group1 [group2] [...]
yum groupinfo group1 [...]  # 在centos7上 没有安装的包前面有 + 号,已经安装的包前面有 = 号,没有任何符号的包是在安装系统的时候安装的

#yum的命令行选项:
--nogpgcheck:禁止进行gpg check
-y: 自动回答为"yes"
-q:静默模式
--disablerepo=repoidglob:临时禁用此处指定的repo
--enablerepo=repoidglob:临时启用此处指定的repo
--noplugins:禁用所有插件

系统光盘yum仓库

#系统安装光盘作为本地yum仓库:
(1) 挂载光盘至某目录,例如/mnt/cdrom
mount /dev/cdrom /mnt/cdrom
(2) 创建配置文件
[CentOS7]
name=
baseurl=   # baseurl就是 repodata 的父目录的地址
gpgcheck=
enabled=

创建yum仓库

createrepo [options] <directory>

createrepo --basedir=./ -d /app
--basedir  # rpm包的存放路径
-d  # 生成的 repodata 目录的父目录路径,也就是将来作为.repo文件的baseurl地址

提示:
--basedir 和 repodata 目录的父目录可以不在同一个路径下,
但是一旦创建 repodata 后就不能变了。

程序包编译

httpd_install.sh

#!/bin/bash
# *****************************************************
# author     : shchangming
# date       : 2018-06-06
# QQ         : 414945814
# Description: this script is to install http one shoot
# *****************************************************

CENTOS_VER=`egrep -wo '[0-9]+' /etc/centos-release | head -n 1`

httpd_list() {
echo "
which httpd version would you like to install:
**********************************************
httpd-2.2.18
httpd-2.2.20
httpd-2.2.26
httpd-2.4.37
or you can input other version
quit | q
**********************************************
"
}

BASE_DIR="/web"

check_pre() {
    if [ -d ${BASE_DIR}/${1} ];then
        echo "${1} has been installed!"
        exit
    fi
}

change_yum() {
    mkdir /etc/yum.repos.d/old
    mv /etc/yum.repos.d/*.repo  /etc/yum.repos.d/old
    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-${CENTOS_VER}.repo
    wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-${CENTOS_VER}.repo
}

env_pre() {
    LISTNO="${1}"
    ### 安装其他必要的依赖
    yum clean all
    yum groupinstall "Development Tools" -y
    DEP_LIST1="gcc glibc apr-devel apr-util-devel pcre-devel openssl-devel expat-devel make"
    DEP_LIST2="gcc glibc pcre-devel openssl-devel expat-devel make"
    if [ $LISTNO == "1" ];then
        for dep in "${DEP_LIST1}";do
                rpm -q "${dep}" &> /dev/null || yum install $dep -y
        done
    elif [ $LISTNO == "2" ];then
                for dep in "${DEP_LIST2}";do
                        rpm -q "${dep}" &> /dev/null || yum install $dep -y
                done
    fi
}

get_http_package() {
    HTTP_VER=$1
    [ -f ${HTTP_VER}.tar.bz2 ] || wget -t 5 -w 10 https://archive.apache.org/dist/httpd/${HTTP_VER}.tar.bz2
    tar xf ${HTTP_VER}.tar.bz2 &>/dev/null || exit
}

install() {
    INSTALL_DIR="$1"
    WITH_APR="$2"
    [ ! -d ${BASE_DIR} ] && mkdir -p ${BASE_DIR}
    ./configure --prefix=${BASE_DIR}/${INSTALL_DIR} \
    --enable-so \
    --enable-ssl \
    --enable-cgi \
    --enable-rewrite \
    --with-zlib \
    --with-pcre \
    --enable-modules=most \
    --enable-mpms-shared=all \
    --with-mpm=prefork ${WITH_APR} && \
    make -j 4 && make install && \
    ln -s ${INSTALL_DIR} ${BASE_DIR}/httpd
    id apache || useradd -r -s /sbin/nologin apache
    cp ${BASE_DIR}/httpd/conf/httpd.conf{,.bak}
    sed -ri "/^(User|Group)/s/daemon/apache/" ${BASE_DIR}/httpd/conf/httpd.conf
    sed -ri "/^#ServerName/s/^#//" ${BASE_DIR}/httpd/conf/httpd.conf
}

get_httpd_init() {
    HTTPD_INIT="$1"
    if [ -f ${HTTPD_INIT} ];then
        if [ ! -f /etc/init.d/${HTTPD_INIT} ];then
            \cp ${HTTPD_INIT} /etc/init.d/${HTTPD_INIT}
            chmod +x /etc/init.d/${HTTPD_INIT}
            chkconfig --add ${HTTPD_INIT} ;chkconfig ${HTTPD_INIT} on
            return 0
        else
            echo "/etc/init.d/${HTTPD_INIT} exsit." ;return 1
        fi
    else
        echo "${HTTPD_INIT} not found,make it by yourself." ;return 1
    fi
}

main() {
httpd_list
read -p "please select version:"  http_version
case "$1" in
    6)
        case "$http_version" in
            httpd-2.4.[2-3][6-7])
                check_pre $http_version
                change_yum
                env_pre 2
                get_http_package $http_version
                APR_DEPS="apr-1.6.5 apr-util-1.6.1"
                for apr_dep in ${APR_DEPS};do
                    [ -f ${apr_dep}.tar.bz2 ] || wget -t 5 -w 10 http://mirrors.tuna.tsinghua.edu.cn/apache/apr/${apr_dep}.tar.bz2
                    tar xf ${apr_dep}.tar.bz2 &>/dev/null
                    if [ $? -ne 0 ];then
                        echo "${apr_dep}.tar.bz2 download failed";exit
                    fi
                done
                cp -av apr-1.6.5 ${http_version}/srclib/apr
                cp -av apr-util-1.6.1 ${http_version}/srclib/apr-util
                cd $http_version
                install $http_version --with-included-apr
                cd ../
                echo export PATH=${BASE_DIR}/httpd/bin:'$PATH' >  /etc/profile.d/httpd24.sh
                . /etc/profile.d/httpd24.sh
                grep "MANPATH ${BASE_DIR}/httpd/man" /etc/man.config || echo "MANPATH ${BASE_DIR}/httpd/man" >> /etc/man.config
                get_httpd_init httpd && /etc/init.d/httpd start
                ;;

            httpd-2.2.[1-2-3][0-1-2-3-4-5-6-7-8-9])
                check_pre $http_version
                change_yum
                env_pre 1
                get_http_package $http_version && cd $http_version
                install $http_version
                cd ../
                echo export PATH=${BASE_DIR}/httpd/bin:'$PATH' >  /etc/profile.d/httpd22.sh
                . /etc/profile.d/httpd22.sh
                grep "MANPATH ${BASE_DIR}/httpd/man" /etc/man.config || echo "MANPATH ${BASE_DIR}/httpd/man" >> /etc/man.config
                get_httpd_init httpd && /etc/init.d/httpd start
                ;;

            quit|q)
                echo "Bye" && exit
                ;;

            *)
                echo "do not support this version" && exit
                ;;
        esac
        ;;
    7)
        case "$http_version" in
            httpd-2.2.[2][6-7-8-9]|httpd-2.4.[1-2-3-4][0-1-2-3-4-5-6-7-8-9])
                check_pre $http_version
                change_yum
                env_pre 1
                get_http_package $http_version && cd $http_version
                install $http_version
                cd ../
                echo export PATH=${BASE_DIR}/httpd/bin:'$PATH' >  /etc/profile.d/httpd24.sh
                . /etc/profile.d/httpd24.sh
                grep "MANDATORY_MANPATH ${BASE_DIR}/httpd/man" /etc/man_db.conf || echo "MANDATORY_MANPATH ${BASE_DIR}/httpd/man" >> /etc/man_db.conf 
                httpd -t && httpd
                ;;

            quit|q)
                echo "Bye" && exit
                ;;

            *)
                echo "do not support this version" && exit
                ;;
        esac
esac

}
main $CENTOS_VER

练习

1、查询命令java来自于哪个rpm包

[root@centos6 ~]#rpm -qf java
error: file /root/java: No such file or directory
[root@centos6 ~]#ll `which java` 
lrwxrwxrwx. 1 root root 22 Nov  9 07:16 /usr/bin/java -> /etc/alternatives/java
[root@centos6 ~]#rpm -qf  /etc/alternatives
chkconfig-1.3.49.5-1.el6.x86_64

2、yum的配置和使用,包括yum仓库的创建
3、编写系统初始化脚本reset.sh,包括别名,提示符颜色,yum仓库配置文件,安装tree,ftp,lftp,telnet等包
4、在CentOS6上编译安装apache 2.2源码包,并启动此服务
5、在CentOS7上编译安装apache 2.4源码包,并启动此服务
6、第4,5题写成脚本 : httpd 一键编译安装脚本(centos6&7_httpd2.2&2.4)https://www.cnblogs.com/shichangming/p/10153464.html
7、rpm -e rpm --nodeps 删除rpm包,恢复之

# === 方法1:光盘引导救援模式 ===
1. 光盘引导救援模式
2. 挂载光盘,将 mount_point/Packages/rpm-4.11.3-25.el7.x86_64.rpm 拷贝到 /mnt/sysimage/app
3. cd /mnt/sysimage/app
4. rpm2cpio ./rpm-4.11.3-25.el7.x86_64.rpm | cpio -tv | less  # 查看
5. rpm2cpio ./rpm-4.11.3-25.el7.x86_64.rpm | cpio -id ./{bin,usr}/*  # 将必要的包解压出来
6. 重启系统
7. 在CRT上操作
cp /app/bin/rpm /bin/
cp /app/usr/bin/* /usr/bin/
cp /app/usr/lib/rpm/* /usr/lib/rpm
cp /app/usr/lib/tmpfiles.d/rpm.conf /usr/lib/tmpfiles.d/
8. 检查rpm命令的使用
which rpm
rpm -ql tree
rpm -e tree
yum install tree
yum install rpm # 最后建议使用此条命令重新安装一下rpm

# === 方法2:在其他机器上解压后scp到故障机器上 ===
# ***在有rpm的机器上的操作***
1. 在其他机器上,下载 rpm-4.11.3-25.el7.x86_64.rpm 包,
2. rpm2cpio ./rpm-4.11.3-25.el7.x86_64.rpm | cpio -tv | less  # 查看
3. rpm2cpio ./rpm-4.11.3-25.el7.x86_64.rpm | cpio -id ./{bin,usr}/*  # 将必要的包解压出来
4. scp 必要的包到故障机器上
scp /app/bin/rpm 192.168.27.7:/bin/
scp /app/usr/bin/* 192.168.27.7:/usr/bin/
scp -r /app/usr/lib/rpm/* 192.168.27.7:/usr/lib/rpm/  # scp 不会覆盖目的主机上已经有的不同名的文件,只会覆盖同名的文件。
scp /app/usr/lib/tmpfiles.d/rpm.conf 192.168.27.7:/usr/lib/tmpfiles.d/
# ***在故障的机器上的操作***
5. 检查rpm命令的使用
which rpm
rpm -ql tree
rpm -e tree
yum install tree
yum install rpm # 最后建议使用此条命令重新安装一下rpm

本文链接:https://www.cnblogs.com/shichangming/p/10200344.html

猜你喜欢

转载自www.cnblogs.com/shichangming/p/10200344.html