欢迎查看zhaojiedi1992的linux学习笔记

我自己在马哥教育培训机构的linux学习笔记

马哥教育内部讲义

01 LINUX简介

1.1 操作系统与硬件

分层结构如下:

  • 硬件
  • 内核
  • 应用程序

1.2 终端的概念

概念: 是一个或者多个设备的组合。

分类:

物理终端
本机自带的,显示器,键盘和鼠标等,表示为”/dev/control”。
虚拟终端
系统提供的终端(软件实现),表示为”/dev/tty#”。
图形终端
附加在物理终端之上,用软件方式实现的终端,提供图形界面。
伪终端
图形界面下打开的命令行接口,还有基于远程协议打开的命令行界面,表示为”/dev/pts#”。

查看当前的登陆的终端类型:

[root@mail ~]# tty
/dev/pts/2

交互式程序分类

GUI
图形化界面(GNOME,KDE,XFCE)
CLI
命令行界面

查看当前的shell类型

[root@mail ~]# echo $SHELL
/bin/bash

查看系统支持的所有shell类型

[root@mail ~]# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin
/bin/tcsh
/bin/csh

1.3 命令提示符

“[root@mail ~]#” 我们成为PS1,设置我们使用命令的前缀的。

查看当前的PS1设置

[root@mail ~]# echo $PS1
[\u@\h \W]\$

详细的PS1设置可以通过`man bash |grep PS1 -A 40`获得

\a     an ASCII bell character (07)
\d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
\D{format}
       the format is passed to strftime(3) and the result  is  inserted
       into the prompt string; an empty format results in a locale-spe‐
       cific time representation.  The braces are required
\e     an ASCII escape character (033)
\h     the hostname up to the first '.' 短主机名字
\H     the hostname 全主机名
\j     the number of jobs currently managed by the shell
\l     the basename of the shell's terminal device name
\n     newline
\r     carriage return
\s     the name of the shell, the basename of $0 (the portion following
       the final slash)
\t     the current time in 24-hour HH:MM:SS format 24小时的格式
\T     the current time in 12-hour HH:MM:SS format 24小时的格式
\@     the current time in 12-hour am/pm format    12小时的上下午格式
\A     the current time in 24-hour HH:MM format    24的时分没秒的格式
\u     the username of the current user   用户名
\v     the version of bash (e.g., 2.00)   bash的版本
\V     the release of bash, version + patch level (e.g., 2.00.0) 补丁版本
\w     the  current  working  directory,  with $HOME abbreviated with a
       tilde (uses the value of the PROMPT_DIRTRIM variable) 长工作目录名字
\W     the basename of the current working directory, with $HOME abbre‐
       viated with a tilde  短工作目录名字
\!     the history number of this command 当前命令的历史号
\#     the command number of this command 命令提示符,表示管理员和普通用户的
\$     if the effective UID is 0, a #, otherwise a $ 用户的uid
\nnn   the character corresponding to the octal number nnn
\\     a backslash
\[     begin a sequence of non-printing characters, which could be used
       to embed a terminal control sequence into the prompt
\]     end a sequence of non-printing characters

查看命令对应的执行程序全路径

[root@mail user1]# which ls
alias ls='ls --color=auto'
  /usr/bin/ls
[root@mail user1]# which ls --skip-alias
/usr/bin/ls

查看命令帮助文档位置

[root@mail user1]# whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz /usr/share/man/man1p/ls.1p.gz

shell命令分类

内建命令
由shell自带。
外部命令
某路径下对i用那个的可执行程序文件。

查看命令类型

[root@mail user1]# type cd
cd is a shell builtin
[root@mail user1]# type service
service is /usr/sbin/service

1.4 文件系统

文件系统特性

  • 文件名区分大小写
  • 文件名除了`/`的任意字符都可以,不建议特殊字符
  • 文件名长度不能超过255字符
  • 所有`.`开头的文件都是隐藏文件

路径分类:

  • 绝对路径: 从根目录开始的路径
  • 相对路径: 从当前目录开始的路径

LINUX命令获取帮助方式

  1. COMMAND –help
  2. man
  3. info
  4. 程序自身的帮助文档,如README,INSTALL,CHANGELOG.
  5. 程序的官方文档
  6. 发行版的官方文档
  7. GOOGLE

1.5 基础命令学习

1.5.1 hash命令学习
[root@mail user1]# help hash
hash: hash [-lr] [-p pathname] [-dt] [name ...]
    Remember or display program locations.
    Options:
      -d              forget the remembered location of each NAME 清空指定的命令hash
      -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     清空所有命令的hash
      -t              print the remembered location of each NAME, preceding
        each location with the corresponding NAME if multiple
        NAMEs are given 打印hash记录的命令位置
1.5.2 history命令学习
[root@mail user1]# help history
history: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]
    Display or manipulate the history list.

    Display the history list with line numbers, prefixing each modified
    entry with a '*'.  An argument of N lists only the last N entries.

    Options:
      -c      clear the history list by deleting all of the entries 清空命令历史
      -d offset       delete the history entry at offset OFFSET. 删除指定位置的命令历史

      -a      append history lines from this session to the history file 追加历史行到历史文件中
      -n      read all history lines not already read from the history file 从历史文件中读取所有命令历史
      -r      read the history file and append the contents to the history
      list 读取所有命令历史文件追加history 列表中
      -w      write the current history to the history file
      and append them to the history list 写当前的历史记录到文件中去

      -p      perform history expansion on each ARG and display the result
      without storing it in the history list
      -s      append the ARGs to the history list as a single entry

    If FILENAME is given, it is used as the history file.  Otherwise,
    if $HISTFILE has a value, that is used, else ~/.bash_history.

    If the $HISTTIMEFORMAT variable is set and not null, its value is used
    as a format string for strftime(3) to print the time stamp associated
    with each displayed history entry.  No time stamps are printed otherwise.
1.5.3查询命令的所属章节
[root@mail user1]# whatis ls
ls (1)               - list directory contents
ls (1p)              - list directory contents
[root@mail user1]# man 1 ls
1.5.4 命令的分类
  1. 用户命令
  2. 系统调用
  3. 库调用
  4. 设备及特殊文件
  5. 配置文件
  6. 游戏
  7. 杂项
  8. 管理命令
1.5.5 man文档的配置文件
  • centos6: “/etc/man.config”
  • centos7: “/etc/man_db.conf”
1.5.6 man手册段落含义
  • name: 命令的名字或简要说明
  • description: 命令功能的详细描述
  • options: 支持的选项
  • sysnopsis: 使用格式
  • examples: 使用样例
  • notes:相关的注意事项
  • files:先关的配置文件
  • see also:先关的参考

1.6 练习

1.6.1 date命令使用
NAME
      date - print or set the system date and time 打印或者设置日期

SYNOPSIS
      date [OPTION]... [+FORMAT] 打印功能
      date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] 设置日期

DESCRIPTION
      Display the current time in the given FORMAT, or set the system date.

      Mandatory arguments to long options are mandatory for short options too.

      -d, --date=STRING
              display time described by STRING, not 'now'

      -f, --file=DATEFILE
              like --date once for each line of DATEFILE

      -I[TIMESPEC], --iso-8601[=TIMESPEC]
              output  date/time  in  ISO  8601 format.  TIMESPEC='date' for date only
              (the default), 'hours', 'minutes', 'seconds', or 'ns' for date and time
              to the indicated precision.

      -r, --reference=FILE
              display the last modification time of FILE

      -R, --rfc-2822
              output  date  and  time  in RFC 2822 format.  Example: Mon, 07 Aug 2006
              12:34:56 -0600

      --rfc-3339=TIMESPEC
              output date and time in RFC 3339 format.   TIMESPEC='date',  'seconds',
              or  'ns'  for  date and time to the indicated precision.  Date and time
              components are separated by a single space: 2006-08-07 12:34:56-06:00

      -s, --set=STRING
              set time described by STRING

      -u, --utc, --universal
              print or set Coordinated Universal Time (UTC)

      --help display this help and exit

      --version
              output version information and exit

      FORMAT controls the output.  Interpreted sequences are:

      %%     a literal % 显示百分号

      %a     locale's abbreviated weekday name (e.g., Sun) 显示星期简单名字

      %A     locale's full weekday name (e.g., Sunday) 显示星期长名字

      %b     locale's abbreviated month name (e.g., Jan)显示月份短名字

      %B     locale's full month name (e.g., January) 显示月份长名字

      %c     locale's date and time (e.g., Thu Mar  3 23:05:25 2005)

      %C     century; like %Y, except omit last two digits (e.g., 20)显示世纪

      %d     day of month (e.g., 01)显示日

      %D     date; same as %m/%d/%y    月日年

      %e     day of month, space padded; same as %_d 带空格填充的月

      %F     full date; same as %Y-%m-%d 年月日

      %g     last two digits of year of ISO week number (see %G)

      %G     year of ISO week number (see %V); normally useful only with %V

      %h     same as %b

      %H     hour (00..23) 24小时

      %I     hour (01..12) 12小时

      %j     day of year (001..366)年内日

      %k     hour, space padded ( 0..23); same as %_H 带空格的24小时

      %l     hour, space padded ( 1..12); same as %_I 带空格的12小时

      %m     month (01..12) 月

      %M     minute (00..59)分钟

      %n     a newline 空行

      %N     nanoseconds (000000000..999999999)

      %p     locale's equivalent of either AM or PM; blank if not known 上午下午

      %P     like %p, but lower case 小写的上下午

      %r     locale's 12-hour clock time (e.g., 11:11:04 PM)

      %R     24-hour hour and minute; same as %H:%M 小时和分钟的

      %s     seconds since 1970-01-01 00:00:00 UTC  总秒数从70年开始

      %S     second (00..60)秒

      %t     a tab   制表符

      %T     time; same as %H:%M:%S  时分秒

      %u     day of week (1..7); 1 is Monday 指定日期在一周中是第几天

      %U     week number of year, with Sunday as first day of week (00..53) 指定日期在这年中是第几周

      %V     ISO week number, with Monday as first day of week (01..53)

      %w     day of week (0..6); 0 is Sunday 指定日期在一周中是第几天

      %W     week number of year, with Monday as first day of week (00..53)

      %x     locale's date representation (e.g., 12/31/99)

      %X     locale's time representation (e.g., 23:13:48)

      %y     last two digits of year (00..99) 2位数字的年

      %Y     year 年

      %z     +hhmm numeric time zone (e.g., -0400)

      %:z    +hh:mm numeric time zone (e.g., -04:00)

      %::z   +hh:mm:ss numeric time zone (e.g., -04:00:00)

      %:::z  numeric time zone with : to necessary precision (e.g., -04, +05:30)

      %Z     alphabetic time zone abbreviation (e.g., EDT)

      By default, date pads numeric fields  with  zeroes.   The  following  optional
      flags may follow '%':

      -      (hyphen) do not pad the field

      _      (underscore) pad with spaces

      0      (zero) pad with zeros

      ^      use upper case if possible

      #      use opposite case if possible

date显示和修改日期

[root@mail ~]# date '+%Y-%m-%d %H:%M:%S'
2017-11-06 09:15:34
[root@mail ~]# date 120108022012.59
Sat Dec  1 08:02:59 CST 2012
[root@mail ~]# date '+%Y-%m-%d %H:%M:%S'
2012-12-01 08:03:23

时钟的修改

[root@mail ~]# hwclock --hctosys # hc to sys 硬件去修改系统
[root@mail ~]# hwclock --systohc # sys to hc 系统去修改硬件

日历的查看

[root@mail ~]# cal
    November 2017
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@mail ~]# cal 2016
                              2016

      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       1  2  3  4  5  6          1  2  3  4  5
3  4  5  6  7  8  9    7  8  9 10 11 12 13    6  7  8  9 10 11 12
10 11 12 13 14 15 16   14 15 16 17 18 19 20   13 14 15 16 17 18 19
17 18 19 20 21 22 23   21 22 23 24 25 26 27   20 21 22 23 24 25 26
24 25 26 27 28 29 30   28 29                  27 28 29 30 31
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    1  2  3  4  5  6  7             1  2  3  4
3  4  5  6  7  8  9    8  9 10 11 12 13 14    5  6  7  8  9 10 11
10 11 12 13 14 15 16   15 16 17 18 19 20 21   12 13 14 15 16 17 18
17 18 19 20 21 22 23   22 23 24 25 26 27 28   19 20 21 22 23 24 25
24 25 26 27 28 29 30   29 30 31               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       1  2  3  4  5  6                1  2  3
3  4  5  6  7  8  9    7  8  9 10 11 12 13    4  5  6  7  8  9 10
10 11 12 13 14 15 16   14 15 16 17 18 19 20   11 12 13 14 15 16 17
17 18 19 20 21 22 23   21 22 23 24 25 26 27   18 19 20 21 22 23 24
24 25 26 27 28 29 30   28 29 30 31            25 26 27 28 29 30
31
      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          1  2  3  4  5                1  2  3
2  3  4  5  6  7  8    6  7  8  9 10 11 12    4  5  6  7  8  9 10
9 10 11 12 13 14 15   13 14 15 16 17 18 19   11 12 13 14 15 16 17
16 17 18 19 20 21 22   20 21 22 23 24 25 26   18 19 20 21 22 23 24
23 24 25 26 27 28 29   27 28 29 30            25 26 27 28 29 30 31
30 31
1.6.2 cd
[root@mail ~]# cd /var/log    #change directory 切换到/var/log日志
[root@mail log]# cd ~         #切换到家目录
[root@mail ~]# pwd            #print workspace directory 打印工作目录
/root
[root@mail ~]# cd ~user1      #切换到user1的家目录,默认位置为/home/用户名
[root@mail user1]# pwd        #打印目录
/mnt/home/user1
[root@mail user1]# cd -       #切换到上一个目录
/root

相关环境变量

  • PWD:保存当前目录路径
  • OLDPWD:保存上一次目录的路径
1.6.3 ls
NAME
      ls - list directory contents   列出目录的内容

SYNOPSIS
      ls [OPTION]... [FILE]...

DESCRIPTION
      List  information  about  the  FILEs (the current directory by default).  Sort
      entries alphabetically if none of -cftuvSUX nor --sort is specified.

      Mandatory arguments to long options are mandatory for short options too.

      -a, --all
              do not ignore entries starting with . 列出所有的, 包括隐藏文件

      -A, --almost-all
              do not list implied . and ..   列出所有文件, 不包括.和..这2个

      --author
              with -l, print the author of each file 列出作者

      -b, --escape
              print C-style escapes for nongraphic characters 打印非打印符号用c-style

      --block-size=SIZE
              scale sizes by SIZE before printing them; e.g., '--block-size=M' prints
              sizes in units of 1,048,576 bytes; see SIZE format below 指定大小单位

      -B, --ignore-backups
              do not list implied entries ending with ~  不列出结尾是~的条目

      -c     with  -lt:  sort by, and show, ctime (time of last modification of file
              status information); with -l: show ctime and sort by  name;  otherwise:
              sort by ctime, newest first

      -C     list entries by columns 列方式列出条目

      --color[=WHEN]
              colorize  the  output;  WHEN  can  be 'never', 'auto', or 'always' (the
              default); more info below 设置输出颜色

      -d, --directory
              list directories themselves, not their contents 列出目录自身

      -D, --dired
              generate output designed for Emacs' dired mode  列出emacs目录模式

      -f     do not sort, enable -aU, disable -ls --color 不做排序

      -F, --classify
              append indicator (one of */=>@|) to entries 在目录后面添加/

      --file-type
              likewise, except do not append '*'

      --format=WORD
              across -x, commas -m, horizontal -x, long -l, single-column -1, verbose
              -l, vertical -C

      --full-time
              like -l --time-style=full-iso

      -g     like -l, but do not list owner 不列出所有者

      --group-directories-first
              group directories before files; 先列目录,在列出文件

              can  be augmented with a --sort option, but any use of --sort=none (-U)
              disables grouping

      -G, --no-group
              in a long listing, don't print group names 不打印组名字

      -h, --human-readable   文件大小自动调整为合适单位
              with -l, print sizes in human readable format (e.g., 1K 234M 2G)

      --si   likewise, but use powers of 1000 not 1024 使用1000作为k,m的换算单位而不是1024

      -H, --dereference-command-line
              follow symbolic links listed on the command line 追踪符号连接

      --dereference-command-line-symlink-to-dir
              follow each command line symbolic link

              that points to a directory

      --hide=PATTERN
              do not list implied entries matching shell PATTERN (overridden by -a or
              -A) 不列出匹配的正则

      --indicator-style=WORD
              append  indicator with style WORD to entry names: none (default), slash
              (-p), file-type (--file-type), classify (-F)

      -i, --inode
              print the index number of each file 打印inode号

      -I, --ignore=PATTERN
              do not list implied entries matching shell PATTERN 不列出匹配的正则

      -k, --kibibytes
              default to 1024-byte blocks for disk usage

      -l     use a long listing format 使用长格式显示

      -L, --dereference
              when showing file information for a symbolic link, show information for
              the file the link references rather than for the link itself 符号链接,显示连接到的文件

      -m     fill width with a comma separated list of entries 条目逗号分割

      -n, --numeric-uid-gid
              like -l, but list numeric user and group IDs 类似-l,只是用户名和组使用数字,而不是名字

      -N, --literal
              print raw entry names (don't treat e.g. control characters specially)

      -o     like -l, but do not list group information   不列出组信息

      -p, --indicator-style=slash
              append / indicator to directories  追加/在目录后面

      -q, --hide-control-chars
              print ? instead of nongraphic characters   打印?而不是不可打印的符号

      --show-control-chars
              show  nongraphic  characters as-is (the default, unless program is 'ls'
              and output is a terminal)

      -Q, --quote-name
              enclose entry names in double quotes 双引号包住列出的条目

      --quoting-style=WORD
              use quoting  style  WORD  for  entry  names:  literal,  locale,  shell,
              shell-always, c, escape

      -r, --reverse
              reverse order while sorting 反向排序

      -R, --recursive
              list subdirectories recursively 递归列出子目录

      -s, --size
              print the allocated size of each file, in blocks 打印分配的大小

      -S     sort by file size 排序文件大小

      --sort=WORD
              sort  by WORD instead of name: none (-U), size (-S), time (-t), version
              (-v), extension (-X)

      --time=WORD
              with -l, show time as WORD instead of default modification time:  atime
              or  access or use (-u) ctime or status (-c); also use specified time as
              sort key if --sort=time

      --time-style=STYLE
              with -l, show times using style STYLE: full-iso, long-iso, iso, locale,
              or  +FORMAT;  FORMAT  is  interpreted like in 'date'; if FORMAT is FOR‐
              MAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FOR‐
              MAT2  to  recent files; if STYLE is prefixed with 'posix-', STYLE takes
              effect only outside the POSIX locale

      -t     sort by modification time, newest first 排序按照mtime

      -T, --tabsize=COLS
              assume tab stops at each COLS instead of 8

      -u     with -lt: sort by, and show, access time; with -l: show access time and
              sort by name; otherwise: sort by access time

      -U     do not sort; list entries in directory order 按照目录的顺序累出

      -v     natural sort of (version) numbers within text

      -w, --width=COLS
              assume screen width instead of current value 指定宽度

      -x     list entries by lines instead of by columns

      -X     sort alphabetically by entry extension 按照扩展排序

      -1     list one file per line  每行列出一个文件

      SELinux options:

      --lcontext
              Display  security context.   Enable -l. Lines will probably be too wide
              for most displays.

      -Z, --context
              Display security context so it fits on most  displays.   Displays  only
              mode, user, group, security context and file name.

      --scontext
              Display only security context and file name.

      --help display this help and exit

      --version
              output version information and exit

ls -l列出的信息说明

[root@mail ~]# ls -l
total 16
-rw-r--r--  1 root root  154 Sep 25 19:34 adduserbat.sh
-:文件类型
rw-r--r--:权限
1: 文件被硬连接的次数
root:文件的owner
root:文件的group
154:文件的大小
Sep 25 19:34: 文件最近修改的时间
adduserbat.sh: 文件名字

文件类型有一下几类

  • -:普通文件
  • d:目录文件
  • b:块设备文件
  • c:字符设备文件
  • s:socket文件
  • p:管道文件
  • l:连接文件
1.6.4 cat
NAME
      cat - concatenate files and print on the standard output

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

DESCRIPTION
      Concatenate FILE(s), or standard input, to standard output.

      -A, --show-all
              equivalent to -vET 显示所有

      -b, --number-nonblank
              number nonempty output lines, overrides -n 编号非空行不编号

      -e     equivalent to -vE

      -E, --show-ends
              display $ at end of each line 每行结尾追加一个$

      -n, --number
              number all output lines 每行添加一个行号

      -s, --squeeze-blank
              suppress repeated empty output lines  压缩重复的空行

      -t     equivalent to -vT

      -T, --show-tabs
              display TAB characters as ^I

      -u     (ignored)
1.6.5 echo
NAME
      echo - display a line of text 显示一行文本

SYNOPSIS
      echo [SHORT-OPTION]... [STRING]...
      echo LONG-OPTION

DESCRIPTION
      Echo the STRING(s) to standard output.

      -n     do not output the trailing newline 不显示自动换行

      -e     enable interpretation of backslash escapes 启动转义符

      -E     disable interpretation of backslash escapes (default) 关闭转义符

      --help display this help and exit

      --version
              output version information and exit

      If -e is in effect, the following sequences are recognized:

      \\     backslash  打印\

      \a     alert (BEL) 警钟声音

      \b     backspace 删除一个字符

      \c     produce no further output

      \e     escape

      \f     form feed

      \n     new line 新行

      \r     carriage return 回车符

      \t     horizontal tab 制表符

      \v     vertical tab  水平制表符

echo 打印颜色符号

[root@mail ~]# echo -e "\033[34mOk\033[0m"
Ok(这个字体是带颜色的)

颜色控制

\033[##m:控制颜色
第一个#:控制字体的前景色
第二个#:控制字体的背景色
如果同时使用前景和背景色:\033[3#:4#m
\033[0m:关闭字体功能
1.6.6 which
[root@mail ~]# which ls
alias ls='ls --color=auto'
  /usr/bin/ls
[root@mail ~]# which ls --skip-alias
/usr/bin/ls
1.6.7 whatis
[root@mail ~]# whatis ls
ls (1)               - list directory contents
ls (1p)              - list directory contents

#centos6:makewhat命令创建帮助手册和对应关键字的数据库
#cnetos7:mandb

02 LINUX文件系统

根文件系统: linux识别的第一个与根直接关联的文件系统。

FHS:LSB组织定义的LINUX发行版基础目录命名法则及功用规定。filesystem hierarchy standard,文件系统层级标准

2.1 linux根简介

  • /boot: 系统引导启动目录
  • /bin:系统相关的二进制程序
  • /sbin:系统相关的管理类基础命令
  • /lib:基础的共享库文件
  • /lib64:专用64系统上的辅助共享库
  • /etc:配置文件
  • /home:家目录
  • /root:管理员家目录
  • /media:便携式移动设备的挂载点
  • /mnt:临时文件系统挂载点
  • /dev:设备文件
  • /opt:第三方安装目录
  • /src:服务类存放目录
  • /tmp:临时文件存放目录
  • /usr:unix software resource
  • /var/cache:应用缓存目录
  • /var/lib:应用库目录
  • /var/local:应用程序可变存储目录
  • /var/lock:锁文件
  • /var/log:日志文件存放目录
  • /var/run:存储进程的pid目录
  • /var/spool:应用程序的数据池
  • /var/tmp:保存系统2次重启之间产生的临时数据
  • /proc:用于输入内核与进程信息相关的虚拟文件系统
  • /sys:用于输出当前系统上硬件设备相关信息的虚拟文件系统
  • /selinux:selinux相关的安全策略等信息

2.2 应用程序主要组成部分

  • 二进制程序: /bin,/sbin,/usr/bin,/usr/sbin,/usr/local/bin,/usr/local/sbin
  • 库文件:/lib,/lib64,/usr/lib,/usr/lib64,/usr/local/lib,/usr/local/lib64
  • 配置文件:/etc,/etc/DIRECTORY,/usr/local/etc
  • 帮助文件:/usr/share/man, /usr/share/doc, /usr/local/share/man,/usr/local/share/doc

03 LINUX上bash的基础特性(一)

3.1 命令历史

环境变量

  • HISTSIZE:命令历史的条数
  • HISTFILE:默认为`~/.bash_history`
  • HISTFILESIZE:HISTFILE文件记录历史的条数

history 常用命令

-d 删除指定的命令
-c 清空命令
-a 手工追加当前会话的命令历史到历史文件中去

调用历史命令

  • !#:重复执行第#条命令
  • !!:重复执行上一条命令
  • !str:执行指定str开头的命令(最后一个)
  • !?:获得最后执行的状态码

控制命令历史的记录方式

主要和HISTCONTROL这个环境变量有关(”/etc/profile”)

  • ignoredups:忽略重复
  • ignorespace:忽略空白开头
  • ignoreboth:上面2个都启用

3.2 命令补全

tab补全

3.3 路径补全

tab补全

3.4 目录管理类命令

3.4.1 mkdir

用法: mkdir [option] directoy…

-p 没有父目录就一起创建了
-v 显示创建目录过程
-m 指定权限
[root@centos6 dirtest]# mkdir -pv /app/dirtest/a/b/c/d
mkdir: created directory '/app/dirtest/a'
mkdir: created directory '/app/dirtest/a/b'
mkdir: created directory '/app/dirtest/a/b/c'
mkdir: created directory '/app/dirtest/a/b/c/d'
[root@centos6 dirtest]# mkdir -m 0744 d
[root@centos6 dirtest]# ls
a  d
[root@centos6 dirtest]# ll
total 8
drwxr-xr-x. 3 root root 4096 Aug  7 06:47 a
drwxr--r--. 2 root root 4096 Aug  7 06:47 d
3.4.2 tree

用法: tree [option] directory

-d 只显示目录
-L 只显示指定的level级别
-P 只显示匹配指定的路径
3.4.3 命令行展开

~,{},~username

3.4.4 命令的执行结果状态

$?:获取上一个命令的执行状态码

3.4.5 文件查看命令

more

less

head

-n 获取前n行
-c 获取前n个字符

tail

-n 获取后n行
-c 获取后n个字符
-f 动态显示

3.5 文件管理

3.5.1 cp

用法: cp src dst

情况1:测试src是文件,目标不存在

[root@centos6 dirtest]# touch a.tx
[root@centos6 dirtest]# ls
a  a.tx  bin  d  sbin  usr  x  x_m  x_n  y_m  y_n
[root@centos6 dirtest]# cp a.tx p
[root@centos6 dirtest]# ll
total 40
drwxr-xr-x. 3 root root 4096 Aug  7 06:47 a
-rw-r--r--. 1 root root    0 Aug  7 07:09 a.tx
drwxr-xr-x. 2 root root 4096 Aug  7 07:01 bin
drwxr--r--. 2 root root 4096 Aug  7 06:47 d
-rw-r--r--. 1 root root    0 Aug  7 07:09 p
drwxr-xr-x. 2 root root 4096 Aug  7 07:01 sbin
drwxr-xr-x. 4 root root 4096 Aug  7 07:01 usr
drwxr-xr-x. 3 root root 4096 Aug  7 06:59 x
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 x_m
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 x_n
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 y_m
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 y_n

情况2:测试src是文件,dst存在

[root@centos6 dirtest]# cp a.tx  p
cp: overwrite 'p'? y
[root@centos6 dirtest]# cp a.tx  a
[root@centos6 dirtest]# ll a
total 4
-rw-r--r--. 1 root root    0 Aug  7 07:11 a.tx
drwxr-xr-x. 3 root root 4096 Aug  7 06:47 b

情况3:测试src是目录,dst不存在

[root@centos6 dirtest]# cp -r a ap
[root@centos6 dirtest]# ll
total 44
drwxr-xr-x. 3 root root 4096 Aug  7 07:11 a
drwxr-xr-x. 3 root root 4096 Aug  7 07:12 ap
-rw-r--r--. 1 root root    0 Aug  7 07:09 a.tx
drwxr-xr-x. 2 root root 4096 Aug  7 07:01 bin
drwxr--r--. 2 root root 4096 Aug  7 06:47 d
-rw-r--r--. 1 root root    0 Aug  7 07:11 p
drwxr-xr-x. 2 root root 4096 Aug  7 07:01 sbin
drwxr-xr-x. 4 root root 4096 Aug  7 07:01 usr
drwxr-xr-x. 3 root root 4096 Aug  7 06:59 x
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 x_m
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 x_n
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 y_m
drwxr-xr-x. 2 root root 4096 Aug  7 07:00 y_n
[root@centos6 dirtest]# ll a ap
a:
total 4
-rw-r--r--. 1 root root    0 Aug  7 07:11 a.tx
drwxr-xr-x. 3 root root 4096 Aug  7 06:47 b

ap:
total 4
-rw-r--r--. 1 root root    0 Aug  7 07:12 a.tx
drwxr-xr-x. 3 root root 4096 Aug  7 07:12 b

情况4:测试src是目录,dst存在

[root@centos6 dirtest]# cp -r a ap
[root@centos6 dirtest]# ll ap
total 8
drwxr-xr-x. 3 root root 4096 Aug  7 07:14 a
-rw-r--r--. 1 root root    0 Aug  7 07:12 a.tx
drwxr-xr-x. 3 root root 4096 Aug  7 07:12 b
[root@centos6 dirtest]# cd a
[root@centos6 a]# ls
a.tx  b
[root@centos6 a]# tree ap
ap [error opening dir]

0 directories, 0 files
[root@centos6 a]# ls
a.tx  b
[root@centos6 a]# cd ..
[root@centos6 dirtest]# ls
a  ap  a.tx  bin  d  p  sbin  usr  x  x_m  x_n  y_m  y_n
[root@centos6 dirtest]# tree ap
ap
├── a
│   ├── a.tx
│   └── b
│       └── c
│           └── d
├── a.tx
└── b
    └── c
        └── d

7 directories, 2 files

mv

rm

-i 交互
-f 强制
-r 递归

04 LINUX上bash的基础特性(二)

4.1 命令别名

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

针对用户的别名: “~/.bashrc”

针对系统的别名:”/etc/bashrc”

重读配置文件:source /path/to/config.file

unalias:撤销别名

4.2 glob通配

    • 代表任意长度的任意字符
  • ?: 表示任意单个字符
  • []:匹配指定范围的任意的单个字符
  • [^]:取反
  • [alnum]:所有字母和数字
  • [:alpha:]:字母
  • [:digit:]:数字
  • [:lower:]:小写字母
  • [:upper:]:大写字母
  • [:punct:]:标点符号
  • [:space:]:空白字符,不是仅仅空格

4.3 bash快捷键盘

  • ctrl+L:
  • ctrl+a:
  • ctrl+e:
  • ctrl+u:
  • ctrl+k:

4.4 bash i/o重定向

  • >
  • >>:
  • 2>
  • 2>>
  • > a.txt 2 > &1
  • >>a.txt 2>> &1

tr

[root@centos6 dirtest]# tr 'a-z' 'A-Z' < /etc/fstab

#
# /ETC/FSTAB
# CREATED BY ANACONDA ON TUE NOV  7 15:31:40 2017
#
# 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=AA4C5795-C48C-4E21-B5A2-31198C603E8D /                       EXT4    DEFAULTS        1 1
UUID=0733A859-9567-48D3-88B1-B8D1FBEBBBA0 /APP                    EXT4    DEFAULTS        1 2
UUID=53B38D7C-322C-484D-B108-5C8191251531 /BOOT                   EXT4    DEFAULTS        1 2
UUID=38651A9B-10AB-4218-960B-D0EBB9CBAA54 SWAP                    SWAP    DEFAULTS        0 0
TMPFS                   /DEV/SHM                TMPFS   DEFAULTS        0 0
DEVPTS                  /DEV/PTS                DEVPTS  GID=5,MODE=620  0 0
SYSFS                   /SYS                    SYSFS   DEFAULTS        0 0
PROC                    /PROC                   PROC    DEFAULTS        0 0

4.5 文本处理工具

4.5.1 wc
-l 行数
-c 字符数量
-w 单词个数
4.5.2 cut
-d 分割符号
-f 提取
4.5.3 sort
-f 忽略大小写
-k 指定字段排序
-t 分割
-n 数字排序
-u 去重连续的重复
-r 逆序
4.5.4 uniq
-c 显示重复的次数
-d 只显示重复的行
-u 值显示不重复的行

05 linux用户和组管理

用户分类

  • 系统用户:1-499(centos6),1-999(centos7)
  • 登陆用户: 500+(centos6),1000+(centos7)

5.1 主要配置文件分析

5.1.1 /etc/passwd

name:password:uid:gid:geocos:homedir:shell

[root@centos6 ~]# head -1 /etc/passwd
root:x:0:0:root:/root:/bin/bash
5.1.2 /etc/group

groupname:password:gid:userlist

[root@centos6 ~]# head -1 /etc/group
root:x:0:
5.1.2 /etc/shadow

name:password: date of last password change : minimum password age : maximum password age : password warning period: password warning period: password inactivity period

[root@centos6 ~]# tail -n 1 /etc/shadow
zhaojiedi:$6$rZ5h80aV/7Sci.YB$D25I/MTmTHyo.2XhUNSiJab1BU/qf1vgpdZ3c0JBgzSDMG8tKzyUsPk..xJ9a31a17kGctcgm0OBIUTQGf7Uv0:17477:0:99999:7:::
  • 用户名
  • 加密密码
  • 上次修改的密码
  • 最小使用时间
  • 最大使用时间
  • 密码警告时间
  • 密码禁用期
  • 账户过期日期
  • 保留字段

5.2 用户管理命令

5.2.1 useradd
-u 指定用户id
-g 基本组
-G 附加组
-c 注释信息
-s shell类型
-d 用户的家目录
5.2.2 groupadd
-g 组id
-r 系统用户

id

[root@centos6 ~]# id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@centos6 ~]# id -u
0
[root@centos6 ~]# id -g
0
[root@centos6 ~]# id -G
0
[root@centos6 ~]# id -un
root
5.2.3 su
  • su username: 非登录切换,不会读取目标用户的配置文件
  • su -username:登陆切换,会读取目标用户配置文件,完全切换
5.2.4 usermod

-g: -G: -u: -s: -c: -d: -l -L -U -e 指定过期日期 -f 指定非活动期限

5.2.5 passwd
-l 锁定用户
-u 解锁
-n 最短期限
-x 最大期限
-w 警告期限
-i 非活动期限
--stdin 接受终端输入
5.2.6 userdel
-r 删除用户家目录
5.2.7 groupdel
5.2.8 groupmod
-n 新名字
-g 新的id
5.2.9 gpasswd
-a 添加到指定的组
-d 从指定组删除
-A 设置用户列表
5.2.10 newgrp

用户临时切换基本组

5.2.11 chage
-d 修改用户最近一次修改时间
-I 修改用户的非活动期限
-E 过期日期

5.3 sudo

-l 查看用户可以执行的sudo
-k 清楚记一下的令牌
-u 以指定用户运行命令

配置文件是/etc/sudoers

账号 登陆这来源主机名 (可切换的身份) 命令

注意事项

  • ALL大写
  • 命令使用全路径
  • 组使用%
  • 别名 User_Alias User1 = magedu,centos,test

06 Linux上bash的基础特性(三)

6.1 编程环境

shell脚本的组成部分

  • shebang
  • 各种命令组合

编程变量种类

  • 本地变量: 仅仅在当前的shell生效
  • 环境变量: 在当前和子shell生效
  • 局部变量: shell进程某代码片段
  • 位置变量: $1,$2来表示,用与获取脚本接受的参数
  • 特殊变量: 一些特殊变量

特殊变量如下

  • $?:上一个命令的执行返回码
  • $#:参数个数
  • $*:参数
  • $0:命令本身
  • $@:所有参数

本地变量: name=’value’

环境变量:export name=value,declare -x name=value,查看环境变量,env,export,printenv变量

bash的配置文件

  • 全局配置文件
    • /etc/profile
    • /etc/profile.d/*.sh
  • 个人的配置文件
    • ~/.bash_profile
    • ~/.bashrc

profile:用于定义环境变量和脚本

bashrc:用于定义命令别名和本地变量

6.1.1 算数运算
  • let a=expr
  • $[expr]
  • $((expr))
  • expr a1 op a2
[root@centos6 x]# let a=10
[root@centos6 x]# $[10+20]
-bash: 30: command not found
[root@centos6 x]# echo $[10+20]
30
[root@centos6 x]# echo $((10+20))
30
[root@centos6 x]# echo `expr 10 + 20`
30
6.1.2 条件测试
  • test expr
  • [ expr ]
  • [[ expr ]]
6.1.3 测试类型
  • -gt
  • -lt
  • -eq
  • -ge
  • -le
  • -ne
6.1.4 字符测试
  • ==
  • >
  • <
  • !=
  • =~
  • -z
  • -n
6.1.5 文件测试
  • -a
  • e
  • -b
  • -c
  • -d
  • -f
  • -S:存在且为socket
  • -p
  • -h -L
  • -r
  • -w
  • -x
  • -g
  • -u
  • -k
  • -s:存在且非空
  • -t fd:表示文件表叔父是否已经打开且与某个终端先关
  • -N :文件自上次被读取之后是否被修改过
  • -O:是否是文件属主
  • -G:是否是文件组
  • file2 -ef file2: 相同inode文件
  • file1 -nt file2:file1比file2新
  • file1 -ot file2:file1比file2旧
6.1.6 组合测试
  • &&
  • ||
  • -a
  • -o
  • !
6.1.7 语句控制

if

if expr ; then
    sate
fi

for

for var in [] ; do
    sate
done

07 grep正则表达式

grep

grep:global search regula expression and print out the line.

分类:

  • 基本的
  • 扩展的

7.1 grep语法

--color 高亮显示匹配到字符串
-v 显示不能被匹配的行
-i 忽略大小写
-o 仅仅显示匹配到的
-q 静默模式
-A 后面几行
-B 前面几行
-C 前后几行
-E 启用扩展

7.2 基本的正则表达式

7.2.1 字符匹配
.                   任意字符一次
[]                  几何中任一个字符
[^]                 几何之外任何一个
[:alpha:]           字母
[:alnum:]           字母数字
[:digit:]           数字
[:punct:]           标点符号
[:space:]           空白字符
[:upper:]           大写
[:lower:]           小写
7.2.2 次数匹配

  • 多次

? 0次或者1次 + 1次或者更多次 {m} 精确m次 {m,n} m到n次 {0,n} 小于等于n次 {m,} 大于等于m次

7.2.3 位置锚定

^ 行首锚定 $ 行尾锚定 < 单词头锚定 > 单词尾锚定 b 单词边界锚定

7.2.4 分组

() 分组 1 分组后的后向引用

7.3 扩展正则表达式

08 Linux文件查找

文件的查找分为2种:

  • 实时查找
  • 非实时查找

8.1 locate

locate的使用比较简单,依赖于数据库,需要更新数据库

  • centos6 : makewhatis
  • centos7 : mandb

8.2 find

8.2.1 find的查找用法
find [选项] [查找路径] [查找条件] [处理动作]
8.2.2 查找条件
-name 名字查找
-iname 文件名字查找,忽略大小写
-user 用户
-group
-gid 组id
-nouser 没有属主
-nogroup 没有属组
8.2.3 组合条件查找
-a 同时满足
-o 满足一个即可
-not 条件取反
8.2.4 文件类型判断

-type 文件类型

f           普通文件
d           目录
l           链接文件
s           socket
b           块设备
c           字符设备
p           管道文件
8.2.5 根据文件大小

-size [+|-] #UNIT

#UNIT                   #-1< X <= #
-UNIT                   0<= X < #
+UNIT                   X > #
8.2.6 根据时间戳
  • -atime [+|-] #UNIT
  • -ctime [+|-] #UNIT
  • -mtime [+|-] #UNIT
#UNIT                   #<= X <= #+1
-UNIT                   0<= X < #
+UNIT                   X >= #+1
8.2.7 根据权限

-perm [+|-] MODE

644                     精确匹配权限
+644                    任何一位满足就匹配
-644                    对应为都满足
8.2.8 处理动作
-print 打印到屏幕
-ls 列出来
-delete 删除查找的文件
-fls 长格式写到指定文件中
-ok 交互的执行后续命令
-exec 执行后续命令

09 Vim编辑器

Vim有3种模式

  • 编辑模式
  • 输入模式
  • 末行模式

9.1 模式转化

输入模式--> 末行模式: ESC
编辑模式--> 输入模式:
                        a
                        A
                        o
                        O
                        i
                        I
编辑模式--> 末行模式:ESC
末行模式转编辑模式:ESC

9.2 退出文件

:q                  退出
:w                  保存
:wq                 保存退出
:x                  保存退出
:wq!                保存退出
:w new_file_path    保存到指定的文件

9.3 光标移动

字符间移动
h
l
j
k

单词之间移动
w
e
b

行内移动
^
0
$

句子内移动
(
)

段落内移动
{
}

行间移动
#G
G
gg

9.4 Vim的编辑命令

x               删除所在位置字符
#x              删除后续几个字符
d               删除命令,配合移动字符
dd              删除行
p               粘贴
y               复制
Y               复制当前行
c               修改,配合移动字符
u               撤销之前操作

9.5 Vim可视化模式

v               光标走过的字符
V               光标走过的行

9.6 翻屏操作

ctrl+f              文件尾部翻一屏
ctrl+b              文件首部翻1屏
ctrl+d              文件尾部翻半屏
ctrl+u              文件首部翻半屏

9.7 Vim末行模式

9.7.1 内容定界

startpos,endpos

#               第#行
#,#             第#到第#行
.               当前行
$               最后一行
%               全文
9.7.2 查找
/pathern           正向查找
?                  反向查找
9.7.3 查找并替换

s/查找模式/要替换的内容/修饰符

修饰符:

  • i 忽略大小写
  • g 全局替换

9.8 多文件模式

:next               下一个文档
:previous           前一个文档
:last               最后一个文档
:first              第一个文档
:waall              保存所有

9.9 窗口属性设置

:set nu             显示行号
:set nonu           关闭行号显示
:set ai             打开智能提示
:set noai           关闭智能提示
:set ic             忽略大小写
:set noic           关闭忽略大小写
:set sm             括号匹配
:set nosm           关闭括号匹配
:syntax on          语法高亮
:syntax off         语法高亮关闭
:set hlsearch       高亮搜索
:set nohlsearch     关闭高亮搜索

10 Linux磁盘管理

设备的分类:

  • 块设备
  • 字符设备

10.1 磁盘设备的文件命名

  • IDE /dev/hd
  • SCSI,SATA,SAS,USB /dev/sd

10.2 机械式硬盘

磁道
每个盘片上被分为N个同心圆,每个同心圆就是一个磁盘。
柱面
相同编号的磁道
扇区
每个磁道512个字节

磁道越靠外的分区器读写速度越快,通常外面的划分为系统分区,第0磁道0扇区是被预留出来的,不属于任意的分区,称为MBR

10.3 MBR

前446字节:                 存储boot loader,引导加载器
64字节:                    存储分区表的,4个部分,每个16字节
2字节:                     结束标志55AA

10.4 磁盘分区管理命令

fdisk [DEVICE]

p           显示分区表
n           创建分区
d           删除分区
t           修改分区id
l           列出系统id
w           保存退出
q           不保存退出

10.5 LINUX文件系统

常用文件系统

普通文件系统              ext2,ext3,ext4,xfs,btrfs,reiserfs,jfs,swap
网络文件系统              nfs,smbfs,cifs
集群文件系统              gfs,ocfs
分布式文件系统            ceph,moosefs,mogilefs,glusterfs
光盘文件系统              iso9660
10.5.1 创建文件系统

mkfs

-t 指定文件系统
-L 指定卷标

mke2fs

-t 指定文件系统
-b 指定块大小
-L 指定卷标
-j 相当于-t ext3
-i 每多少字节创建一个inode
-N 直接指定inode个数
-m 设置预留的百分比,默认5
-O 指定分区特性

blkid

-L 查看指定的卷标
-U 查看指定的uid

e2label

修改卷标名字

tunefs

-l 查看指定文件系统的超级块信息
-j ext2–>ext3
-L 修改卷标
-m 修改预留百分比
-O 启用指定特性
-o 开启或或者关闭指定挂载选项
-U 修改UUID
10.5.2 文件系统监测

fsck

-t 指定类型
-a 自动修复错误
-r 交互式修复

e2fs

-y 对问题自动回答yes
-f 强制进行检查
10.5.3 超级块

超级块的作用是存储文件系统的元数据信息

10.6 文件系统的挂载

所谓的挂载文件系统就是将额外的分区和根文件系统上的某个目录建立关联的过程。

mount

-t 指定文件系统
-r 只读
-w 读写
-L 卷标
-U uuid
-a 自动挂载
-n 不更新mtab
-B 绑定到目录
-o 指定挂载选项

挂载详细选项

async/sync              同步异步问题
atime/noatime           是否更新atime
auto/noauto             是否自动挂载
/diratime/nodiratime    目录被访问,是否更新时间戳
/dev/nodev              是否支持使用设备
exec/noexec             是否执行二进制程序
suid/nosuid             是否支持suid
remount                 重新挂载
ro                      读
rw                      读写
user/nouser             是否运行普通用户挂载
acl                     是否支持acl

10.7 挂载交互分区

swapon

-a 激活所有的交互分区
-p 指定优先级

10.8 文件系统的卸载

umount即可完成卸载,有时候有访问的时候需要fuser -km配合使用

10.8 设备自动开机挂载

/etc/fstab一共6个部分,空格后者tab分割即可

  1. 挂载的设备
  2. 挂载点
  3. 文件系统类型
  4. 挂载选项
  5. 转储频率
  6. 自检次序

10.9 硬链接

一般情况下一个文件名和inode号码是一一对应的。多个文件名指向同一个inode就是硬链接。

ln 源文件 目标文件

10.10 软连接

软连接文件和源文件的inode是不同的, 软连接文件存储的是相对应源文件的路径。

ln -s 源文件 目标文件

01 LINUX简介

02 LINUX文件系统

03 LINUX上bash的基础特性(一)

04 LINUX上bash的基础特性(二)

05 linux用户和组管理

06 Linux上bash的基础特性(三)

07 grep正则表达式

08 Linux文件查找

09 Vim编辑器

10 Linux磁盘管理

练习题

01-2017-07-练习-Linux简介练习

1)halt,poweroff,shutdown,init 0的主要区别

关机相关shutdown,init 0:

shutdown实际上是调用init 0, init 0会cleanup一些工作然后调用halt或者poweroff。
其实主要区别是halt和poweroff,做没有acpi(高级配置和电源管理接口)的系统上,
halt只是关闭了os,电源还在工作,你得手动取按一下那个按钮,
但在现在的系统上,他们实际上都一样了

重启相关reboot,shudown,init6:

"init 6" 基于一系列/etc/inittab文件,并且每个应用都会有一个相应shutdown脚本。
'init 6' 调用一系列shutdown脚本(/etc/rc0.d/K*)来使系统优雅关机;
'reboot'并不执行这些过程,
reboot更是一个kernel级别的命令,不对应用使用shutdown脚本。
我们应该在通常情况下使用 init 6.
在出问题的状况下或强制重启时使用reboot.

2)用户登陆相关

who,whoami,w的使用

[root@centos6 ~]# who #查看当前用户登陆情况, 建议使用w,显示更全面
root     tty1         2017-11-07 16:20 (:0)
root     pts/0        2017-11-07 16:20 (:0)
root     pts/1        2017-11-07 16:34 (:0)
root     pts/2        2017-11-07 16:39 (192.168.27.1)
root     pts/3        2017-11-07 17:11 (192.168.27.1)
root     pts/4        2017-11-07 18:56 (192.168.27.1)


[root@centos6 ~]# who -r #显示运行级别
run-level 5  2017-11-07 16:11
[root@centos6 ~]# whoami
root
[root@centos6 ~]# w #    带有启动时间,用户数,还有负载情况,用户,连接终端,来源ip,登陆时间,空闲时间,占用cpu时常
19:05:53 up  2:54,  6 users,  load average: 0.00, 0.00, 0.00

USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     tty1     :0               16:20    2:54m  5.38s  5.38s /usr/bin/Xorg :0 -br -v
root     pts/0    :0               16:20    2:45m  0.00s  0.54s kded4
root     pts/1    :0               16:34    2:30m  0.00s  0.00s /bin/bash
root     pts/2    192.168.27.1     16:39    2:12m  0.04s  0.04s -bash
root     pts/3    192.168.27.1     17:11    1:21m  0.07s  0.07s -bash
root     pts/4    192.168.27.1     18:56    0.00s  0.16s  0.10s w

02-2017-11-08-练习-日期开机关机

练习1-date

1 、显示当前时间,格式:2016-06-18 10:20:30

[root@centos6 ~]# date "+%Y-%m-%d %H:%M:%S"
2017-11-10 09:20:34

2 、显示前天是星期几

[root@centos6 ~]# date
Fri Nov 10 09:27:41 CST 2017
[root@centos6 ~]# date -d  "@"$(echo $(date +%s) -  60*60*24*2 |bc) +%w
3
[root@centos6 ~]# date -d  "-2 day" +%w
3

3 、设置当前日期为2019-08-07 06:05:10

[root@centos6 ~]# date 080706052019.10
Wed Aug  7 06:05:10 CST 2019
[root@centos6 ~]# date
Wed Aug  7 06:05:12 CST 2019
[root@centos6 ~]# date "+%Y-%m-%d %H:%M:%S"
2019-08-07 06:05:42

练习2-mingetty,shutdown

1、在本机字符终端登录时,除显示原有信息外,再显示当前登录终端号,主机名和当前时间 我们使用man mingetty可以获取到如下的帮助信息。

-d insert current day (localtime), 插入当前日期
-l insert line on which mingetty is running,终端类型
-m inserts machine architecture (uname -m),机器架构
-n inserts machine’s network node hostname (uname -n),主机名
-o inserts domain name,域名
-r inserts operating system release (uname -r),版本号
-t insert current time (localtime),时间
-s inserts operating system name,操作系统名字
-u resp. U the current number of users which are currently loggedin. 显示登陆用户数量
-v inserts operating system version (uname -v).操作系统版本

修改文件如下即可

[root@centos6 ~]# cat /etc/issue
CentOS release 6.9 (Final)
Kernel \r on an \m
current time: \d \t
hostname : \n
tty:    \l

2、今天18:30自动关机,并提示用户

[root@centos6 ~]# shutdown 18:30 "computer will close"

Broadcast message from root@centos6.magedu.com
        (/dev/pts/1) at 6:28 ...

The system is going down for maintenance in 722 minutes!
computer will close

03-2017-11-09-练习-glob

练习1-glob

1、 显示/var目录下所有一1开头,一一个小写字母结果,且中间至少出现一个数字的目录和文件

[root@centos6 dirtest]# ls -d /var/1*[0-9]*[[:lower:]]

2、 显示/etc目录下,一非字母开头,后面跟一个字母,以及其他任意长度字符的文件或者目录

[root@centos6 dirtest]# ls -d /etc/[^[:alpha:]][[:alpha:]]*

3、复制/etc/目录下,所有以m开头,以非数字结尾的文件或者目录到/tmp/magedu目录

[root@centos6 dirtest]# cp /etc/m*[^0-9] /tmp/magedu

4、复制/etc目录下,所有以.d结尾的文件或者目录到/tmp/magedu.com目录中

[root@centos6 dirtest]# cp /etc/*.d /tmp/magedu.com

5、复制/etc目录下,所有以.conf结果,且一m,n,r,p开头的文件或者目录到/tmp/magedu.com目录中

[root@centos6 dirtest]# cp /etc/[mnrp]*.conf /tmp/magedu

练习2-glob

1 、显示/var 目录下所有以l 开头,以一个小写字母结尾,且中间出现至少一位数字的文件或目录

[root@centos7 glob]# ls -d /var/l*[0-9]*[[:lower:]]

2 、显示/etc 目录下以任意一位数字开头,且以非数字结尾的文件或目录

[root@centos7 glob]# ls /etc/[0-9]*[^0-9]

3 、显示/etc/ 目录下以非字母开头,后面跟了一个字母及其它任意长度任意字符的文件或目录

[root@centos7 glob]# ls -d /etc/[^[:alpha:]][[:alpha:]]*

4 、显示/etc/ 目录下所有以rc 开头,并后面是0-6 之间的数字,其它为任意字符的文件或目录

[root@centos7 glob]# ls -d /etc/rc[0-6]*

5 、显示/etc 目录下,所有以.d 结尾的文件或目录

[root@centos7 glob]# ls -d /etc/*.d

``` 6 、显示/etc 目录下,所有.conf 结尾,且以m,n,r,p 开头的文件或目录

[root@centos7 glob]# ls -d /etc/[mnrp]*.conf

7 、只显示/root 下的隐藏文件和目录

[root@centos7 glob]# ls -ad /root/.*

8 、只显示/etc下的非隐藏文件

ls /etc/[^.]* -d

04-2017-11-09-练习-目录相关

练习1-mkdir

1、如何创建/app/x/y1,/app/x/y2,/app/x/y1/a,/app/y1/b,/app/x/y2/a,/app/x/y2/b

[root@centos6 dirtest]# mkdir x/y1,x/y2,x/y1/a,y1/b,x/y2/a,x/y2/b -pv
mkdir: created directory 'x'
mkdir: created directory 'x/y1,x'
mkdir: created directory 'x/y1,x/y2,x'
mkdir: created directory 'x/y1,x/y2,x/y1'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1/b,x'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1/b,x/y2'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1/b,x/y2/a,x'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1/b,x/y2/a,x/y2'
mkdir: created directory 'x/y1,x/y2,x/y1/a,y1/b,x/y2/a,x/y2/b'

2、如何创建x_m,y_m,x_n,y_n

[root@centos6 dirtest]# mkdir -pv {x,y}_{m,n}
mkdir: created directory 'x_m'
mkdir: created directory 'x_n'
mkdir: created directory 'y_m'
mkdir: created directory 'y_n'

3、如何创建/app/bin,/app/sbin,/app/usr/app/usr/bin,/app/usr/sbin

[root@centos6 dirtest]# mkdir -pv {bin,sbin,usr/{bin,sbin}}
mkdir: created directory 'bin'
mkdir: created directory 'sbin'
mkdir: created directory 'usr'
mkdir: created directory 'usr/bin'
mkdir: created directory 'usr/sbin'

练习2-alias,cp

1 、定义别名命令baketc ,每 天将 将/etc/ 目录下所有文件,备份到/app 独立的子目录 下, 并要求子目录 格式为 为 backupYYYY-mm-dd, , 备份过程可见

[root@centos7 cpdir]# alias baketc="cp -av /etc /app/backup$(date +%Y-%m-%d)"

2 、创建/app/rootdir 目录,并复制/root下 下 所有文件 到该目录 内,要求保留权限

#这个有点迷,不知道是复制到文件内部还是就是root复制到/rootdir
[root@centos7 cpdir]# cp -a /root /app/rootdir

练习3-rename

1 、 目录下有f1..f300文件,修改为f001..f300。

[root@centos7 renametest]# touch f{1..300}         # 创建一些样例文件
[root@centos7 renametest]# ls                      # 查看下文件
f1    f117  f135  f153  f171  f19   f207  f225  f243  f261  f28   f298  f45  f63  f81
f10   f118  f136  f154  f172  f190  f208  f226  f244  f262  f280  f299  f46  f64  f82
f100  f119  f137  f155  f173  f191  f209  f227  f245  f263  f281  f3    f47  f65  f83
f101  f12   f138  f156  f174  f192  f21   f228  f246  f264  f282  f30   f48  f66  f84
f102  f120  f139  f157  f175  f193  f210  f229  f247  f265  f283  f300  f49  f67  f85
f103  f121  f14   f158  f176  f194  f211  f23   f248  f266  f284  f31   f5   f68  f86
f104  f122  f140  f159  f177  f195  f212  f230  f249  f267  f285  f32   f50  f69  f87
f105  f123  f141  f16   f178  f196  f213  f231  f25   f268  f286  f33   f51  f7   f88
f106  f124  f142  f160  f179  f197  f214  f232  f250  f269  f287  f34   f52  f70  f89
f107  f125  f143  f161  f18   f198  f215  f233  f251  f27   f288  f35   f53  f71  f9
f108  f126  f144  f162  f180  f199  f216  f234  f252  f270  f289  f36   f54  f72  f90
f109  f127  f145  f163  f181  f2    f217  f235  f253  f271  f29   f37   f55  f73  f91
f11   f128  f146  f164  f182  f20   f218  f236  f254  f272  f290  f38   f56  f74  f92
f110  f129  f147  f165  f183  f200  f219  f237  f255  f273  f291  f39   f57  f75  f93
f111  f13   f148  f166  f184  f201  f22   f238  f256  f274  f292  f4    f58  f76  f94
f112  f130  f149  f167  f185  f202  f220  f239  f257  f275  f293  f40   f59  f77  f95
f113  f131  f15   f168  f186  f203  f221  f24   f258  f276  f294  f41   f6   f78  f96
f114  f132  f150  f169  f187  f204  f222  f240  f259  f277  f295  f42   f60  f79  f97
f115  f133  f151  f17   f188  f205  f223  f241  f26   f278  f296  f43   f61  f8   f98
f116  f134  f152  f170  f189  f206  f224  f242  f260  f279  f297  f44   f62  f80  f99
[root@centos7 renametest]# rename f f00 f?            # 这个f?匹配到f1..f9这些文件, 然后把f替换为f00,就变成了f001..f009
[root@centos7 renametest]# rename f f0 f??            # 这个f??匹配到f10..f99这些文件, 然后把f替换为f0,就变成了f010..f099
[root@centos7 renametest]# ls                         # 再次查看
f001  f023  f045  f067  f089  f111  f133  f155  f177  f199  f221  f243  f265  f287
f002  f024  f046  f068  f090  f112  f134  f156  f178  f200  f222  f244  f266  f288
f003  f025  f047  f069  f091  f113  f135  f157  f179  f201  f223  f245  f267  f289
f004  f026  f048  f070  f092  f114  f136  f158  f180  f202  f224  f246  f268  f290
f005  f027  f049  f071  f093  f115  f137  f159  f181  f203  f225  f247  f269  f291
f006  f028  f050  f072  f094  f116  f138  f160  f182  f204  f226  f248  f270  f292
f007  f029  f051  f073  f095  f117  f139  f161  f183  f205  f227  f249  f271  f293
f008  f030  f052  f074  f096  f118  f140  f162  f184  f206  f228  f250  f272  f294
f009  f031  f053  f075  f097  f119  f141  f163  f185  f207  f229  f251  f273  f295
f010  f032  f054  f076  f098  f120  f142  f164  f186  f208  f230  f252  f274  f296
f011  f033  f055  f077  f099  f121  f143  f165  f187  f209  f231  f253  f275  f297
f012  f034  f056  f078  f100  f122  f144  f166  f188  f210  f232  f254  f276  f298
f013  f035  f057  f079  f101  f123  f145  f167  f189  f211  f233  f255  f277  f299
f014  f036  f058  f080  f102  f124  f146  f168  f190  f212  f234  f256  f278  f300
f015  f037  f059  f081  f103  f125  f147  f169  f191  f213  f235  f257  f279
f016  f038  f060  f082  f104  f126  f148  f170  f192  f214  f236  f258  f280
f017  f039  f061  f083  f105  f127  f149  f171  f193  f215  f237  f259  f281
f018  f040  f062  f084  f106  f128  f150  f172  f194  f216  f238  f260  f282
f019  f041  f063  f085  f107  f129  f151  f173  f195  f217  f239  f261  f283
f020  f042  f064  f086  f108  f130  f152  f174  f196  f218  f240  f262  f284
f021  f043  f065  f087  f109  f131  f153  f175  f197  f219  f241  f263  f285
f022  f044  f066  f088  f110  f132  f154  f176  f198  f220  f242  f264  f286

05-2017-11-09-练习-head-tr-管道

练习1-tr,cut,sort,tail

1、 将/etc/passwd 文件的前5行内容转化为大写后保存到/tmp/passwd.out文件

[root@centos6 dirtest]# head -n 5 /etc/passwd |tr 'a-z' 'A-Z' > /tmp/passwd.out

2、 将登陆到当前系统的用户信息的后3行信息转化为大写保存到/tmp/who.out文件中

[root@centos6 dirtest]# who |tail -n 3  | tr 'a-z' 'A-Z' > /tmp/who.out

3、 取出/etc/passwd 文件中的第6行至第10行,并将这些信息按第3个字段数值进行排序,最后显示进显示第一个字段

[root@centos6 ~]# head -n 10 /etc/passwd | tail -n 5 | sort -t ":" -k 3 | cut -d ":" -f 1

## 练习2-cat,who,seq

1、将/etc/issue 文件中的内容转换为大写后保存至/tmp/issue.out 文件中

[root@centos7 app]# cat /etc/issue |tr "a-z" "A-Z" >/tmp/issue.out

2 、将当前系统登录用户的信息转换为大写后保存至/tmp/who.out 文件中

[root@centos7 app]# who| tr "a-z" "A-Z" > /tmp/who.out

3 、一个linux 用户给root 发邮件,要求邮件标题为”help” ,邮件正文如下:Hello, I am 用户名,The system version is here,please help me tocheck it ,thanks! 操作系统版本信息

[root@centos7 app]# echo "hello,I am $USER, The system version is $(uname -r), please help me to check it ,thanks" | mail -s "help" root

4 、将/root/ 下文件列表,显示成一行,并文件名之间用空格隔开

[root@centos7 app]# ls -1 /root  |tr "\n" " "

5 、计算1+2+3+..+99+100 的总和

[root@centos7 app]# seq -s + 1 100 |bc
5050
[root@centos7 app]# echo {1..100} |tr " " "+" |bc
5050

6 、删除Windows 文本文件中的‘^M’ 字符

[root@centos7 app]# cat -A win.txt
zhaojiedi ^M$
hello world^M$
end^M$
[root@centos7 app]# dos2unix win.txt
dos2unix: converting file win.txt to Unix format ...
[root@centos7 app]# cat -A win.txt
zhaojiedi $
hello world$
end$

7 、处理字符串“xt.,l 1 jr#!$mn 2 c*/fe 3 uz 4 ”,只保留其中的数字和空格

[root@centos7 app]# echo 'xt.,l 1 jr#win.txtmn 2 c*/fe 3 uz 4 ' | tr -cd "[0-9] "

8 、将PATH 变量每个目录显示在独立的一行

[root@centos7 app]# echo $PATH |tr ":" "\n"
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/root/bin

9、 将 指定文件中0-9 分别替代成a-j

[root@centos7 app]# cat /etc/fstab |tr [0-9] [a-j]
#
# /etc/fstab
# Created by anaconda on Tue Nov  a aa:aa:aa aaaa
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(a), findfs(a), mount(a) and/or blkid(a) for more info
#
UUID=aacceaaa-acae-abbc-aeaf-afadbadcfaea /                       exta    defaults        a a
UUID=faeaaaea-bcde-aaaa-adca-caabaaaaeaaf /app                    exta    noatime        a a
UUID=adacbeaa-ffba-aadf-bacf-aabeafaaaaaa /boot                   exta    defaults        a a
UUID=bacaaafa-aeea-abac-aeaa-edaacbaacaaa swap                    swap    defaults        a a

10 、将/etc/centos-release文件中每个单词(由字母组成)显示在独立的一行,并无空行

[root@centos7 app]# cat /etc/centos-release | tr -sc "a-zA-Z " "\n"

06-2017-11-16-练习-用户管理

练习1-useradd,usermod

1、创建用户gentoo,附加组为distro和linux,默认shell为/bin/csh,注释信息”gentoo distribution”

[root@centos6 ~]# useradd -G distro,linux -s /bin/csh -c "gentoo distribution" gentoo

练习2-恢复用户家目录

1、创建好的用户wang,用户家目录被删除的,如何还原。

模拟一个破坏环境

[root@centos6 ~]# useradd wang                          #创建用户
[root@centos6 ~]# echo "oracle" | passwd --stdin wang   #设置密码
Changing password for user wang.
passwd: all authentication tokens updated successfully.
[root@centos6 ~]# rm -rf /home/wang                     #模拟恶意删除家目录
[root@centos6 ~]# ll /home/wang                         #查看
ls: cannot access /home/wang: No such file or directory
[root@centos6 home]# su - test01                        #切换到普通用户
[test01@centos6 ~]$ su - wang                           #从普通用户切换到wang
Password:
su: warning: cannot change directory to /home/wang: No such file or directory
-bash-4.1$                                                #这里家目录没有就是-bash-4.1的样子了。

修复过程

[root@centos6 home]# cp -r /etc/skel /home/wang   #复制模板文件夹
[root@centos6 home]# ll
total 28
drwx------.  5 git       git       4096 Nov  9 23:51 git
drwx------.  4 nginx     nginx     4096 Nov 11 15:39 nginx
drwx------.  4 test      test      4096 Nov 11 15:04 test
drwx------.  4 test01    test01    4096 Nov 11 15:04 test01
drwx------.  4 test03    test03    4096 Nov 11 15:33 test03
drwxr-xr-x.  4 root      root      4096 Nov 11 16:05 wang
drwx------. 25 zhaojiedi zhaojiedi 4096 Nov 11 15:03 zhaojiedi
[root@centos6 home]# chown -R  wang:wang wang #修改所有者和组
[root@centos6 home]# chmod  700 wang        #修改权限700
[root@centos6 home]# ll                       #检查下权限和所有者
total 28
drwx------.  5 git       git       4096 Nov  9 23:51 git
drwx------.  4 nginx     nginx     4096 Nov 11 15:39 nginx
drwx------.  4 test      test      4096 Nov 11 15:04 test
drwx------.  4 test01    test01    4096 Nov 11 15:04 test01
drwx------.  4 test03    test03    4096 Nov 11 15:33 test03
drwx------.  4 wang      wang      4096 Nov 11 16:05 wang
drwx------. 25 zhaojiedi zhaojiedi 4096 Nov 11 15:03 zhaojiedi
[root@centos6 home]# su - test01             #切换到普通用户
[test01@centos6 ~]$ su - wang                #切换到wang用户
Password:
[wang@centos6 ~]$ l.                         #查看文件
.  ..  .bash_logout  .bash_profile  .bashrc  .emacs  .gnome2  .mozilla

练习3-useradd,passwd

1 、创建用户gentoo ,附加组为bin 和root ,默认shell为 为/bin/csh ,注释信息为”Gentoo Distribution”

[root@centos6 home]# useradd -G bin,root -s /bin/csh -c "Gentoo Distribution" gentoo

2 、创建下面的用户、组和组成员关系如下:

  • 名字为admins 的组
  • 用户natasha ,使用admins 作为附属组
  • 用户harry ,也使用admins 作为附属组
  • 用户sarah ,不可交互登录系统,且不是admins 的成员,
  • natasha ,harry ,sarah 密码都是centos
[root@centos6 home]# groupadd admins
[root@centos6 home]# useradd -G admins natasha
[root@centos6 home]# useradd -G admins harry
[root@centos6 home]# useradd -s /sbin/nologin
[root@centos6 home]# useradd -s /sbin/nologin sarah
[root@centos6 home]# echo "centos" | passwd --stdin natasha
Changing password for user natasha.
passwd: all authentication tokens updated successfully.
[root@centos6 home]# echo "centos" | passwd --stdin harry
Changing password for user harry.
passwd: all authentication tokens updated successfully.
[root@centos6 home]# echo "centos" | passwd --stdin sarah
Changing password for user sarah.
passwd: all authentication tokens updated successfully.

练习4-批量添加用户和修改密码

批量添加用户

[root@centos6 home]# echo user{00..10} |tr " " "\n"   |xargs -L  1  useradd  #cent6创建11个用户
[root@centos6 ~]# tail -n 11 /etc/passwd >>need_to_add_users.txt             #cent6把/etc/passwd后面的11行数据到文件中
[root@centos6 ~]# sz need_to_add_users.txt    #在cent6使用sz上传文件
[root@centos7 ~]# rz                          #cent7 接受这个文件
[root@centos7 ~]# newusers  < need_to_add_users.txt #批量添加
[root@centos7 ~]# tail -n 11 /etc/passwd
user00:x:607:608::/home/user00:/bin/bash
user01:x:608:609::/home/user01:/bin/bash
user02:x:609:610::/home/user02:/bin/bash
user03:x:610:611::/home/user03:/bin/bash
user04:x:611:612::/home/user04:/bin/bash
user05:x:612:613::/home/user05:/bin/bash
user06:x:613:614::/home/user06:/bin/bash
user07:x:614:615::/home/user07:/bin/bash
user08:x:615:616::/home/user08:/bin/bash
user09:x:616:617::/home/user09:/bin/bash
user10:x:617:618::/home/user10:/bin/bash
[root@centos7 ~]# id user01
uid=608(user01) gid=609(user01) groups=609(user01)

批量改密码

[root@centos7 ~]# nano all_pass.txt #编辑一个密码文件
[root@centos7 ~]# cat all_pass.txt  #查看
user00:oracle
user01:oracle
user02:oracle
user03:oracle
user04:oracle
user05:oracle
user06:oracle
user07:oracle
user08:oracle
user09:oracle
user10:oracle
[root@centos7 ~]# cat all_pass.txt  | chpasswd #批量修改密码

练习5-权限判断

1 、当用户xiaoming 对/testdir 目录无执行权限时,意味着无法做哪些操作?

无法进入目录

2 、当用户xiaoqiang 对/testdir 目录无读权限时,意味着无法做哪些操作?

无法查看目录下的文件

3 、当用户wangcai 对/testdir 目录无写权限时,该目录下的只读文件file1 是否可修改和删除?

不可修改,无法删除

4 、当用户wangcai 对/testdir 目录有写和执行权限时,该目录下的只读文件file1 是否可修改和删除?

不可修改,但是可以删除

5 、复制/etc/fstab 文件到/var/tmp 下,设置文件所有者为wangcai 读写权限,所属组为sysadmins 组有读写权限,其他人无权限

[root@centos7 app]$ chown wangcai:sysadmins /var/tmp/fstab
[root@centos7 app]$ chmod 660 /var/tmp/fstab

练习6-getfacl,setfacl,chmod

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

分析下题目 * 1)创建一个目录 * 2)自动属于g1组,这个应该设置gid,且组名为g1 * 3)alice 在g2组,需要先创建用户,读写权限 * 4)tome在g3组, 需要创建用户,有读权限 * 5)其他用户无权限

[root@centos6 ~]# mkdir /testdir/dir -pv
mkdir: created directory `/testdir'
mkdir: created directory `/testdir/dir'
[root@centos6 ~]# groupadd g1
[root@centos6 ~]# chgrp  g1 /testdir/dir/
[root@centos6 ~]# chmod g+s /testdir/dir/
[root@centos6 ~]# cd /testdir/dir/
[root@centos6 dir]# touch a.txt
[root@centos6 dir]# ll
total 0
-rw-r--r--. 1 root g1 0 Nov 13 01:44 a.txt
[root@centos6 dir]# groupadd g2
[root@centos6 dir]# useradd alice -G g2
[root@centos6 dir]# setfacl -m "d:g:g2:rw" -R /testdir/dir/
[root@centos6 dir]# groupadd g3
[root@centos6 dir]# useradd tom -G g3
[root@centos6 dir]# setfacl -m "d:g:g3:r" -R /testdir/dir/
[root@centos6 dir]# ll
total 0
-rw-r--r--. 1 root g1 0 Nov 13 01:44 a.txt
[root@centos6 dir]# chmod o-rx /testdir/dir/ -R
[root@centos6 dir]# setfacl -m "d:o::---" -R /testdir/dir/

2 、备份/testdir/dir 里所有文件的ACL 权限到/root/acl.txt 中,清除/testdir/dir 中所有ACL 权限,最后还原ACL

[root@centos6 dir]# getfacl /testdir/dir -R >/root/acl.txt
getfacl: Removing leading '/' from absolute path names
[root@centos6 dir]# cd /testdir/
[root@centos6 testdir]# getfacl -R dir > /root/acl.txt
[root@centos6 testdir]# setfacl -R -b dir
[root@centos6 testdir]# setfacl --restore /root/acl.txt
[root@centos6 testdir]# getfacl -R dir

07-2017-11-10-练习-wc-useradd

练习1-编写统计行数脚本

1、编写一个脚本,脚本可以接受一个以上的文件路径作为参数,显示每个文件所拥有的行数,本次工统计了多少个文件执行了行数统计

#!/bin/bash

for file in $* ; do
        line=$(wc -l /etc/issue |cut -d " " -f 1)
        echo $file has $line lines.
done
echo has $# files

练习2-创建用户并统计个数

1、 编写一个脚本传递2个以上的字符串当作用户名创建这些用户,且密码同用户名总结说明创建了多少用户

#!/bin/bash
let cnt=0
for user in $*; do
        echo $user
        if id $user >/dev/null 2>&1;then
                echo $user exist.
        else
                if useradd $user >/dev/null 2>&1;then
                        let cnt++
                        echo $user | passwd --stdin $user >/dev/null 2>&1
                        echo $user created success.
                else
                        echo $user created failed.
                fi
        fi

done

if [ $cnt -eq $# ] ; then
        echo create $cnt users.
else
        echo $# users ,but create $cnt users.
fi

08-2017-11-10-练习-grep-文本

练习1-grep使用

1、 显示/proc/meminfo文件中以大写或者小写S开头的行

[root@centos7 sh]# egrep "^[s|S]" /proc/meminfo
SwapCached:            0 kB
SwapTotal:      134217724 kB
SwapFree:       134217724 kB
Shmem:              9468 kB
Slab:              95508 kB
SReclaimable:      42972 kB
SUnreclaim:        52536 kB

2、显示/etc/passwd文件中默认shell为非/sbin/nologin的用户。

[root@centos7 sh]# egrep  -v "/sbin/nologin" /etc/passwd | cut -d ":" -f1
root
sync
shutdown
halt
zhaojiedi
u2
u3
u1

3、显示/etc/passwd文件中器默认shell为/bin/bash的用户,进一步进现实上述结果中id最大的用户

[root@centos7 sh]# cat /etc/passwd | egrep "/bin/bash" | sort -t ":" -k 3 -n |tail -n 1 | cut -d ":" -f1
u1

4、找出/etc/passwd文件中的一位数或者2位数。

[root@centos7 sh]# cat /etc/passwd | egrep "\b[0-9]{1,2}\b"
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin

5、显示/boot/grub/grub.conf中以至少一个空白字符开头的行

[root@centos7 grub2]# cat /boot/grub2/grub.cfg | egrep "^[[:space:]]+"

6、显示etc/rc.d/init.d/functions文件中,以#开头,后面跟至少一个空白字符,而后有至少一个非空白字符行

[root@centos7 grub2]# cat /etc/rc.d/init.d/functions | egrep "^#[[:space:]]+[^[:space:]]+"

7、找出netstat -tan命令执行结果中以LISTEN结尾的行。

[root@centos7 grub2]# netstat -tan |egrep "LISTEN[[:space:]]$"
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN
tcp6       0      0 :::111                  :::*                    LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 ::1:631                 :::*                    LISTEN
tcp6       0      0 ::1:25                  :::*                    LISTEN

8、添加用户bash,testbash,basher,nologin,(shell为/sbin/nologin),而找出当前系统上用户名和默认shell相同的用户。

[root@centos7 grub2]# cat /etc/passwd |egrep "([[:alpha:]]+):.*/\1$"
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
nologin:x:1008:1008::/home/nologin:/sbin/nologin

练习2-grep

1 、找出ifconfig ” “网卡名” 命令结果中本机的IPv4 地址

[root@centos7 app]# ifconfig ens33 |head -n 2 |tail -n 1 | cut -d " " -f10

2 、查出分区空间使用率的最大百分比值


[root@centos7 app]# df |cut -c 44-46 |sort -n | tail -n 1
100

3 、查出用户UID 最大值的用户名、UID 及shell 类型

[root@centos7 app]# cat /etc/passwd  | sort -t ":" -k 3 -nr |head -n 1 |cut -d ":" -f1,3,7
nfsnobody:65534:/sbin/nologin

4 、查出/tmp 的权限,以数字方式显示

[root@centos7 app]#  stat /tmp | head -n 4 |tail -n 1 | cut -d "/" -f1 |cut -d "(" -f2
1777

5 、统计当前连接本机的每个远程主机IP 的连接数,并按从大到小排序

[root@centos7 app]# ss -tn | grep "ESTAB"| tr  -s " "|tr  " " ":"  |cut -d ":" -f6 | sort | uniq -c |sort -r
2 172.18.1.25

练习3-diff,patch

1、获取文件修改改变, 并使用补丁文件恢复文件

[root@centos7 ~]# cd /app
[root@centos7 app]# cp /etc/fstab  f1
cp: overwrite ‘f1’? y
[root@centos7 app]# cp f1 f2
cp: overwrite ‘f2’? y
[root@centos7 app]# echo "add a new line " >> f2
[root@centos7 app]# diff -u f1 f2 >f1-f2.patch
[root@centos7 app]# cat f1
f1           f1-f2.patch  f1.txt
[root@centos7 app]# cat f1-f2.patch
--- f1  2017-11-21 08:16:16.877021441 +0800
+++ f2  2017-11-21 08:16:42.153022966 +0800
@@ -10,3 +10,4 @@
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0
+add a new line
[root@centos7 app]# mv f2 f2.bak
[root@centos7 app]# patch -b f1 f1-f2.patch
bash: patch: command not found...
[root@centos7 app]# rpm -ivh /misc/cd/Packages/pa
[root@centos7 app]# patch -b f1 f1-f2.patch
patching file f1
[root@centos7 app]# cat f1

#
# /etc/fstab
# Created by anaconda on Tue Nov  7 16:07:01 2017
#
# 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=59ccea87-3c4e-4bbc-9e2f-3fadb1dcf2e6 /                       ext4    defaults        1 1
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0
add a new line
[root@centos7 app]# cat f1.orig

#
# /etc/fstab
# Created by anaconda on Tue Nov  7 16:07:01 2017
#
# 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=59ccea87-3c4e-4bbc-9e2f-3fadb1dcf2e6 /                       ext4    defaults        1 1
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0

练习4-egrep

1 、显示/proc/meminfo 文件中以大小s 开头的行( 要求:使用两种方法)

[root@centos7 app]# cat /proc/meminfo  |grep -i "^s"
SwapCached:            0 kB
SwapTotal:      134217724 kB
SwapFree:       134217724 kB
Shmem:             26944 kB
Slab:             135480 kB
SReclaimable:      79096 kB
SUnreclaim:        56384 kB
[root@centos7 app]# cat /proc/meminfo  |grep  "^[sS]"
SwapCached:            0 kB
SwapTotal:      134217724 kB
SwapFree:       134217724 kB
Shmem:             26944 kB
Slab:             135480 kB
SReclaimable:      79096 kB
SUnreclaim:        56384 kB

2 、显示/etc/passwd 文件中不以/bin/bash 结尾的行

[root@centos7 app]# cat /etc/passwd |grep -v "/bin/bash$"

3 、显示用户rpc 默认的shell 程序

[root@centos7 app]# cat /etc/passwd |grep "^rpc:" |cut -d ":" -f7
/sbin/nologin

4 、找出/etc/passwd 中的两位或三位数

[root@centos7 app]# cat /etc/passwd |egrep "\b[0-9]{2,3}\b"

5 、显示CentOS7 的/etc/grub2.cfg 文件中,至少以一个空白字符开头的且后面存非空白字符的行

[root@centos7 app]# cat /etc/grub2.cfg | egrep "^[[:space:]]+[^[:space:]]*"

6 、找出“netstat -tan” 命令的结果中以‘LISTEN’ 后跟任意多个空白字符结尾的行

[root@centos7 app]# netstat -tan  |grep "LISTEN[[:space:]]*$"

7 、显示CentOS7 上所有系统用户的用户名和UID

[root@centos7 app]# cat /etc/passwd |grep "^[^:]*:[^:]*:[0-9]{2,3}:.*" |cut -d ":" -f 1,3

8 、添加用户bash 、testbash 、basher 、sh 、nologin( 其shell为/sbin/nologin), 找出/etc/passwd 用户名同shell 名的行

[root@centos7 app]# cat /etc/passwd |egrep "^([^:]*):.*\b\1$"
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
bash:x:1005:1005::/home/bash:/bin/bash
nologin:x:1008:1008::/home/nologin:/sbin/nologin

9 、利用df 和grep取出磁盘各分区利用率,并从大到小排序

[root@centos7 app]# df |grep "[0-9]{1,3}%" -o |grep "[0-9]{1,3}" -o |sort -nr

练习5-egrep

1 、显示三个用户root 、mage 、wang 的UID 和默认shell

[root@centos7 app]# cat /etc/passwd |grep "(root|mage|wang)" |cut -d ":" -f3,7

2 、找出/etc/rc.d/init.d/functions 文件中行首为某单词(包 包括下划线) 后面跟一个小括号的行

[root@centos7 app]# cat /etc/rc.d/init.d/functions  | egrep "^(_|[[:alpha:]])[[:alnum:]_]*[[:space:]]*\(\)" -o

3 、使用egrep 取出/etc/rc.d/init.d/functions 中其基名

[root@centos7 app]# echo "/etc/rc.d/init.d/function" |egrep -o ".*[^/]+" |egrep "[^/]*$" -o
[root@centos7 app]# echo "/etc/rc.d/init.d/" |egrep -o ".*[^/]+" |egrep "[^/]*$" -o

4 、使用egrep 取出上面路径的目录名

[root@centos7 app]#  echo "/etc/rc.d/init.d/fucntion" | egrep -o ".*[^/]+" |grep ".*/" -o |grep -o ".*[^/]+"
[root@centos7 app]#  echo "/etc/rc.d/init.d/" | egrep -o ".*[^/]+" |grep ".*/" -o |grep -o ".*[^/]+"

5 、统计last 命令中以root 登录的每个主机IP 地址登录次数

[root@centos7 app]# last | grep "^root\b" |cut -d " " -f1,14 |sort -t " " -k2 |uniq -c
17 root 172.18.1.25

6 、利用扩展正则表达式分别表示0-9 、10-99 、100-199、 200-249 、250-255

[root@centos7 app]# echo "123,434,545j4,32432,22,232,32,255" | grep "(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))" -o
123
43
54
32
43
22
232
32
255

7 、显示ifconfig 命令结果中所有IPv4 地址

[root@centos7 app]# ifconfig |egrep "([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))(\.([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3}"  -o
172.18.1.250
255.255.0.0
172.18.255.255
127.0.0.1
255.0.0.0
192.168.122.1
255.255.255.0
192.168.122.255

8 、将此字符串:welcome to magedu linux 中的每个字符去重并排序,重复次数多的排到前面

[root@centos7 app]# echo "welcome to magedu linux"  |grep "[[:alnum:]]"  -o |sort |uniq -c   | sort -nrt " " -k2 |cut -d " " -f8 |tr -d "\n"

09-2017-11-13-练习-find

练习1-find

1、查找/var目录属主为root且属组为mail的所有文件。

find /var/ -user root -group mail

2、查找/usr目录下不属于root,bin,hadoop的文件。

find /usr/ -not \( -user root -o -user bin -o -user hadoop \)

3、查找/etc/目录下最近一周内其内容修改过的,且不属于root且不属于hadoop。

find /etc/ -mtime -7 -not -user root -not -user hadoop

4、查找系统上没有属主或属组,且最近一个月曾被访问过。

find / -nouser -nogroup  -atime -30

5、查找/etc/目录不大于1M且类型为普通文件的所有文件

find /etc/ -size -$[1*1024*1024] -type f

6、查找/etc/目录所有用户都没有写权限的文件

find /etc/ -not -perm /222 -ls

7、查找/etc目录下只有一类用户没有写权限的文件

find /etc/  \( -perm -220 -o -perm -202 -o -perm -022 \) -not -perm -222

8、查找/etc/init.d目录下,所有用户都有执行权限,且其他用户有写权限的文件

find /etc/init.d/ -perm -111 -perm -002

练习2

1、查找/var目录下属主为root,且属组为mail的所有文件

find /var/ -user root -group mail

2、查找/var目录下不属于root、lp、gdm的所有文件

find /var/ -not \( -user root -o -user lp -o -user  gdm  \)

3、查找/var目录下最近一周内其内容修改过,同时属主不为root,也不是postfix的文件

find /var  find /var -mtime -7 -not \( -user root -o -user postfix \)

4、查找当前系统上没有属主或属组,且最近一个周内曾被访问过的文件

find / -nouser -nogroup -mtime -7

5、查找/etc目录下大于1M且类型为普通文件的所有文件

find /etc/ -size +1M -type f

6、查找/etc目录下所有用户都没有写权限的文件

find /etc/ -not  -perm /222

7、查找/etc目录下至少有一类用户没有执行权限的文件

find /etc/ \( -perm -110 -o -perm -101 -o -perm -011 \) -not -perm -111

8、查找/etc/init.d目录下,所有用户都有执行权限,且其它用户有写权限的文件

find /etc/init.d/ -perm -111 -perm -002

10-2017-11-14-练习-vim

练习1

1) 复制/etc/grub.conf至/tmp目录,删除/tmp/grub.conf文件中的开头的空白字符

:%s@[[:space:]]\+@@g

2)复制/etc/rc.d/rc.sysinit至/tmp目录,将/tmp/rc.sysinit文件中的至少一个空白字符开头的行行首加#号。

:%s@^[[:space:]]\+@#\0@g

3)删除/tmp/rc.sysinit文件中以#开头,且后面跟了至少一个空白字符的行的行首的#号和空白字符。

:%s@^#[[:space:]]\+(.*)@\1@g

4)为/tmpgrub.conf文件的前3行加#号

:1,3s@.*@#\0@g

5)将/etc/yum.repos.d/CentOS-Media.repo文件中的enable=0he gpgcheck=0改成1

:%s@enabled=0@enabled=1@
:%s@gpgcheck=0@gpgcheck=1@

6)复制/etc/rc.d/init.d/functions至/tmp目录,替换/tmp/functions文件中的/etc/sysconfig/init为/var/log

:%s@/etc/sysconfig/init@/var/log@

12-2017-11-23-练习-bash

练习1

1、编写脚本/root/bin/systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小

#!/bin/bash
#================================================
#FileName   :systeminfo_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 09:01:32
#Version    :V1.0
#Other      :
#================================================
hostname=`hostname`
ipv4=`ifconfig ens33 |grep "inet " |egrep "[0-9]{1,3}(\.[0-9]{1,3}){3}" -o |head -n 1`
os_version=`cat /etc/redhat-release`
kernel_version=`uname -r`
cpu_info=`lscpu |grep "Model name:" |cut -c 12- |grep "[^[:space:]].*" -o`
mem_size=`cat /proc/meminfo  |grep "MemTotal" |cut -c 10- | grep "[^[:space:]].*" -o`
disk_size=`df -h`

echo "system info is
===========================================
hostname=$hostname
ipv4=$ipv4
kernel_version=$kernel_version
cpu_info=$cpu_info
mem_size=$mem_size
disk_size=$disk_size
============================================
"

2、编写脚本/root/bin/backup.sh,可实现每日将/etc/目录备份到/root/etcYYYY-mm-dd中

#!/bin/bash
#Author:     root
#Description:
#DateTime:   2017-11-22 14:53:42
#Version:    V1.0

cp -a /etc /root/etc$(date "+%Y-%m-%d")

3、编写脚本/root/bin/disk.sh,显示当前硬盘分区中空间利用率最大的值

#!/bin/bash
#================================================
#FileName   :disk_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 09:25:00
#Version    :V1.0
#Other      :
#================================================

val=`df  |egrep "[0-9]{1,3}%" -o |tr -d "%" |sort  -n |tail -n 1`
echo val

4、编写脚本/root/bin/links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排序

#!/bin/bash
#================================================
#FileName   :links_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 09:28:28
#Version    :V1.0
#Other      :
#================================================

links=`ss -tan |grep "^ESTAB" |egrep "[0-9]{1,3}(\.[0-9]{1,3}){3}:[0-9]{1,6}[[:space:]]*$" -o |cut -d ":" -f 1 |sort |uniq -c | sort  -r -n -t " " -k1`
echo "$links"

练习2

1、编写脚本/root/bin/sumid.sh,计算/etc/passwd文件中的第10个用户和第20用户的ID之和

#!/bin/bash
#================================================
#FileName   :sumid_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 10:33:24
#Version    :V1.0
#Other      :
#================================================

uid_10=`cat /etc/passwd |head -n 10 |tail -n 1 |cut -d ":" -f 3`
uid_20=`cat /etc/passwd |head -n 20 |tail -n 1 |cut -d ":" -f 3`
sum_id=$[uid_10+uid_20]
echo $sum_id

2、编写脚本/root/bin/sumspace.sh,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和

#!/bin/bash
#================================================
#FileName   :sumspace_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 10:39:22
#Version    :V1.0
#Other      :
#================================================

# need to check  paramter number
file1_space_line=`cat $1  |grep "^$" |wc -l`
file2_space_line=`cat $2  |grep "^$" |wc -l`

sum_space_line=$[file1_space_line+file2_space_line]
echo $sum_space_line

3、编写脚本/root/bin/sumfile.sh,统计/etc, /var, /usr目录中共有多少个一级子目录和文件

#!/bin/bash
#================================================
#FileName   :sumfile_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-23 10:44:17
#Version    :V1.0
#Other      :
#================================================

let sumfiles=$[`ls -A -1 /etc |wc -l`]+$[`ls -A -1 /usr | wc -l`]+$[`ls -A -1 /var |wc -l`]
echo $sumfiles

练习3

1、编写脚本/root/bin/argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数

#!/bin/bash
#================================================
#FileName   :argsnum_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 18:55:43
#Version    :V1.0
#Other      :
#================================================

[ $# -lt 1 ] && echo "must one parameter" && exit 1
[ ! -f $1 ] && echo " file not exist" && exit 2
echo `cat $1 |grep "^[[:space:]]*$" |wc -l`

2、编写脚本/root/bin/hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”

#!/bin/bash
#================================================
#FileName   :hostping_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 19:00:40
#Version    :V1.0
#Other      :
#================================================
[ $# -lt 1 ] && echo "must a parameter " && exit 1
[[ "$1" =~ ^(([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))(\.([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3})$ ]]
[ $? -ne 0 ] && echo " ip is not reacheable" && exit 2
ping -t 1 -c 1 $1 &>/dev/null  && echo "ip is reachable" ||echo "ip is not reachable"

3、编写脚本/root/bin/checkdisk.sh,检查磁盘分区空间和inode使用率,如果超过80%,就发广播警告空间将满

#!/bin/bash
#================================================
#FileName   :checkdisk_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 11:25:31
#Version    :V1.0
#Other      :
#================================================
declare -i data_limit=10
declare -i inode_limit=10
declare -i data_block_max=`df |egrep "/dev/[sh]d.*" |egrep "[0-9]{1,3}%" -o |egrep "[0-9]{1,3}" -o |sort -nr |head -n 1`
declare -i inode_block_max=`df -i |egrep "/dev/[sh]d.*" |egrep "[0-9]{1,3}%" -o |egrep "[0-9]{1,3}" -o |sort -nr |head -n 1`


[ $data_block_max -ge $data_limit ] && wall "data_block beyond $data_limit"
[ $inode_block_max -ge $inode_limit ] && wall "inode_block beyond $inode_limit"

练习4

1、编写脚本/bin/per.sh,判断当前用户对指定的参数文件,是否不可读并且不可写

#!/bin/bash
#================================================
#FileName   :per_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 19:40:48
#Version    :V1.0
#Other      :
#================================================

[ $# -lt 1 ] && echo " must a parameter" && exit 1

[ ! -r $1 ] && [ ! -w $1 ] && echo " no read,and write" || echo " other"

2、编写脚本/root/bin/excute.sh ,判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,否则提示用户非脚本文件

#!/bin/bash
#================================================
#FileName   :excute_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 19:50:29
#Version    :V1.0
#Other      :
#================================================

[ $# -lt 1 ] && echo "must one parameter" && exit 1
[ ! -f $1 ] && echo "file not exist"
[[ "$1" =~ .*.sh$ ]] && chmod a+x $1 || echo "not sh file  "

3、编写脚本/root/bin/nologin.sh和login.sh,实现禁止和充许普通用户登录系统

#!/bin/bash
#================================================
#FileName   :nologin.sh_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 19:56:30
#Version    :V1.0
#Other      :
#================================================
[ ! -f /etc/nologin ] && touch /etc/nologin

[root@centos7 sh]# cat login.sh_46_zhaojiedi.sh
#!/bin/bash
#================================================
#FileName   :login.sh_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 19:57:23
#Version    :V1.0
#Other      :
#================================================

[ -f /etc/nologin ] && rm -rf /etc/nologin

练习5

1、让所有用户的PATH环境变量的值多出一个路径,例如:/usr/local/apache/bin

[root@centos7 job]# echo "export PATH=$PATH:/usr/local/apache/bin" >>/etc/profile.d/path.sh

2、用户root登录时,将命令指示符变成红色,并自动启用如下别名:rm=‘rm –i’cdnet=‘cd /etc/sysconfig/network-scripts/’ editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eth0’ editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eno16777736 或 ifcfg-ens33 ’ (如果系统是CentOS7)

[root@centos7 ~]# echo "PS1=\"\033[1;31m$PS1\033[0m\"" >>/root/.bash_profile
[root@centos7 .etc]# cat alias.sh
alias rm='rm-i'
alias cdnet='cd /etc/sysconfig/network-scripts'
alias editeth0='vim /etc/sysconfig/network-scripts/ifcfg-eth0'
alias editens33='vim /etc/sysconfig/network-scripts/ifcfg-ens33'
# 添加如下行到/root/.bashrc文件中去
. ~/.etc/alias.sh
echo ". ~/.etc/alias.sh" >> /root/.bashrc

3、任意用户登录系统时,显示红色字体的警示提醒信息“Hi,dangerous!”

[root@centos7 .etc]# cat -A /etc/motd
^[[31mHi,dangerous^[[0m$

4、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等

#!/bin/bash
#change filename
filename=$1_46_zhaojiedi.sh
#check file exist
[ -e $filename ] && echo "$filename has exist" && exit 1
# create file and add x
touch $filename
chmod u+x $filename
#add info

echo "#!/bin/bash
#================================================
#FileName   :$(basename $filename)
#Author     :zhaojiedi
#Description:
#DateTime   :$(date "+%Y-%m-%d %H:%M:%S")
#Version    :V1.0
#Other      :
#================================================
" >> $filename


# start vim
vim $filename  +

5、编写用户的环境初始化脚本reset.sh,包括别名,登录提示符,vim的设置,环境变量等

. alias.sh
. prompt.sh
. vim.sh
. path.sh

13-2017-11-25-练习-压缩

1 、使用不同压缩工具对同一个文件进行压缩,并比较大小

[root@centos7 test]$ compress -c messages-20171113 > messages.Z
[root@centos7 test]$ ll
total 3684
-rw-------. 1 root root 1678853 Nov 28 09:42 messages-20171113
-rw-------. 1 root root 1678853 Nov 28 09:45 messages-20171113.bak
-rw-r--r--. 1 root root  411094 Nov 28 09:47 messages.Z
[root@centos7 test]$ gzip -c messages-20171113 > message.gz
[root@centos7 test]$ ll
total 3892
-rw-r--r--. 1 root root  212778 Nov 28 09:48 message.gz
-rw-------. 1 root root 1678853 Nov 28 09:42 messages-20171113
-rw-------. 1 root root 1678853 Nov 28 09:45 messages-20171113.bak
-rw-r--r--. 1 root root  411094 Nov 28 09:47 messages.Z
[root@centos7 test]$ xz -c messages-20171113 >messages.xz
[root@centos7 test]$ ll
total 4044
-rw-r--r--. 1 root root  212778 Nov 28 09:48 message.gz
-rw-------. 1 root root 1678853 Nov 28 09:42 messages-20171113
-rw-------. 1 root root 1678853 Nov 28 09:45 messages-20171113.bak
-rw-r--r--. 1 root root   76476 Nov 28 09:50 messages.xz
-rw-r--r--. 1 root root  411094 Nov 28 09:47 messages.Z
[root@centos7 test]$ ll -S
total 3968
-rw-------. 1 root root 1678853 Nov 28 09:42 messages-20171113
-rw-------. 1 root root 1678853 Nov 28 09:45 messages-20171113.bak
-rw-r--r--. 1 root root  411094 Nov 28 09:47 messages.Z
-rw-r--r--. 1 root root  212778 Nov 28 09:48 message.gz
-rw-r--r--. 1 root root   76476 Nov 28 09:50 messages.xz

[root@centos7 test]$ echo -e  "xz:$[1678853/76476]\ngz:$[1678853/212778]\nZ:$[1678853/411094]"
xz:21
gz:7
Z:4

Important

从上面的对比可以看出来, xz的压缩效果最好,其次gzip,最差的compress压缩。

2 、zip,unzip对/etc/sysconfig打包和压缩

[root@centos7 test]$ zip -r sysconfig.zip /etc/sysconfig
[root@centos7 test]$ unzip sysconfig.zip

3 、使用tar命令创建归档,并添加文件,查看文件列表,展开归档

[root@centos7 test]$ tar Jcvf sysconfig.tar.xz  /etc/sysconfig/
[root@centos7 test]$ ll
total 900
-rw-r--r--. 1 root root 919508 Nov 28 10:13 sysconfig.tar.xz
[root@centos7 test]$ tar tvf sysconfig.tar.xz
root@centos7 test]$ tar -rf sysconfig.tar.xz /root/access_log
tar: Cannot update compressed archives
tar: Error is not recoverable: exiting now
[root@centos7 test]$ tar xf sysconfig.tar.xz  -C /usr/src
[root@centos7 test]$ ll /usr/src
total 12
drwxr-xr-x. 2 root root 4096 Nov  5  2016 debug
drwxr-xr-x. 3 root root 4096 Nov 28 10:19 etc
drwxr-xr-x. 3 root root 4096 Nov 23 10:06 kernels

4 、split分割一个tar文件,并合并这些文件

[root@centos7 test]$ split -d -b 50k sysconfig.tar.xz  myconfig
[root@centos7 test]$ ll myconfig*
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig00
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig01
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig02
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig03
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig04
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig05
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig06
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig07
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig08
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig09
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig10
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig11
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig12
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig13
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig14
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig15
-rw-r--r--. 1 root root 51200 Nov 28 10:21 myconfig16
-rw-r--r--. 1 root root 49108 Nov 28 10:21 myconfig17
[root@centos7 test]$ cat myconfig* >> myconfig.tar.xz

5 、cpio 进行打包并还原

[root@centos7 test]$ find /etc/sysconfig -print  |cpio -ovc >sysconfig.cpio
[root@centos7 test]$ find /etc/scpio -tv < sysconfig.cpio
[root@centos7 test]$ cpio -idv < sysconfig.cpio

6 、测试压缩并解压对文件权限的影响

[root@centos7 test]$ touch general.txt
[root@centos7 test]$ touch acl.txt
[root@centos7 test]$ setfacl -m "u:zhaojiedi:rwx" acl.txt
[root@centos7 test]$ ll
total 4
-rw-rwxr--+ 1 root root 0 Nov 28 10:33 acl.txt
-rw-r--r--. 1 root root 0 Nov 28 10:33 general.txt
[root@centos7 test]$ mkdir bakdir
[root@centos7 test]$ xz -c acl.txt  > bakdir/acl.txt.xz
[root@centos7 test]$ gzip -c general.txt  > bakdir/general.txt.gz
[root@centos7 test]$ cd bakdir
[root@centos7 bakdir]$ ll
total 8
-rw-r--r--. 1 root root 32 Nov 28 10:35 acl.txt.xz
-rw-r--r--. 1 root root 32 Nov 28 10:38 general.txt.gz
[root@centos7 bakdir]$ xz -d acl.txt.xz
[root@centos7 bakdir]$ gzip -d general.txt.gz
[root@centos7 bakdir]$ ll . ; ll ../
total 0
-rw-r--r--. 1 root root 0 Nov 28 10:35 acl.txt
-rw-r--r--. 1 root root 0 Nov 28 10:38 general.txt
total 8
-rw-rwxr--+ 1 root root    0 Nov 28 10:33 acl.txt
drwxr-xr-x. 2 root root 4096 Nov 28 10:38 bakdir
-rw-r--r--. 1 root root    0 Nov 28 10:33 general.txt

Warning

经过测试我们发现,普通的权限还是能保留的,acl权限会在压缩和解压过程中丢失的。

7 、测试tar打包保留权限的问题

[root@centos7 test]$ ll
total 4
-rw-rwxr--+ 1 root root 0 Nov 28 10:33 acl.txt
-rw-r--r--. 1 root root 0 Nov 28 10:33 general.txt
[root@centos7 test]$ tar Jcvf /root/test.tar.xz /app/test
tar: Removing leading '/' from member names
/app/test/
/app/test/general.txt
/app/test/acl.txt
[root@centos7 test]$ tar --acl -Jcvf /root/test.tar.xz /app/test
tar: Removing leading '/' from member names
/app/test/
/app/test/general.txt
/app/test/acl.txt
[root@centos7 test]$ cd /root
[root@centos7 ~]$ tar xvf test.tar.xz
app/test/
app/test/general.txt
app/test/acl.txt
[root@centos7 ~]$ ll /app/test
total 4
-rw-rwxr--+ 1 root root 0 Nov 28 10:33 acl.txt
-rw-r--r--. 1 root root 0 Nov 28 10:33 general.txt

Important

经过测试我们发现使用tar –acl 选项打包的时候可以保留acl权限。其实还有xattrs,selinux保留选项的

14-2017-11-28-练习-sed

练习1

1、删除centos7系统/etc/grub2.cfg文件中所有以空白开头的行行首的空白字符

[root@centos7 ~]$ sed -nr 's@^([[:space:]]+)(.*)@\2@p' /etc/grub2.cfg

2、删除/etc/fstab文件中所有以#开头,后面至少跟一个空白字符的行的行首的#和空白字符

[root@centos7 ~]$ sed -nr 's@(^#[[:space:]])(.*)@\2@p' /etc/fstab

3、在centos6系统/root/install.log每一行行首增加#号

[root@centos6 ~]# sed -nr 's@.*@#\0@p' /root/install.log

4、在/etc/fstab文件中不以#开头的行的行首增加#号

[root@centos6 ~]# sed -nr 's@^[^#].*@#\0@p' /etc/fstab

5、处理/etc/fstab路径,使用sed命令取出其目录名和基名

[root@centos6 ~]# echo "/etc/fstab"   |sed -nr 's@(.*/)([^/]+)/?@\2@p'
fstab
[root@centos6 ~]# echo "/etc/fstab/"   |sed -nr 's@(.*/)([^/]+)/?@\2@p'
fstab
[root@centos6 ~]# echo "/etc/"   |sed -nr 's@(.*/)([^/]+)/?@\1@p'
/

6、利用sed 取出ifconfig命令中本机的IPv4地址

[root@centos7 ~]$ ifconfig ens33 |sed -nr '2s@.*inet (.*) netmask.*@\1@p'

7、统计centos安装光盘中Package目录下的所有rpm文件的以.分隔倒数第二个字段的重复次数

root@centos7 ~]$ ls /misc/cd/Packages/ |sed -nr 's@.*\.([^.]*)\.rpm@\1@p' |sort  |uniq -c
2141 i686
3076 noarch
4374 x86_64

8、统计/etc/init.d/functions文件中每个单词的出现次数,并排序(用grep和sed两种方法分别实现)

cat  /etc/init.d/functions  | egrep -o "([[:alpha:]]+)"  |sort |uniq -c  > /root/grep.txt
cat /etc/init.d/functions | sed -r 's@[^[:alpha:]]@\n@g' |sed '/^$/d' |sort |uniq -c  >/root/sed.txt
diff /root/sed.txt /root/grep.txt

Warning

这个题,2种结果必须是一致的, 如果第二种方式没有sed -nr ‘s@.*@#0@p’ 就会少统计行单独为fi的行。

9、将文本文件的n和n+1行合并为一行,n为奇数行

[root@centos7 ~]$ sed 'N;s@\n@@' /etc/fstab

15-2017-11-28-练习-rpm

练习1

1 、 删除一个动态链接库, 并使用救援模式修复它

光盘挂载启动,进入救援模式
copy so /sys/sysimage目录下对应目录即可

2 、 内核被卸载 ,并安装后丢失了启动菜单修复他

模拟一个破坏环境

[root@centos6 ~]# rpm -qa |grep kernel
kernel-2.6.32-696.13.2.el6.x86_64
dracut-kernel-004-409.el6_8.2.noarch
kernel-2.6.32-696.el6.x86_64
abrt-addon-kerneloops-2.0.8-43.el6.centos.x86_64
kernel-firmware-2.6.32-696.13.2.el6.noarch
libreport-plugin-kerneloops-2.0.9-33.el6.centos.x86_64
kernel-headers-2.6.32-696.13.2.el6.x86_64
[root@centos6 ~]# rpm -e kernel-2.6.32-696.el6.x86_64
warning:    erase unlink of /lib/modules/2.6.32-696.el6.x86_64/modules.order failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.el6.x86_64/modules.networking failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.el6.x86_64/modules.modesetting failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.el6.x86_64/modules.drm failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.el6.x86_64/modules.block failed: No such file or directory
[root@centos6 ~]# ll /boot
total 32204
-rw-r--r--. 1 root root   108169 Oct  6 05:27 config-2.6.32-696.13.2.el6.x86_64
drwxr-xr-x. 3 root root     4096 Nov  7 15:38 efi
drwxr-xr-x. 2 root root     4096 Nov 26 04:03 grub
-rw-------. 1 root root 25719414 Nov  9 21:49 initramfs-2.6.32-696.13.2.el6.x86_64.img
drwx------. 2 root root    16384 Nov  7 15:26 lost+found
-rw-r--r--. 1 root root   215634 Oct  6 05:28 symvers-2.6.32-696.13.2.el6.x86_64.gz
-rw-r--r--. 1 root root  2622609 Oct  6 05:27 System.map-2.6.32-696.13.2.el6.x86_64
-rwxr-xr-x. 1 root root  4276016 Oct  6 05:27 vmlinuz-2.6.32-696.13.2.el6.x86_64
[root@centos6 ~]# rpm -e kernel-2.6.32-696.13.2.el6.x86_64
error: Failed dependencies:
    kernel >= 2.6.30 is needed by (installed) pulseaudio-0.9.21-26.el6.x86_64
    kernel >= 2.6.17 is needed by (installed) autofs-1:5.0.5-132.el6.x86_64
    kernel >= 2.6.14 is needed by (installed) fuse-2.8.3-5.el6.x86_64
    kernel >= 2.6.32-33.el6 is needed by (installed) xorg-x11-drv-intel-2.99.917-0.4.20151111.el6.x86_64
    kernel >= 2.6.32-358.2.1 is needed by (installed) irqbalance-2:1.0.7-8.el6.x86_64
    kernel >= 2.6.12-1.1411_FC5 is needed by (installed) pcmciautils-015-4.2.el6.x86_64
    kernel >= 2.6.32-33.el6 is needed by (installed) xorg-x11-drv-ati-7.6.1-3.el6_9.x86_64
    kernel-drm-nouveau = 16 is needed by (installed) xorg-x11-drv-nouveau-1:1.0.12-1.el6.x86_64
[root@centos6 ~]# rpm -e kernel-2.6.32-696.13.2.el6.x86_64 --force
rpm: only installation, upgrading, rmsource and rmspec may be forced
[root@centos6 ~]# rpm -e kernel-2.6.32-696.13.2.el6.x86_64 --nodeps
grubby fatal error: unable to find a suitable template
grubby: doing this would leave no kernel entries. Not writing out new config.
warning:    erase unlink of /lib/modules/2.6.32-696.13.2.el6.x86_64/modules.order failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.13.2.el6.x86_64/modules.networking failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.13.2.el6.x86_64/modules.modesetting failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.13.2.el6.x86_64/modules.drm failed: No such file or directory
warning:    erase unlink of /lib/modules/2.6.32-696.13.2.el6.x86_64/modules.block failed: No such file or directory
[root@centos6 ~]# ll /boot
total 24
drwxr-xr-x. 3 root root  4096 Nov  7 15:38 efi
drwxr-xr-x. 2 root root  4096 Nov 26 04:03 grub
drwx------. 2 root root 16384 Nov  7 15:26 lost+found

修复问题

[root@centos6 ~]# rpm -ivh /misc/cd/Packages/kernel-2.6.32-696.el6.x86_64.rpm
Preparing...                ########################################### [100%]
1:kernel                 ########################################### [100%]
grubby fatal error: unable to find a suitable template

[root@centos6 ~]# ll /bot
ls: cannot access /bot: No such file or directory
[root@centos6 ~]# ll/boot
-bash: ll/boot: No such file or directory
[root@centos6 ~]# ll /boot
total 32204
-rw-r--r--. 1 root root   108164 Mar 22  2017 config-2.6.32-696.el6.x86_64
drwxr-xr-x. 3 root root     4096 Nov  7 15:38 efi
drwxr-xr-x. 2 root root     4096 Nov 26 04:11 grub
-rw-------. 1 root root 25719125 Nov 26 04:11 initramfs-2.6.32-696.el6.x86_64.img
drwx------. 2 root root    16384 Nov  7 15:26 lost+found
-rw-r--r--. 1 root root   215634 Mar 22  2017 symvers-2.6.32-696.el6.x86_64.gz
-rw-r--r--. 1 root root  2622364 Mar 22  2017 System.map-2.6.32-696.el6.x86_64
-rwxr-xr-x. 1 root root  4274992 Mar 22  2017 vmlinuz-2.6.32-696.el6.x86_64

#重启进入grub页面
root (hd0,0)
kernel /vmlinuz-2.6.32-696.el6.x86_64
initrd /initrd-2.6.32-696.el6.x86_64
#b键重启

练习2

1 、 查询/usr/bin/java来自于哪个rpm

[root@centos7 Bash]$ ll /usr/bin/java                  #readlink -e /usr/bin/java
lrwxrwxrwx. 1 root root 22 Nov  7 16:10 /usr/bin/java -> /etc/alternatives/java
[root@centos7 Bash]$ ll /etc/alternatives/java
lrwxrwxrwx. 1 root root 72 Nov  7 16:10 /etc/alternatives/java -> /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-11.b12.el7.x86_64/jre/bin/java
[root@centos7 Bash]$ rpm -qf /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-11.b12.el7.x86_64/jre/bin/java
java-1.8.0-openjdk-headless-1.8.0.131-11.b12.el7.x86_64

2 、rpm -e rpm –nodeps 删除rpm包,恢复之

#另一个机器copy到故障机器
[root@centos7 ~]# scp /usr/bin/rpm  root@172.18.1.250:/bin/
[root@centos7 ~]# scp /usr/lib/rpm/rpmrc 172.18.1.250:/usr/lib/rpm/rpmrc
[root@centos7 rpm]# scp /usr/lib/rpm/macros 172.18.1.250://usr/lib/rpm/macros
#故障机器执行updatedb
[root@centos7 rpm]$ updatedb
[root@centos7 rpm]$ yum install yum*

3、编写系统初始化脚本reset.sh,包括别名,提示符颜色,yum仓库配置文件,安装tree,ftp,lftp,telnet等包

[root@centos7 Bash]$ cat alias.sh
#!/bin/bash
#================================================
#FileName   :alias_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 08:51:22
#Version    :V1.0
#Other      :
#================================================
# interactive operation
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'

# grep
alias grep='grep --color'
alias egrep='egrep --color'

# list
alias ll= 'ls -l'
alias la='ls -a'
alias lA='ls -A'
alias l1='ls -1'

# cd dir

alias cdnet='cd /etc/sysconfig/network-scripts'
alias cdyum='cd /etc/yum.repos.d'

# git
alias ga='git add'
alias gaa='git add --all'
alias gs='git status'
alias gc='git commit'
alias gct='git commit -m "- comment"'
alias gcm='git commit -m'
alias gca='git commit --amend'
alias gco='git checkout'
alias gd='git diff'
alias gdh='git diff HEAD'
alias gf='git fetch'
alias gfa='git fetch -a'
alias gp='git pull'
alias gb='git branch'
alias gg='git grep'
alias gmv='git mv'

[root@centos7 Bash]$ cat rpm.sh
mkdir -pv /etc/yum.repos.d/bak
mv /etc/yum.repos.d/*.* /etc/yum.repos.d/bak
echo "
[base]
name=base
baseurl=file:///misc/cd
gpgcheck=0
cost=20
enable=1
" >> /etc/yum.repos.d/base.repo

yum clean all
yum makecache


# start install
yum install -y  tree ftp lftp telnet

[root@centos7 Bash]$ cat init.sh
#!/bin/bash
#================================================
#FileName   :init_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-24 08:50:50
#Version    :V1.0
#Other      :
#================================================
# configurate rpm and install some rpm
. rpm.sh

# alias set
sed -i '/^alias/d'  ~/.bashrc
sed -i '/^# Source global/i . alias.sh' ~/.bashrc

# set PS1
. ps.sh

[root@centos7 Bash]$ cat ps.sh
#!/bin/bash
#================================================
#FileName   :ps.sh_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-30 19:40:35
#Version    :V1.0
#Other      :
#================================================

! grep PS1 ~/.bash_profile &&  echo PS1=\"'\033[1;33m[\u@\h \W]$ \033[0m'\" >> ~/.bash_profile

4、在CentOS6上编译安装apache 2.2源码包,并启动此服务

[root@centos7 Bash]$ cat install_httpd_46_zhaojiedi.sh
#!/bin/bash
#================================================
#FileName   :install_httpd_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-11-30 14:23:41
#Version    :V1.0
#Other      :
#================================================

# var set
#file_url=http://mirror.bit.edu.cn/apache//httpd/httpd-2.4.29.tar.bz2
file_url=ftp://172.18.1.159/pub/httpd-2.2.34.tar.bz2
#file_url=ftp://172.18.1.159/pub/httpd-2.4.29.tar.bz2
#file_url=/root/httpd-2.4.29.tar.bz2
download_dir=/root/apache/httpd
download_log=$download_dir/download.log
filename=$(basename $file_url)
filename_without_ext=$(echo $filename |sed -r 's@.tar.bz2$@@')
echo $filename
download_file=$download_dir/$filename
download_retry=3
install_dir=/usr/local/httpd
# create compire dir
rm -rf $download_dir
mkdir -pv $download_dir
# start download
[[ "$file_url" =~ ^/ ]]  && cp $file_url $download_file || wget --no-check-certificate -o $download_log  -O $download_file -t $download_retry -Nc $file_url
[ $? -ne 0 ] && exit 1
# extract tar file
[ ! -f $download_file ] && exit 2
[ -d $download_dir/$filename_without_ext ] && rm -rf $download_dir/$filename_without_ext
tar xf $download_file -C $download_dir
# get version
version=$(cat /etc/system-release  |sed -nr 's@.*release ([0-9]+)\.[0-9]+.*@\1@p')
# install Development Tools and apr
yum groupinstall "Development Tools" -y
yum install apr-devel apr-util-devel pcre-devel openssl-devel -y
yum install elinks -y

# cd workspace and start make
[ -d $install_dir ] && rm -rf $install_dir
cd $download_dir/$filename_without_ext
./configure --prefix=$install_dir  --enable-ssl
[ $? -ne 0 ] && echo ".configure error " && exit 6

make -j 2  && make install

# test make
[ $? -ne 0 ] && echo "echo make && make install error " && exit 7

# add bin
httpd_bin=$install_dir/bin
echo "PATH=$httpd_bin:\$PATH" > /etc/profile.d/httpd.sh
. /etc/profile.d/httpd.sh
# add man
httpd_man=$install_dir/man
man_conf=""
[ $version -ge 7 ] && man_conf="/etc/man_db.conf"
[ $version -eq 6 ] && man_conf="/etc/man.config"
grep $httpd_man  $man_conf
declare -i ret=$?
[ $ret -ne 0 ] && [ $version -ge 7 ] && sed -i "/#MANDATORY_MANPATH/aMANDATORY_MANPATH                     $httpd_man" $man_conf
[ $ret -ne 0 ] && [ $version -eq 6 ] && sed -i "/# Every automatically/aMANPATH    $httpd_man" $man_conf
# start httpd
chown -R apache:apache /var/run/httpd
apachectl stop &> /dev/null
killall httpd
[ $version -ge 7 ] && ip=$(ifconfig ens33 |sed -nr '2s@.*inet (.*) netmask.*@\1@p')
[ $version -eq 6 ] && ip=$(ifconfig eth0 |sed -nr '2s@.*inet addr:(.*) Bcast.*@\1@p')

apachectl start && elinks $ip --source |grep "works" && echo " finish it ok " ||echo "not ok"

# start httpd on boot
[ $version -ge 7 ] && systemctl enable httpd
[ $version -eq 6 ] && chkconfig httpd on

16-2017-12-01-练习-磁盘管理

练习1

1、 mbr损坏的修复

2、文件系统出现故障的修复

模拟破坏环境

[root@centos7 mnt]$ mkfs.ext4 /dev/sdb1
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
1310720 inodes, 5242880 blocks
262144 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=2153775104
160 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000

Allocating group tables: done
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

[root@centos7 mnt]$ mount /dev/sdb1 /mnt/1
[root@centos7 mnt]$ touch 1.txt >/mnt/1/
-bash: /mnt/1/: Is a directory
[root@centos7 mnt]$ touch "f1 " >> /mnt/1/f1.txt
[root@centos7 mnt]$ dd if=/dev/zero of=/dev/sdb1 bs=1M count=10
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.00539083 s, 1.9 GB/s

修复文件系统问题

[root@centos7 mnt]$ umount /dev/sdb1
[root@centos7 mnt]$ fsck /dev/sdb1
fsck from util-linux 2.23.2
e2fsck 1.42.9 (28-Dec-2013)
ext2fs_open2: Bad magic number in super-block
fsck.ext2: Superblock invalid, trying backup blocks...
Superblock has an invalid journal (inode 8).
Clear<y>? yes
*** ext3 journal has been deleted - filesystem is now ext2 only ***

/dev/sdb1 was not cleanly unmounted, check forced.
Resize inode not valid.  Recreate<y>? yes
Pass 1: Checking inodes, blocks, and sizes
Root inode is not a directory.  Clear<y>? yes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Root inode not allocated.  Allocate<y>? yes
/lost+found not found.  Create<y>? yes
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Block bitmap differences:  +(0--9252) +(32768--33795) +(98304--99331) +(163840--164867) +(229376--230403) +(294912--295939) -(2655236--2688003)
Fix<y>? yes
Free blocks count wrong for group #0 (23508, counted=23513).
Fix<y>? yes
Free blocks count wrong for group #81 (0, counted=31740).
Fix<y>? yes
Free blocks count wrong for group #82 (31740, counted=32768).
Fix<y>? yes
Free blocks count wrong (5116556, counted=5149329).
Fix<y>? yes
Inode bitmap differences:  +1 +(3--10)
Fix<y>? yes
Free inodes count wrong for group #0 (8180, counted=8181).
Fix<y>? yes
Directories count wrong for group #0 (3, counted=2).
Fix<y>? yes
Free inodes count wrong (1310708, counted=1310709).
Fix<y>? yes
Recreate journal<y>? yes
Creating journal (32768 blocks):

Done.

*** journal has been re-created - filesystem is now ext3 again ***

/dev/sdb1: ***** FILE SYSTEM WAS MODIFIED *****
/dev/sdb1: 11/1310720 files (0.0% non-contiguous), 126319/5242880 blocks

练习2

1、创建一个2G的文件系统,块大小为2048byte,预留1%可用空间,文件系统ext4,卷标为TEST,要求此分区开机后自动挂载至/test目录,且默认有acl挂载选项

[root@centos7 app]$ fdisk /dev/sdb
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
Disk identifier: CF8E8E9A-2E50-4DD8-AC6F-A621DDD9B8ED


#         Start          End    Size  Type            Name
1      1953792     58593279     27G  Linux LVM       primary

Command (m for help): n
Partition number (2-128, default 2):
First sector (34-209715166, default 58593280):
Last sector, +sectors or +size{K,M,G,T,P} (58593280-209715166, default 209715166): +2G
Created partition 2


Command (m for help): p

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
Disk identifier: CF8E8E9A-2E50-4DD8-AC6F-A621DDD9B8ED


#         Start          End    Size  Type            Name
1      1953792     58593279     27G  Linux LVM       primary
2     58593280     62787583      2G  Linux filesyste

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[root@centos7 app]$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0  200G  0 disk
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0  128G  0 part [SWAP]
├─sda3   8:3    0 48.8G  0 part /
├─sda4   8:4    0    1K  0 part
└─sda5   8:5    0 19.5G  0 part /app
sdb      8:16   0  100G  0 disk
├─sdb1   8:17   0   27G  0 part
└─sdb2   8:18   0    2G  0 part
sr0     11:0    1  8.1G  0 rom  /run/media/root/CentOS 7 x86_64

[root@centos7 app]$ mkfs -t ext4 -b 2048 -m 1 -L "TEST"  /dev/sdb2
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=TEST
OS type: Linux
Block size=2048 (log=1)
Fragment size=2048 (log=1)
Stride=0 blocks, Stripe width=0 blocks
131072 inodes, 1048576 blocks
10485 blocks (1.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=269484032
64 block groups
16384 blocks per group, 16384 fragments per group
2048 inodes per group
Superblock backups stored on blocks:
    16384, 49152, 81920, 114688, 147456, 409600, 442368, 802816

Allocating group tables: done
Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

[root@centos7 app]$ tune2fs -l /dev/sdb2
tune2fs 1.42.9 (28-Dec-2013)
Filesystem volume name:   TEST
Last mounted on:          <not available>
Filesystem UUID:          ac0dfb11-573e-4036-8fe9-256e04f0110c
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype extent 64bit flex_bg sparse_super huge_file uninit_bg dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              131072
Block count:              1048576
Reserved block count:     10485
Free blocks:              994651
Free inodes:              131061
First block:              0
Block size:               2048
Fragment size:            2048
Group descriptor size:    64
Reserved GDT blocks:      512
Blocks per group:         16384
Fragments per group:      16384
Inodes per group:         2048
Inode blocks per group:   256
Flex block group size:    16
Filesystem created:       Mon Dec  4 19:27:56 2017
Last mount time:          n/a
Last write time:          Mon Dec  4 19:28:00 2017
Mount count:              0
Maximum mount count:      -1
Last checked:             Mon Dec  4 19:27:56 2017
Check interval:           0 (<none>)
Lifetime writes:          65 MB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:           256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
Default directory hash:   half_md4
Directory Hash Seed:      2008b2d4-8232-4184-8ba8-9badec4f375f
Journal backup:           inode blocks
[root@centos7 app]$ mkdir /test
[root@centos7 app]$ mount /dev/sdb2 /test
[root@centos7 app]$ tail -n 1 /etc/mtab >> /etc/fstab
[root@centos7 app]$ cat /etc/fstab

#
# /etc/fstab
# Created by anaconda on Tue Nov  7 16:07:01 2017
#
# 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=59ccea87-3c4e-4bbc-9e2f-3fadb1dcf2e6 /                       ext4    defaults        1 1
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime,usrquota,grpquota        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0

/dev/sdb2 /test ext4 rw,seclabel,relatime,data=ordered 0 0
[root@centos7 app]$ cd /test
[root@centos7 test]$ touch a.txt
[root@centos7 test]$ setfacl -m "u:zhaojiedi:rwx" a.txt
[root@centos7 test]$ getfacl a.txt
# file: a.txt
# owner: root
# group: root
user::rw-
user:zhaojiedi:rwx
group::r--
mask::rwx
other::r--

2、写一个脚本,完成如下功能:

  1. 列出当前系统识别到的所有磁盘设备
  2. 如磁盘数量为1,则显示其空间使用信息

否则,则显示最后一个磁盘上的空间使用信息

lsblk  |grep '^s[dh][a-z]\+' -o
df  /dev/`lsblk  |grep '^s[dh][a-z]\+' -o | tail -n 1 `

3、将CentOS6的CentOS-6.8-x86_64-bin-DVD1.iso和CentOS-6.8-x86_64-bin-DVD2.iso两个文件,合并成一个CentOS-6.8-x86_64-Everything.iso文件,并将其配置为yum源

mount /dev/sr2 /mnt/cdrom1
mount /dev/sr3 /mnt/cdrom2

cp -a /mnt/cdrom2/*  /app/test/
\cp -a /mnt/cdrom1/* /app/tset/
cp /mnt/cdrom1/.discinfo /app/test
./mkdvdiso.sh  /app/test /root/centos.iso

练习3

1 、制作交换分区,并启用

[root@centos7 ~]$ fdisk /dev/sdb
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): n
Partition number (3-128, default 3):
First sector (34-209715166, default 62787584):
Last sector, +sectors or +size{K,M,G,T,P} (62787584-209715166, default 209715166): +1G
Created partition 3


Command (m for help): p

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
Disk identifier: CF8E8E9A-2E50-4DD8-AC6F-A621DDD9B8ED


#         Start          End    Size  Type            Name
1      1953792     58593279     27G  Linux LVM       primary
2     58593280     62787583      2G  Linux filesyste
3     62787584     64884735      1G  Linux filesyste

Command (m for help): t
Partition number (1-3, default 3):
Partition type (type L to list all types): L
1 EFI System                     C12A7328-F81F-11D2-BA4B-00A0C93EC93B
2 MBR partition scheme           024DEE41-33E7-11D3-9D69-0008C781F39F
3 BIOS boot partition            21686148-6449-6E6F-744E-656564454649
4 Microsoft reserved             E3C9E316-0B5C-4DB8-817D-F92DF00215AE
5 Microsoft basic data           EBD0A0A2-B9E5-4433-87C0-68B6B72699C7
6 Microsoft LDM metadata         5808C8AA-7E8F-42E0-85D2-E1E90434CFB3
7 Microsoft LDM data             AF9B60A0-1431-4F62-BC68-3311714A69AD
8 Windows recovery evironmnet    DE94BBA4-06D1-4D40-A16A-BFD50179D6AC
9 IBM General Parallel Fs        37AFFC90-EF7D-4E96-91C3-2D7AE055B174
10 HP-UX data partition           75894C1E-3AEB-11D3-B7C1-7B03A0000000
11 HP-UX service partition        E2A1E728-32E3-11D6-A682-7B03A0000000
12 Linux filesystem               0FC63DAF-8483-4772-8E79-3D69D8477DE4
13 Linux RAID                     A19D880F-05FC-4D3B-A006-743F0F84911E
14 Linux swap                     0657FD6D-A4AB-43C4-84E5-0933C84B4F4F
15 Linux LVM                      E6D6D379-F507-44C2-A23C-238F2A3DF928
16 Linux reserved                 8DA63339-0007-60C0-C436-083AC8230908
17 FreeBSD data                   516E7CB4-6ECF-11D6-8FF8-00022D09712B
18 FreeBSD boot                   83BD6B9D-7F41-11DC-BE0B-001560B84F0F
19 FreeBSD swap                   516E7CB5-6ECF-11D6-8FF8-00022D09712B
20 FreeBSD UFS                    516E7CB6-6ECF-11D6-8FF8-00022D09712B
21 FreeBSD ZFS                    516E7CBA-6ECF-11D6-8FF8-00022D09712B
22 FreeBSD Vinum                  516E7CB8-6ECF-11D6-8FF8-00022D09712B
23 Apple HFS/HFS+                 48465300-0000-11AA-AA11-00306543ECAC
24 Apple UFS                      55465300-0000-11AA-AA11-00306543ECAC
25 Apple RAID                     52414944-0000-11AA-AA11-00306543ECAC
26 Apple RAID offline             52414944-5F4F-11AA-AA11-00306543ECAC
27 Apple boot                     426F6F74-0000-11AA-AA11-00306543ECAC
28 Apple label                    4C616265-6C00-11AA-AA11-00306543ECAC
29 Apple TV recovery              5265636F-7665-11AA-AA11-00306543ECAC
30 Apple Core storage             53746F72-6167-11AA-AA11-00306543ECAC
31 Solaris boot                   6A82CB45-1DD2-11B2-99A6-080020736631
32 Solaris root                   6A85CF4D-1DD2-11B2-99A6-080020736631
33 Solaris /usr & Apple ZFS       6A898CC3-1DD2-11B2-99A6-080020736631
34 Solaris swap                   6A87C46F-1DD2-11B2-99A6-080020736631
35 Solaris backup                 6A8B642B-1DD2-11B2-99A6-080020736631
36 Solaris /var                   6A8EF2E9-1DD2-11B2-99A6-080020736631
37 Solaris /home                  6A90BA39-1DD2-11B2-99A6-080020736631
38 Solaris alternate sector       6A9283A5-1DD2-11B2-99A6-080020736631
39 Solaris reserved 1             6A945A3B-1DD2-11B2-99A6-080020736631
40 Solaris reserved 2             6A9630D1-1DD2-11B2-99A6-080020736631
41 Solaris reserved 3             6A980767-1DD2-11B2-99A6-080020736631
42 Solaris reserved 4             6A96237F-1DD2-11B2-99A6-080020736631
43 Solaris reserved 5             6A8D2AC7-1DD2-11B2-99A6-080020736631
44 NetBSD swap                    49F48D32-B10E-11DC-B99B-0019D1879648
45 NetBSD FFS                     49F48D5A-B10E-11DC-B99B-0019D1879648
46 NetBSD LFS                     49F48D82-B10E-11DC-B99B-0019D1879648
47 NetBSD concatenated            2DB519C4-B10E-11DC-B99B-0019D1879648
48 NetBSD encrypted               2DB519EC-B10E-11DC-B99B-0019D1879648
49 NetBSD RAID                    49F48DAA-B10E-11DC-B99B-0019D1879648
50 ChromeOS kernel                FE3A2A5D-4F32-41A7-B725-ACCC3285A309
51 ChromeOS root fs               3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC
52 ChromeOS reserved              2E0A753D-9E48-43B0-8337-B15192CB1B5E
53 MidnightBSD data               85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7
54 MidnightBSD boot               85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7
55 MidnightBSD swap               85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7
56 MidnightBSD UFS                0394Ef8B-237C-11E1-B4B3-E89A8F7FC3A7
57 MidnightBSD ZFS                85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7
58 MidnightBSD Vinum              85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7

Partition type (type L to list all types): 14
Changed type of partition 'Linux filesystem' to 'Linux swap'

Command (m for help): p

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
Disk identifier: CF8E8E9A-2E50-4DD8-AC6F-A621DDD9B8ED


#         Start          End    Size  Type            Name
1      1953792     58593279     27G  Linux LVM       primary
2     58593280     62787583      2G  Linux filesyste
3     62787584     64884735      1G  Linux swap

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.
[root@centos7 ~]$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0  200G  0 disk
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0  128G  0 part [SWAP]
├─sda3   8:3    0 48.8G  0 part /
├─sda4   8:4    0  512B  0 part
└─sda5   8:5    0 19.5G  0 part /app
sdb      8:16   0  100G  0 disk
├─sdb1   8:17   0   27G  0 part
└─sdb2   8:18   0    2G  0 part /test
sr0     11:0    1  8.1G  0 rom  /run/media/root/CentOS 7 x86_64
loop0    7:0    0    1G  0 loop /mnt/c1
[root@centos7 ~]$ partx -a /dev/sdb
partx: /dev/sdb: error adding partitions 1-2
[root@centos7 ~]$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0  200G  0 disk
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0  128G  0 part [SWAP]
├─sda3   8:3    0 48.8G  0 part /
├─sda4   8:4    0  512B  0 part
└─sda5   8:5    0 19.5G  0 part /app
sdb      8:16   0  100G  0 disk
├─sdb1   8:17   0   27G  0 part
├─sdb2   8:18   0    2G  0 part /test
└─sdb3   8:19   0    1G  0 part
sr0     11:0    1  8.1G  0 rom  /run/media/root/CentOS 7 x86_64
loop0    7:0    0    1G  0 loop /mnt/c1

[root@centos7 ~]$ mkswap /dev/sdb3
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=a0516c4f-40e6-4919-905a-8b44db12ff7b
[root@centos7 ~]$ free
            total        used        free      shared  buff/cache   available
Mem:        2031912      845264      377640        9488      809008      955040
Swap:     134217724         296   134217428
[root@centos7 ~]$ swapon /dev/sdb3
[root@centos7 ~]$ free
            total        used        free      shared  buff/cache   available
Mem:        2031912      846432      376416        9488      809064      953872
Swap:     135266296         296   135266000

17-2017-12-03-练习-高级磁盘管理

练习1-LVM

1、创建一个至少有两个PV组成的大小为20G的名为testvg的VG;要求PE大小为16MB, 而后在卷组中创建大小为5G的逻辑卷testlv;挂载至/users目录
2、 新建用户archlinux,要求其家目录为/users/archlinux,而后su切换至archlinux用户,复制/etc/pam.d目录至自己的家目录
3、扩展testlv至7G,要求archlinux用户的文件不能丢失
4、收缩testlv至3G,要求archlinux用户的文件不能丢失
5、对testlv创建快照,并尝试基于快照备份数据,验证快照的功能

具体参考地址如下 : LVM的使用.

练习2-raid

具体参考地址如下 : raid的使用.

练习3-quota

具体参考地址如下 : quota的使用.

18-2017-12-13-练习-网络

练习1-子网划分

1、10.0.0.0/8划分32个子网,计算最大子网的的网络id,最大子网的可用ip范围

1.分析32个子网,需要5位借位
    10.00000 000.0.0
2.最大的子网为
    10.1111000.0.0/13即10.240.0.0/13
3.ip范围为
    10.240.0.1-10.255.255.254

练习2-网卡重命名

1、 重名了centos6的网络名字为ens33

[root@centos6 ~]$ ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:0C:29:42:6E:19
        inet addr:172.18.1.159  Bcast:172.18.255.255  Mask:255.255.0.0
        inet6 addr: fe80::20c:29ff:fe42:6e19/64 Scope:Link
        UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
        RX packets:589 errors:0 dropped:0 overruns:0 frame:0
        TX packets:87 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:44342 (43.3 KiB)  TX bytes:11667 (11.3 KiB)

[root@centos6 ~]$ vim /etc/udev/rules.d/70-persistent-net.rules
[root@centos6 ~]$ cdnet
[root@centos6 network-scripts]$ ll
total 224
-rw-r--r--. 1 root root   319 Nov  9 16:17 ifcfg-eth0
-rw-r--r--. 1 root root   254 Jan 18  2017 ifcfg-lo
lrwxrwxrwx. 1 root root    20 Nov  9 21:47 ifdown -> ../../../sbin/ifdown
-rwxr-xr-x. 1 root root   627 Jan 18  2017 ifdown-bnep
-rwxr-xr-x. 1 root root  5891 Jan 18  2017 ifdown-eth
-rwxr-xr-x. 1 root root  6195 Mar 23  2017 ifdown-ib
-rwxr-xr-x. 1 root root   781 Jan 18  2017 ifdown-ippp
-rwxr-xr-x. 1 root root  4168 Jan 18  2017 ifdown-ipv6
lrwxrwxrwx. 1 root root    11 Nov  9 21:47 ifdown-isdn -> ifdown-ippp
-rwxr-xr-x. 1 root root  1617 Jan 18  2017 ifdown-post
-rwxr-xr-x. 1 root root  1064 Jan 18  2017 ifdown-ppp
-rwxr-xr-x. 1 root root   835 Jan 18  2017 ifdown-routes
-rwxr-xr-x. 1 root root  1465 Jan 18  2017 ifdown-sit
-rwxr-xr-x. 1 root root  1434 Jan 18  2017 ifdown-tunnel
lrwxrwxrwx. 1 root root    18 Nov  9 21:47 ifup -> ../../../sbin/ifup
-rwxr-xr-x. 1 root root 13226 Oct  4 10:26 ifup-aliases
-rwxr-xr-x. 1 root root   859 Jan 18  2017 ifup-bnep
-rwxr-xr-x. 1 root root 12119 Oct  4 10:26 ifup-eth
-rwxr-xr-x. 1 root root 11339 Mar 23  2017 ifup-ib
-rwxr-xr-x. 1 root root 11971 Jan 18  2017 ifup-ippp
-rwxr-xr-x. 1 root root 10490 Jan 18  2017 ifup-ipv6
lrwxrwxrwx. 1 root root     9 Nov  9 21:47 ifup-isdn -> ifup-ippp
-rwxr-xr-x. 1 root root   727 Jan 18  2017 ifup-plip
-rwxr-xr-x. 1 root root   954 Jan 18  2017 ifup-plusb
-rwxr-xr-x. 1 root root  2527 Jan 18  2017 ifup-post
-rwxr-xr-x. 1 root root  4154 Jan 18  2017 ifup-ppp
-rwxr-xr-x. 1 root root  1925 Jan 18  2017 ifup-routes
-rwxr-xr-x. 1 root root  3289 Jan 18  2017 ifup-sit
-rwxr-xr-x. 1 root root  2563 Jan 18  2017 ifup-tunnel
-rwxr-xr-x. 1 root root  4011 Jan 18  2017 ifup-wireless
-rwxr-xr-x. 1 root root  4623 Jan 18  2017 init.ipv6-global
-rwxr-xr-x. 1 root root  1219 Jan 18  2017 net.hotplug
-rw-r--r--. 1 root root 15360 Oct  4 10:26 network-functions
-rw-r--r--. 1 root root 29857 Jan 18  2017 network-functions-ipv6
[root@centos6 network-scripts]$ mv ifcfg-eth0 ifcfg-ens33
[root@centos6 network-scripts]$ sed -i 's@eth0@ens33@g' ifcfg-ens33
[root@centos6 network-scripts]$ cat ifcfg-ens33
DEVICE=ens33
TYPE=Ethernet
UUID=78658f7b-18ae-4581-a5b1-50acd8983e99
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=dhcp
#BOOTPROTO=static

#IPADDR=192.168.27.129
#NETMASK=255.255.255.0
#GATEWAY=192.168.27.1

HWADDR=00:0C:29:42:6E:19
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System ens33"
[root@centos6 network-scripts]$ (modprobe -r e1000; modprobe e1000)
[root@centos6 network-scripts]$ ifconfig ens33
ens33     Link encap:Ethernet  HWaddr 00:0C:29:42:6E:19
        inet addr:172.18.1.159  Bcast:172.18.255.255  Mask:255.255.0.0
        inet6 addr: fe80::20c:29ff:fe42:6e19/64 Scope:Link
        UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
        RX packets:464 errors:0 dropped:0 overruns:0 frame:0
        TX packets:46 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:33301 (32.5 KiB)  TX bytes:6186 (6.0 KiB)

练习3-路由配置

1、3个路由器,2个主机,确保各个ip之间都是互通的。

1.绘图分析网络
2.5个机器,每个机器根据情况设置网卡个数,并设置网络区域,其中3个充当路由器
3.禁用所有防火墙和selinux。并启用路由器的转发功能
4.设置ip
5.根据网络设置路由
6.测试

19-2017-12-15-练习-进程管理和作业管理

练习1-进程管理常用命令

具体参考:linux进程管理和系统状态常用命令简介_

练习2-作业管理练习

1、简述作业状态,并说明各个状态的切换

https://github.com/zhaojiedi1992/My_Study_Linux/blob/master/rstdoc/images/%E4%BD%9C%E4%B8%9A%E7%8A%B6%E6%80%81.png?raw=true

练习3-计划任务at

1、 创建一个计划任务,10.20执行一次wall命令,查看计划任务并删除

[root@centos74 at]$ at 10:20
at> wall "wall message"
at> <EOT>
job 3 at Tue Dec 19 10:20:00 2017
[root@centos74 at]$ atq
3   Tue Dec 19 10:20:00 2017 a root
[root@centos74 at]$ at -c 3
[root@centos74 at]$ atrm 3

练习4-计划任务cron

1、每天的2点和12点整,将/etc备份至/testdir/backup目录中,保存的文件名称格式为“etcbak-yyyy-mm-dd-HH.tar.xz”

[root@centos74 test]$ crontab  -l
1 2,12 * * * /app/test/backup.sh
[root@centos74 test]$ cat /backup.sh
cat: /backup.sh: No such file or directory
[root@centos74 test]$ cat /app/test/backup.sh
#!/bin/bash
if [ ! -e /testdir/backup ] ; then
    mkdir -pv /testdir/backup
fi
/usr/bin/tar  --acl --xattrs -Jcvf  /testdir/backup/etcbak-`date +%Y-%m-%d-%H`.tar.xz   /etc
You have new mail in /var/spool/mail/root

2、每周2, 4, 7备份/var/log/messages文件至/logs目录中,文件名形如“messages-yyyymmdd”

[root@centos74 test]$ crontab -l
1 2,12 * * * /app/test/backup.sh
1 1 * * 2,4,7 /app/test/backup_message.sh
[root@centos74 test]$ cat backup_message.sh
#!/bin/bash

if [ ! -e /logs ] ;  then
    mkdir -pv /logs
fi
cp -a /var/log/messages /logs/message-$(date "+%Y%m%d")
You have new mail in /var/spool/mail/root

3、每两小时取出当前系统/proc/meminfo文件中以S或M开头的信息追加至/tmp/meminfo.txt文件中

[root@centos74 test]$ crontab -l
1 2,12 * * * /app/test/backup.sh
1 1 * * 2,4,7 /app/test/backup_message.sh
1 */2 * * *  /app/test/meminfo.sh
You have new mail in /var/spool/mail/root
[root@centos74 test]$ cat meminfo.sh
#!/bin/bash
cat /proc/meminfo  |egrep "^(S|M).*" >> /tmp/meminfo.txt

4、工作日时间,每10分钟执行一次磁盘空间检查,一旦发现任何分区利用率高于80%,就执行wall警报

[root@centos74 test]$ crontab  -l
1 2,12 * * * /app/test/backup.sh
1 1 * * 2,4,7 /app/test/backup_message.sh
1 */2 * * *  /app/test/meminfo.sh
*/10 * * * * /app/test/disk_check.sh

[root@centos74 test]$ cat disk_check.sh
#!/bin/bash
val=$(df --output=pcent |egrep "[0-9]+" -o |sort -nr |head -n 1)
if [ "$val" -gt 80 ] ; then
    wall "disk 80%"
fi

2017-12-16-练习-ip-nmcli

练习1- 多网卡整合

1、使将2个网卡整合, 能达到一个网卡坏掉也能继续工作

方案1 : 使用手工配置的bond

[root@centos74 network-scripts]$ cat ifcfg-bond0
DEVICE=bond0

BOOTPROTO=static
IPADDR=192.168.27.77
PREFIX=24
GATEWAY=192.168.27.1

BONDING_OPTS="mode=active-backup miimon=100"
[root@centos74 network-scripts]$ cat ifcfg-eth1
DEVICE=eth1
MASTER=bond0
SLAVE=yes

[root@centos74 network-scripts]$ cat ifcfg-eth2
DEVICE=eth2
MASTER=bond0
SLAVE=yes

方案2 : 使用nmcli配置bonding

[root@centos74 network-scripts]  nmcli con add type bond con-name bond0 ifname bond0 mode active-backup miimon 200
[root@centos74 network-scripts]  nmcli con modify  bond0 ipv4.method static ipv4.address 192.168.27.77/24 ipv4.gateway 192.168.27.1
[root@centos74 network-scripts]  nmcli con add type bond-slave  con-name bond0-eth1 ifname eth1 master bond0
[root@centos74 network-scripts]  nmcli con add type bond-slave  con-name bond0-eth2 ifname eth2 master bond0
[root@centos74 network-scripts]  nmcli con show
[root@centos74 network-scripts]  nmcli con up bond0
[root@centos74 network-scripts]  nmcli con up bond0-eth1
[root@centos74 network-scripts]  nmcli con up bond0-eth2

方案3 : 使用nmcli 配置team

[root@centos74 network-scripts]$ nmcli con add type team con-name team0 ifname team0 config '{"runner":{"methord":"activebackup"}}'
[root@centos74 network-scripts]$ nmcli con modify team0 ipv4.method static ipv4.addresses 192.168.27.77/24 ipv4.gateway 192.168.27.1
[root@centos74 network-scripts]$ nmcli con add type team-slave  ifname eth1 master team0
[root@centos74 network-scripts]$ nmcli con add type team-slave  ifname eth2 master team0
[root@centos74 network-scripts]$ nmcli con up team0
[root@centos74 network-scripts]$ nmcli con up team-slave-eth1
[root@centos74 network-scripts]$ nmcli con up team-slave-eth2

21-2017-12-16-练习-网络其他

练习1-ftplftp使用

1、编写脚本完成2个主机日志的收集,日志目录为/root/log目录, 上传主机日志文件/var/log/message文件到这个目录,创建一个目录yyyy-MM-dd的名字修改为hostname_yyyy-MM-dd_meessage。

#!/bin/bash
#================================================
#FileName   :ftp.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-17 12:53:20
#Version    :V1.0
#Other      :
#================================================
dt=`date +%F`
hostname=`hostname -s`
newname=$hostname"_"$dt"_"messages

ftp -n <<eof
open 192.168.1.113
user anonymous 123456

binary

cd pub
mkdir $dt
put /var/log/message
rename message $newname
close
bye
eof

2、编写一个脚本完成自动日志信息上传

#!/bin/bash
#================================================
#FileName   :ftp.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-17 12:53:20
#Version    :V1.0
#Other      :
#================================================

ftp -n <<eof
open 192.168.1.113
user anonymous 123456
binary
cd pub
put /var/log/message
close
bye
eof

22-2017-12-18-练习-脚本进阶循环

练习1-分支

1、编写脚本/root/bin/createuser.sh,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显示其存在,否则添加之;显示添加的用户的id号等信息

#!/bin/bash
#================================================
#FileName   :createuser_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 18:56:27
#Version    :V1.0
#Other      :
#================================================
RED="\033[31m"
YELLOW="\033[0;33m"
RESET="\033[0m"
if [ $# -ne 1 ] ; then
    echo -e "$REDyou must be enter a parameter ,only one!$RESET"
    exit 2
fi

username=$1
id $username &>/dev/null
if [ $? -eq 0 ] ; then
    echo -e "$YELLOW$username has existed !$RESET"
else
    useradd $username &>/dev/null
fi
id $username

2、编写脚本/root/bin/yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息

case方案:

#!/bin/bash
#================================================
#FileName   :yesorno_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:09:45
#Version    :V1.0
#Other      :
#================================================

read -p "do you agree (yes/no):" choice

case $choice in
[Yy]|[Yy][Ee][Ss])
    echo "you enter a yes"
    ;;
[Nn]|[Nn][Oo])
    echo "you enter is no"
    ;;
*)
    echo "not yes or no "
    ;;
esac

if方案:

#!/bin/bash
#================================================
#FileName   :yesorno2_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:14:14
#Version    :V1.0
#Other      :
#================================================
read -p "do you agree (yes/no):" choice
yes_re="^[Yy]([Ee][Ss])?$"
no_re="^[Nn]([Nn])?$"

if [[ "$choice" =~ $yes_re ]] ; then
    echo  "you enter yes"
elif [[ "$choice" =~ $no_re ]] ; then
    echo "you enter no "
else
    echo "enter not a yes or no "
fi

3、编写脚本/root/bin/filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)

#!/bin/bash
#================================================
#FileName   :filetype_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:19:42
#Version    :V1.0
#Other      :
#================================================
RED="\033[31m"
YELLOW="\033[0;33m"
RESET="\033[0m"
if [ $# -ne 1 ] ; then
    echo -e "$REDyou must be enter a parameter ,only one!$RESET"
        exit 2
fi

file=$1
type=`ls -ld $file |cut -c 1`
#echo $type
case $type in
    -)
        echo "general file"
        ;;
    d)
        echo "dir"
        ;;
    l)
        echo "link file"
        ;;
    *)
        echo "other"
        ;;
esac

4、编写脚本/root/bin/checkint.sh,判断用户输入的参数是否为正整数

#!/bin/bash
#================================================
#FileName   :checkint_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:29:08
#Version    :V1.0
#Other      :
#================================================
RED="\033[31m"
YELLOW="\033[0;33m"
RESET="\033[0m"
if [ $# -ne 1 ] ; then
    echo -e "$REDyou must be enter a parameter ,only one!$RESET"
    exit 2
fi

val=$1

int_re="^[0-9]+$"
if [[ $val =~ $int_re ]] ; then
    echo "yes"
else
    echo "no"
fi

练习2-循环

1、判断/var/目录下所有文件的类型

#!/bin/bash
#================================================
#FileName   :test_filetype_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:37:41
#Version    :V1.0
#Other      :
#================================================
dir="/var"
for i in $(ls -1 $dir) ; do
    type=`ls -ld $file |cut -c 1`
    echo -n "$dir/$i===============>"
    case $type in
        -)
            echo "general file"
            ;;
        d)
            echo "dir"
            ;;
        l)
            echo "link"
            ;;
        s)
            echo "socket"
            ;;
        b)
            echo "block"
            ;;
        c)
            echo "character"
            ;;
        *)
            echo "other"
            ;;
    esac
done

2、添加10个用户user1-user10,密码为8位随机字符

#!/bin/bash
#================================================
#FileName   :addusers_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:46:05
#Version    :V1.0
#Other      :
#================================================

for i in `seq 1 10` ; do
        username=user$i
        useradd $username
        echo `openssl rand -base64 10| head -c 8` | passwd $username --stdin &>/dev/null
done
echo "finish"

3、/etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的文件;分别读取每个文件,以K开头的输出为文件加stop,以S开头的输出为文件名加start,如K34filename stop S66filename start

#!/bin/bash
#================================================
#FileName   :test_rcd_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:49:45
#Version    :V1.0
#Other      :
#================================================

for i in `ls -1 /etc/rc.d/rc3.d` ; do
        type=`echo $i | cut -c 1 `
        #echo type
        if [ "$type" == "S" ] ; then
                echo "$i start"
        elif [ "$type" == "K" ] ; then
                echo "$i stop"
        else
                echo "$i unkown"
        fi
done

4、编写脚本,提示输入正整数n的值,计算1+2+…+n的总和

#!/bin/bash
#================================================
#FileName   :test_sum_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 19:55:12
#Version    :V1.0
#Other      :
#================================================
if [ $# -ne 1 ] ; then
        echo "must enter a parameter ,only one "
        exit 2
fi
n=$1
digit_re="^[0-9]+$"
if [[ ! $n =~ $digit_re ]] ; then
        echo "not a digit, must a digit"
        exit 3
fi
declare -i sum=0
for i in `seq 1 $n` ; do
        sum+=$i
done
echo $sum

5、计算100以内所有能被3整除的整数之和

#!/bin/bash
#================================================
#FileName   :test_sum_3_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:03:09
#Version    :V1.0
#Other      :
#================================================
declare -i sum=0
for i in `seq 1 100` ; do
        if [ $[i%3] -eq 0 ] ; then
                sum+=$i
        fi
done
echo $sum

sum=0
for i in `seq 3 3 100` ; do
        sum+=$i
done
echo $sum

6、编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态

#!/bin/bash
#================================================
#FileName   :test_ip_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:06:22
#Version    :V1.0
#Other      :
#================================================

read -p "enter you network (like 172.18.0.0) :" network
ip_re_1="(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))"
ip_re="$ip_re_1(\.$ip_re_1){3}"
#echo $ip_re

if [[ ! "$network" =~ $ip_re ]]  ; then
        echo  " not a ip "
        exit 2
fi

net=` echo $network |cut -d "." -f 1-3`
#echo $net
for i in `seq 1 254` ; do
        {
                ip=$net.$i
                ping -c 1 -W 2 $ip &>/dev/null
                if [ $? -eq 0 ] ; then
                        echo $ip up
                else
                        echo $ip down
                fi
        }&
done
wait

7、打印九九乘法表

#!/bin/bash
#================================================
#FileName   :test_99_table_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:24:27
#Version    :V1.0
#Other      :
#================================================

num=9

for i in `seq 1 9` ; do
        for j in `seq 1 $i`; do
                echo -ne "$j*$i=$[j*i]\t"
        done
        echo
done

8、在/testdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母,如:1AbCdeFgH.html

#!/bin/bash
#================================================
#FileName   :test_make_html_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:27:50
#Version    :V1.0
#Other      :
#================================================
dir=/testdir
if [ ! -d $dir ] ; then
        mkdir -pv $dir &>/dev/null
fi
for i in `seq 1 10` ; do
        tmp=`openssl rand -base64 10  ||sed -rn "s@[^[:alpha:]]@@gp"|head -c 8`
        touch $dir/$i$tmp.html
done

9、打印等腰三角形

#!/bin/bash
#================================================
#FileName   :test_trangle_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:36:51
#Version    :V1.0
#Other      :
#================================================
line=5
for i in `seq 1 $line` ; do
        len=$[2*line+1]
        for j in `seq 1 $len` ; do
                if [ $j -le $[line-i] -o $j -ge $[line+i] ] ; then
                        echo -n " "
                else
                        echo -n "*"
                fi
        done
        echo
done

10、打印国际象棋

#!/bin/bash
#================================================
#FileName   :test_guojixiangqi_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-18 20:46:43
#Version    :V1.0
#Other      :
#================================================

line=8
line2=$[line*2]
for i in `seq 1 8 ` ; do
    for j in `seq 1 $line2 ` ; do
        if [ $[i%2] -eq 1 ] ; then
            if [ $[j%4] -eq 1 -o $[j%4] -eq 2 ] ; then
                echo -ne "\033[41m \033[0m"
            else
                echo -ne "\033[42m \033[0m"
            fi
        else
            if [ $[j%4] -eq 1 -o $[j%4] -eq 2 ] ; then
                echo -ne "\033[42m \033[0m"
            else
                echo -ne "\033[41m \033[0m"
            fi
        fi
    done
    echo
done

练习3-while1

1、编写脚本,求100以内所有正奇数之和


2、编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态,并统计在线和离线主机各多少


3、编写脚本,打印九九乘法表


4、编写脚本,利用变量RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大值和最小值


5、编写脚本,实现打印国际象棋棋盘


6、后续六个字符串:efbaf275cd、4be9c40b8b、44b2395c46、f8c8873ce0、b902c16c8b、ad865d2f63是通过对随机数变量RANDOM随机执行命令:echo $RANDOM|md5sum|cut –c1-10后的结果,请破解这些字符串对应的RANDOM值

练习4-while2

1、每隔3秒钟到系统上获取已经登录的用户的信息;如果发现用户hacker登录,则将登录时间和主机记录于日志/var/log/login.log中,并退出脚本


2、随机生成32767以内的数字,实现猜字游戏,提示比较大小,并给出提示范围,相等则退出

#!/bin/bash
#================================================
#FileName   :guess_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:运行是比较简单的,不用猜,一路回车就可以了。
#DateTime   :2017-12-22 10:45:57
#Version    :V1.0
#Other      :
#================================================

declare -i val=$RANDOM


declare -i start=0
declare -i end=32767
declare -i mid=$[(start+end)/2]
#echo $val
#echo $mid
#echo "you val is $val"

while true; do
        read -p "pleater you guesss val[${start}-${end}],default($mid)  " guess
        if [ -z  $guess ] ; then
                guess=$mid
        fi
        if [ "$guess" -eq "$val" ] ; then
                mid=$guess
                break
        elif [ "$guess" -lt "$val" ] ; then
                start=$[guess+1]
        elif [ "$guess" -gt "$val" ] ; then
                end=$[guess-1]
        else
                true
        fi
        mid=$[(start+end)/2]
done

3、用文件名做为参数,统计所有参数文件的总行数


4、用二个以上的数字为参数,显示其中的最大值和最小值


5、扫描/etc/passwd文件每一行,如发现GECOS字段为空,则填充用户名和单位电话为62985600,并提示该用户的GECOS信息修改成功。


练习5-select

1、使用select 做yes,no的判断

#!/bin/bash
#================================================
#FileName   :test_select_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-23 10:15:57
#Version    :V1.0
#Other      :
#================================================

select c in yes no ; do
        echo " you enter is $c"
        case $c in
                yes)
                        echo "yes";;
                no)
                        echo "no";;
                *)
                        echo "other";;
        esac
done

2、使用for(())方式来计算1到100直接能被3整出的数之和

#!/bin/bash
#================================================
#FileName   :test_for_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-23 10:33:25
#Version    :V1.0
#Other      :
#================================================
declare -i sum=0
for (( i=3 ; i<=100; i+=3)); do
        sum+=i
done
echo "sum:"$sum

3、trap的使用

#!/bin/bash
#================================================
#FileName   :test_trap_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-23 11:11:47
#Version    :V1.0
#Other      :
#================================================
f2(){
        trap '-' SIGINT
        echo "            trap int cancel"
}

f1(){
        echo "                 trap int ,you can ctrl +c to cancel"
        trap 'f2' SIGINT
}
trap 'f1 ' SIGINT

for i in `seq 1 100` ; do
        echo $i
        sleep 2
done

23-2017-12-18-练习-脚本进阶服务

练习3-函数

1、编写函数,实现OS的版本判断

2、编写函数,实现取出当前系统eth0的IP地址

3、编写函数,实现打印绿色OK和红色FAILED

4、编写函数,实现判断是否无位置参数,如无参数,提示错误

# color
RED="\033[0;31m"
YELLOW="\033[0;33m"
GREEN="\033[1;32m"
DARKGREEN="\033[0;32m"
OCHRE="\033[38;5;95m"
BLUE="\033[1;34m"
WHITE="\033[0;37m"
RESET="\033[0m"

get_os_version(){
        echo ` cat /etc/system-release |sed -r 's@.*release ([0-9]+).*@\1@' `
}
get_ip_of_eth0(){
        echo    `ip a show dev eth0 | sed -nr '/[[:space:]]+inet /s@[[:space:]]+inet (.*)/.*@\1@p'`
}
print_ok(){
        echo -e ${GREEN}OK${RESET}
}
print_failed(){
        echo  -e ${RED}FAILED${RESET}
}
has_parameter(){
        if [ "$#" -eq 0 ] ; then
                echo "not a parameter"
                return 1
        fi

练习4-sysv

编写服务脚本/root/bin/testsrv.sh,完成如下要求
(1) 脚本可接受参数:start, stop, restart, status
(2) 如果参数非此四者之一,提示使用格式后报错退出
(3) 如是start:则创建/var/lock/subsys/ SCRIPT_NAME , 并显示“启动成功”
考虑:如果事先已经启动过一次,该如何处理?
(4) 如是stop:则删除/var/lock/subsys/ SCRIPT_NAME , 并显示“停止完成”
考虑:如果事先已然停止过了,该如何处理?
(5) 如是restart,则先stop, 再start
考虑:如果本来没有start,如何处理?
(6) 如是status, 则如果/var/lock/subsys/ SCRIPT_NAME 文件存在,则显示
“ SCRIPT_NAME is running...”
如果/var/lock/subsys/ SCRIPT_NAME 文件不存在,则显示“ SCRIPT_NAME
is stopped...”其中: SCRIPT_NAME 为当前脚本名
(7)在所有模式下禁止启动该服务,可用chkconfig 和 service命令管理
#!/bin/bash
# chkconfig:   345 99 99
# description:      this is a testsrv


. /etc/init.d/functions

lockfile=/var/lock/subsys/$0

start(){
    if [ -e $lockfile ] ; then
        action "$0 is running"
    else
        touch $lockfile
        if [ "$?" -eq 0 ] ; then
            action "$0  start"
        else
            action "$0  failed" false
        fi
    fi
}
stop(){
    if [ -e $lockfile ] ; then
        rm -rf $lockfile
        if [ "$?" -eq 0 ] ; then
            action "$0 stop"
        else
            action "$0 stop failed" false
        fi
    else
        action "$0 is stoped"
    fi
}
restart(){
    start
    stop
}
status(){
    if [ -e $lockfile ] ; then
        action "$0 running"
    else
        action "$0 stoped"
    fi
}
usage(){
    echo "$0 {start|stop|status|restart}"
}
case $1 in
start)
    start;;
stop)
    stop;;
restart)
    restart;;
status)
    status;;
*)
    usage;;
esac

练习5-copycmd

编写脚本/root/bin/copycmd.sh
(1) 提示用户输入一个可执行命令名称
(2) 获取此命令所依赖到的所有库文件列表
(3) 复制命令至某目标目录(例如/mnt/sysroot)下的对应路径下
如:/bin/bash ==> /mnt/sysroot/bin/bash
/usr/bin/passwd ==> /mnt/sysroot/usr/bin/passwd
(4) 复制此命令依赖到的所有库文件至目标目录下的对应路径下
: 如:/lib64/ld-linux-x86-64.so.2 ==>
/mnt/sysroot/lib64/ld-linux-x86-64.so.2
(5)每次复制完成一个命令后,不要退出,而是提示用户键入新
的要复制的命令,并重复完成上述功能;直到用户输入quit退出
#!/bin/bash
#================================================
#FileName   :copycmd.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-22 15:57:39
#Version    :V1.0
#Other      :
#================================================
dst=/mnt/sysimage
overwrite=yes

if [ ! -e "$dst" ] ; then
        mkdir -pv $dst
fi
my_cp() {
        local src=$1
        local dst=$2
        local dir=`dirname $dst`
        if [ ! -e $dir ] ; then
                mkdir -pv $dir
        fi

        if [ ! -f "$dst"  -o "$overwrite" == "yes" ] ; then
                cp  $src $dst
        fi
}


while true; do
        read -p "enter you cmd :  " short_cmd
        if [ "$short_cmd" == "quit" ] ; then
                exit 0
        fi
        type $short_cmd 2>/dev/null |grep -q "builtin"
        if [ "$?" -eq 0 ] ; then
                echo "this is a buildin cmd, nothing todo,  input 'bash' for copy buildin cmd"
                continue
        fi
        short_cmd=`basename $short_cmd` &>/dev/null
        long_cmd=`which --skip-alias --skip-functions --skip-dot --skip-tilde $short_cmd 2>/dev/null`
        if [ "$?" -ne 0 ] ; then
                echo "not a valid command, please check and try again"
                continue
        fi
        # cp bin
        my_cp $long_cmd $dst$long_cmd
        # cp lib
        for lib in `ldd $long_cmd |egrep -o  "/[^[:space:]]+" ` ; do
                #echo -e "\n$lib\n"
                my_cp $lib $dst$lib
        done
        # cp man
        #for man in `man -aw $short_cmd` ; do
        #       my_cp $man ${dst}${man}
        #done
done

练习6-

1、编写函数实现两个数字做为参数,返回最大值斐波那契数列又称黄金分割数列,因数学家列昂纳多·斐波那
契以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是
这样一个数列:0、1、1、2、3、5、8、13、21、34、……
,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(
1)=1,F(n)=F(n-1)+F(n-2)(n≥2)
利用函数,求n阶斐波那契数列
#!/bin/bash
#================================================
#FileName   :tuzishulie_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-22 15:28:04
#Version    :V1.0
#Other      :
#================================================
f() {
        if [ "$1" -eq 0 ] ; then
                echo 0
                return 0
        fi
        if [ "$1" -eq 1 ] ; then
                echo 1
                return 0
        fi
        echo $[`f $[$1 -2]` + `f $[$1 -1]`]
}

echo ` f 10`
::
2、汉诺塔(又称河内塔)问题是源于印度一个古老传说。大梵天 创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上 按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘 从下面开始按大小顺序重新摆放在另一根柱子上。并且规定, 在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个 圆盘,利用函数,实现N片盘的汉诺塔的移动步骤
#!/bin/bash
f(){
        v1=$[$1%3]
        v2=$[$2%3]
        v=$[3-v1-v2]
        if [ "$3" -eq 1 ] ; then
                if  [ "$[$4%2]" -eq 1 ] ; then
                        echo -e "$v1=>$v2\n"
                else
                        echo  -e "$v=>$v2\n"
                fi
                return 0
        fi
        vv=$[$4-1]
        echo -e `f $v1 $v $[$3-1] $vv`
        echo -e "$v1=>$v2"
        echo  -e `f $v $v2 $[$3-1] $vv`
}
f2(){
        echo `f 0 2 $1 $1`
}
if [ "$#" -ne 1 ] ; then
        echo " must a parameter,only one "
fi

f2 $1

练习6-

1、输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序

#!/bin/bash
#================================================
#FileName   :test_bubble_sort_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-26 17:49:51
#Version    :V1.0
#Other      :
#================================================

read  -p "enter some value "  -a arr

cnt=${#arr[*]}
echo "count="$cnt
my_print (){
        for i in `seq 0 $[cnt-1]`; do
                echo -ne "${arr[$i]}\t"
        done
        echo
}
echo "befor bubble sort"
my_print

for i in `seq 0 $[cnt-1]`; do
        for j in `seq 0 $[i-1]`;do
                if [ "${arr[$i]}" -lt "${arr[$j]}" ] ; then
                        tmp=${arr[$i]}
                        arr[$i]=${arr[$j]}
                        arr[$j]=$tmp
                fi
        done
done

echo "after bubble sort"
my_print

2、将下图所示,实现转置矩阵matrix.sh

1 2 3          1 4 7
4 5 6  ===>    2 5 8
7 8 9          3 6 9
#!/usr/bin/python
def trans(m):
        return zip(*m)

def my_print(m):
        for i in m :
                print i

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print "before transform"
my_print(m)
m2= trans(m)
print "after transform"
my_print(m2)

24-2017-12-23-练习-常用启动故障修复

练习1

1、修改root密码

1.启动grub界面
2.输入a 添加1
3.进入后passwd 修改密码
4.reboot

2、grub添加rsa密码, 并使用光盘去破解密码

添加密码

[root@centos66 grub]$ grub-crypt
Password:
Retype password:
$6$dggD0xTUdKx6G4wt$1aMQ60tcQrllpnpxoTD0nFQjCCTq65PW9ZAxpJuesXM.wMtq599I0m19stqFyKzqhR91oeetycIML/jGOHxfu1
# vim /boot/grub/grub.conf
password --encrypt  $6$yQJwlJBSBqy4tUA6$YekOdnfaa7Dfvgso/C9pLXw1m3Oif8SohGK1KT.bZcBBqAiv2zd4.hFnl7HscYKKeccHoG5oIbF4dSuVD22v6.
[root@centos66 grub]$ reboot

光盘破解

# 进入光盘的救援模式
# chroot /mnt/sysimage
# vim /boot/grub/grub.conf 注释掉password行即可
# reboot

3、vmlinuz-2.6.32-696.el6.x86_64和initramfs-2.6.32-696.16.1.el6.x86_64.img丢失的修复方法

2个都损坏了的方法
# 进入救援模式
# chroot /mnt/sysimage
# 创建目录 /mnt/cdrom
# 挂载 mount /dev/cdrom /mnt/cdrom
# rpm安装 rpm -ivh /mnt/cdrom/Packages/kerneal[Tab下] --force
# reboot

只有initramfs损坏的话

# 进入救援模式
# chroot /mnt/sysimage
# mkinitrd initramfs-`uname-r`.img `uname-r`
# reboot

只有vmlinuxz损坏的话

# 进入救援模式
# copy过来vmlinuxz文件。 并重新命名为vmlinuz-`uname -r`
# reboot

4、bootloader损坏的修复

# 进入救援模式
# grub-install --root-directory=/ /dev/sda
# reboot

5、磁盘前27个扇区损坏的修复

# 进入救援模式
# grub-install --root-directory=/ /dev/sda
# reboot

25-2017-12-26-练习-脚本进阶3

练习1

1、利用expect 实现FTP自动上传文件

#!/bin/bash
#================================================
#FileName   :test_expect_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-26 14:47:37
#Version    :V1.0
#Other      :
#================================================

# usage ./test_expect_46_zhaojiedi.sh 172.18.101.69 test test /etc/issue /ftp/issue
host=$1
username=$2
password=$3
file=$4
upload_dir=$5

expect <<EOF
set timeout 10
spawn ftp $host
expect {
        "Name" { send "$username\n"; exp_continue }
        "Password:" { send "$password\n";exp_continue }
        "ftp>" { send "put $file $upload_dir\n"; }
}
expect "ftp>" { send "bye\n" }
EOF

2、数组:实现杨辉三角(选做)

#!/bin/bash
#================================================
#FileName   :test_yanghuisanjiao_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-26 18:03:09
#Version    :V1.0
#Other      :
#================================================
line=7
count=$[line**2-1]
declare -a arr
declare -a arr_last

print_arr_last(){
        for i in `seq 0 $[line-1] ` ; do
                echo ${arr_last[$i]}
        done
}

# init arr_last
for i in `seq 0 $[line-1]`; do
        ii=$[i+1]
        arr_last[$i]=$[$ii ** 2 -1 ]
done

print_arr_last

get_location_1(){
        local loc=$1
        local row=0
        local col=0
        for i in `seq  $[line-1] -1 0` ; do
                #echo "${i}==>${arr_last[$i]}==>"
                if [ "$loc" -gt  ${arr_last[$i]} ] ; then
                        row=$[i+1]
                        col=$[ loc-row**2]
                        echo "$row,$col"
                        return 0
                fi
        done
        echo  "0,0"
}
# get_location_1 8
get_location_2(){
        local row=$1
        local col=$2
        echo "$[row ** 2 + col]"
}
#get_location_2 2 3
is_last_col(){
        local row=$1
        local col=$2
        if [ "$col" -eq "$[row * 2]" ] ;then
                return 0
        fi
        return 1
}
echo "count=$count"


for i in `seq 0 $count` ; do
        info=`get_location_1 $i`
        echo "$info ......"
        row=`echo $info |cut -d "," -f1`
        col=`echo $info |cut -d "," -f2`
        echo "$row ... $col "

        if [ "$col" -eq 0 ] ;then
                arr[$i]=1
                echo "set $i 1"
                continue
        fi
        if [ "$col" -eq "$[row *2]" ] ; then

                arr[$i]=1
                echo "set $i 1"
                continue
        fi
        if [ "$[col%2]" -eq 1 ] ; then
                continue
        fi
        loc_left=`get_location_2 $[row-1] $[col-2]`
        loc_right=`get_location_2 $[row-1] $col`
        echo "i,left,right==>$i ,$loc_left,$loc_right"
        v1=${arr[$loc_left]}
        v2=${arr[$loc_right]}
        echo "v1,v2=>$v1,$v2"
        arr[$i]=$[ v1 + v2 ]
done
print_space(){
        for i in `seq 1 $1`; do
                echo -n " "
        done
}

for i in `seq 0 $count` ; do
        info=`get_location_1 $i`
        #echo "$info ......"
        row=`echo $info |cut -d "," -f1`
        col=`echo $info |cut -d "," -f2`
        if [ "$col" -eq 0 ] ; then
                for j in `seq 1 $[2*line-2*row-2]` ; do
                        echo -n " "
                done
        fi
        if [ "$col" -ne  "$[row *2]" ] ; then
                echo -ne "${arr[$i]}  "
        else
                echo -e "${arr[$i]}  "
        fi
done

3、输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序

#!/bin/bash
#================================================
#FileName   :test_bubble_sort_46_zhaojiedi.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-26 17:49:51
#Version    :V1.0
#Other      :
#================================================

read  -p "enter some value "  -a arr

cnt=${#arr[*]}
echo "count="$cnt
my_print (){
        for i in `seq 0 $[cnt-1]`; do
                echo -ne "${arr[$i]}\t"
        done
        echo
}
echo "befor bubble sort"
my_print

for i in `seq 0 $[cnt-1]`; do
        for j in `seq 0 $[i-1]`;do
                if [ "${arr[$i]}" -lt "${arr[$j]}" ] ; then
                        tmp=${arr[$i]}
                        arr[$i]=${arr[$j]}
                        arr[$j]=$tmp
                fi
        done
done

echo "after bubble sort"
my_print

26-2017-12-23-练习-常用启动故障修复2

练习1-修复

1、lvm的根文件系统的/etc/fstab,/boot目录丢失的修复

1.分区和逻辑卷信息的查看
2.lvm的激活,swap的激活和设置/etc/fstab
3.grub-install安装grub
4.安装kernel
5.编写grub.conf文件

2、分区的根文件系统的/etc/fstab,/boot目录丢失的修复

1.分区信息的查看
2.设置/etc/fstab
3.grub-install安装grub
4.安装kernel
5.编写grub.conf文件

练习2-定制linux

1、定制一个linux,支持bash,ifconfig,nmcli,insmod,modprobe命令


27-2017-12-27-练习-自定linux和编译内核

练习1-定制linux

1、定制一个linux

准备磁盘并分区格式化

[root@centos66 Bash]$ fdisk /dev/sdc

WARNING: GPT (GUID Partition Table) detected on '/dev/sdc'! The util fdisk doesn't support GPT. Use GNU Parted.


WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
                switch off the mode (command 'c') and change display units to
                sectors (command 'u').

Command (m for help): p

Disk /dev/sdc: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xa55d77b3

Device Boot      Start         End      Blocks   Id  System

Command (m for help): n
Command action
e   extended
p   primary partition (1-4)
p
Partition number (1-4):
Value out of range.
Partition number (1-4): 1
First cylinder (1-2610, default 1):
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-2610, default 2610): +1G

Command (m for help): n
Command action
e   extended
p   primary partition (1-4)
p
Partition number (1-4): 2
First cylinder (133-2610, default 133):
Using default value 133
Last cylinder, +cylinders or +size{K,M,G} (133-2610, default 2610):
Using default value 2610

Command (m for help): p

Disk /dev/sdc: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xa55d77b3

Device Boot      Start         End      Blocks   Id  System
/dev/sdc1               1         132     1060258+  83  Linux
/dev/sdc2             133        2610    19904535   83  Linux

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[root@centos66 Bash]$ partprobe
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or resource busy).  As a result, it may not reflect all of your changes until after reboot.
Warning: /dev/sdc contains GPT signatures, indicating that it has a GPT table.  However, it does not have a valid fake msdos partition table, as it should.  Perhaps it was corrupted -- possibly by a program that doesn't understand GPT partition tables.  Or perhaps you deleted the GPT table, and are now using an msdos partition table.  Is this a GPT partition table?
Warning: Unable to open /dev/sr1 read-write (Read-only file system).  /dev/sr1 has been opened read-only.
[root@centos66 Bash]$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0     11:0    1 1024M  0 rom
sr1     11:1    1  5.8G  0 rom
sr2     11:2    1 1024M  0 rom
sr3     11:3    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    2G  0 part [SWAP]
└─sda6   8:6    0    1G  0 part
sdb      8:16   0  100G  0 disk
├─sdb1   8:17   0    1G  0 part
├─sdb2   8:18   0   20G  0 part
├─sdb3   8:19   0    1G  0 part
├─sdb4   8:20   0    1K  0 part
├─sdb5   8:21   0   20G  0 part
├─sdb6   8:22   0    1G  0 part
└─sdb7   8:23   0    1G  0 part
sdc      8:32   0   20G  0 disk
├─sdc1   8:33   0    1G  0 part
└─sdc2   8:34   0   19G  0 part
[root@centos66 Bash]$ mkfs
mkfs          mkfs.cramfs   mkfs.ext2     mkfs.ext3     mkfs.ext4     mkfs.ext4dev  mkfs.msdos    mkfs.vfat
[root@centos66 Bash]$ mkfs
mkfs          mkfs.cramfs   mkfs.ext2     mkfs.ext3     mkfs.ext4     mkfs.ext4dev  mkfs.msdos    mkfs.vfat
[root@centos66 Bash]$ mkfs.ext4 /dev/sdc1
mke2fs 1.41.12 (17-May-2010)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
66384 inodes, 265064 blocks
13253 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=272629760
9 block groups
32768 blocks per group, 32768 fragments per group
7376 inodes per group
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376

Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 36 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.
[root@centos66 Bash]$ mkfs.ext4 /dev/sdc2
mke2fs 1.41.12 (17-May-2010)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
1245184 inodes, 4976133 blocks
248806 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
152 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
        4096000

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 35 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

[root@centos66 Bash]$ cls

安装grub,复制文件,grub配置文件启用

[root@centos66 Bash]$ mkdir /mnt/boot
[root@centos66 Bash]$ mount /dev/sdc1 /mnt/boot
[root@centos66 Bash]$ grub-install  --root-directory=/mnt /dev/sdc
Probing devices to guess BIOS drives. This may take a long time.
Installation finished. No error reported.
This is the contents of the device map /mnt/boot/grub/device.map.
Check if this is correct or not. If any of the lines is incorrect,
fix it and re-run the script 'grub-install'.

(fd0)   /dev/fd0
(hd0)   /dev/sda
(hd1)   /dev/sdb
(hd2)   /dev/sdc

[root@centos66 mnt]$ cd /mnt/boot
[root@centos66 boot]$ ls
grub  lost+found
[root@centos66 boot]$ cp /boot/vmlinuz-2.6.32-696.el6.x86_64  .
[root@centos66 boot]$ cp /boot/initramfs-2.6.32-696.el6.x86_64.img .
[root@centos66 boot]$ cp /boot/grub/grub.conf grub/
[root@centos66 ~]$ vim /mnt/boot/grub/grub.conf
[root@centos66 ~]$ cat /mnt/boot/grub/grub.conf
default=0
timeout=5
title centos6.9
kernel /vmlinuz-2.6.32-696.el6.x86_64 root=/dev/sda2  selinux=0 init=/bin/bash
initrd /initramfs-2.6.32-696.el6.x86_64.img

[root@centos66 boot]$ tree
.
├── grub
│   ├── device.map
│   ├── e2fs_stage1_5
│   ├── fat_stage1_5
│   ├── ffs_stage1_5
│   ├── grub.conf
│   ├── iso9660_stage1_5
│   ├── jfs_stage1_5
│   ├── minix_stage1_5
│   ├── reiserfs_stage1_5
│   ├── stage1
│   ├── stage2
│   ├── ufs2_stage1_5
│   ├── vstafs_stage1_5
│   └── xfs_stage1_5
├── initramfs-2.6.32-696.el6.x86_64.img
├── lost+found
└── vmlinuz-2.6.32-696.el6.x86_64

2 directories, 16 files

创建根目录

[root@centos66 ~]$ mkdir /mnt/sysroot
[root@centos66 ~]$ mount /dev/sdc2 /mnt/sysroot/
[root@centos66 ~]$ ll /
total 168
drwxr-xr-x.   7 root root  4096 Dec 15 02:35 app
dr-xr-xr-x.   2 root root  4096 Nov 26 12:58 bin
dr-xr-xr-x.   3 root root  4096 Dec 16  2017 boot
drwxr-xr-x.   2 root root  4096 Nov 26 12:58 build
drwxr-xr-x.   2 root root  4096 Nov 26 12:44 cgi-bin
drwxr-xr-x.   4 root root  4096 Nov 26 12:44 conf
drwxr-xr-x   20 root root  4560 Dec 16 06:51 dev
drwxr-xr-x.   3 root root  4096 Nov 26 12:44 error
drwxr-xr-x. 127 root root 12288 Dec 16 06:58 etc
drwxr-xr-x.   3 root root  4096 Dec 14 07:21 git
drwxr-xr-x.  27 root root  4096 Dec 10 21:40 home
drwxr-xr-x.   2 root root  4096 Jul  7 03:19 htdocs
drwxr-xr-x.   3 root root  4096 Nov 26 12:44 icons
drwxr-xr-x.   2 root root  4096 Nov 26 12:58 include
dr-xr-xr-x.  11 root root  4096 Nov 26 12:25 lib
dr-xr-xr-x.   9 root root 12288 Nov 26 12:54 lib64
drwxr-xr-x.   2 root root  4096 Nov 26 12:44 logs
drwx------.   2 root root 16384 Nov  7 15:26 lost+found
drwxr-xr-x.   4 root root  4096 Nov 26 12:44 man
drwxr-xr-x.  14 root root 12288 Jul  7 03:20 manual
drwxr-xr-x.   6 root root  4096 Dec 10 04:32 media
drwxr-xr-x    2 root root     0 Dec 16 06:42 misc
drwxr-xr-x.   9 root root  4096 Dec 16 06:58 mnt
drwxr-xr-x.   2 root root  4096 Nov 26 12:44 modules
drwxr-xr-x    2 root root     0 Dec 16 06:42 net
drwxr-xr-x.   3 root root  4096 Nov  7 15:38 opt
dr-xr-xr-x  151 root root     0 Dec 16  2017 proc
dr-xr-x---.  38 root root  4096 Dec 16 06:48 root
dr-xr-xr-x.   2 root root 12288 Nov 26 12:55 sbin
drwxr-xr-x.   2 root root  4096 Nov  7 15:31 selinux
drwxr-xr-x.   2 root root  4096 Sep 23  2011 srv
drwxr-xr-x   13 root root     0 Dec 16  2017 sys
drwxr-xr-x.   3 root root  4096 Nov 13 01:43 testdir
drwxrwxrwt.  17 root root  4096 Dec 16 06:54 tmp
drwxr-xr-x.  13 root root  4096 Nov  7 15:32 usr
drwxr-xr-x.  22 root root  4096 Nov 26 12:40 var
[root@centos66 ~]$ mkdir -pv /mnt/sysroot/{etc,lib,lib64,bin,sbin,tmp,var,usr,opt,home,root,boot,dev,mnt,media}
mkdir: created directory '/mnt/sysroot/etc'
mkdir: created directory '/mnt/sysroot/lib'
mkdir: created directory '/mnt/sysroot/lib64'
mkdir: created directory '/mnt/sysroot/bin'
mkdir: created directory '/mnt/sysroot/sbin'
mkdir: created directory '/mnt/sysroot/tmp'
mkdir: created directory '/mnt/sysroot/var'
mkdir: created directory '/mnt/sysroot/usr'
mkdir: created directory '/mnt/sysroot/opt'
mkdir: created directory '/mnt/sysroot/home'
mkdir: created directory '/mnt/sysroot/root'
mkdir: created directory '/mnt/sysroot/boot'
mkdir: created directory '/mnt/sysroot/dev'
mkdir: created directory '/mnt/sysroot/mnt'
mkdir: created directory '/mnt/sysroot/media'

复制命令并测试

[root@centos66 ~]$ vim /root/copy_cmd.sh
[root@centos66 ~]$ cat /root/copy_cmd.sh
#!/bin/bash
#================================================
#FileName   :copycmd.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-22 15:57:39
#Version    :V1.0
#Other      :
#================================================
dst=/mnt/sysroot
overwrite=yes

if [ ! -e "$dst" ] ; then
        mkdir -pv $dst
fi
my_cp() {
        local src=$1
        local dst=$2
        local dir=`dirname $dst`
        if [ ! -e $dir ] ; then
                mkdir -pv $dir
        fi

        if [ ! -f "$dst"  -o "$overwrite" == "yes" ] ; then
                cp  $src $dst
        fi
}


while true; do
        read -p "enter you cmd :  " short_cmd
        if [ "$short_cmd" == "quit" ] ; then
                exit 0
        fi
        type $short_cmd 2>/dev/null |grep -q "builtin"
        if [ "$?" -eq 0 ] ; then
                echo "this is a buildin cmd, nothing todo,  input 'bash' for copy buildin cmd"
                continue
        fi
        short_cmd=`basename $short_cmd` &>/dev/null
        long_cmd=`which --skip-alias --skip-functions --skip-dot --skip-tilde $short_cmd 2>/dev/null`
        if [ "$?" -ne 0 ] ; then
                echo "not a valid command, please check and try again"
                continue
        fi
        # cp bin
        my_cp $long_cmd $dst$long_cmd
        # cp lib
        for lib in `ldd $long_cmd |egrep -o  "/[^[:space:]]+" ` ; do
                #echo -e "\n$lib\n"
                my_cp $lib $dst$lib
        done
        # cp man
        #for man in `man -aw $short_cmd` ; do
        #       my_cp $man ${dst}${man}
        #done
done
[root@centos66 ~]$ /root/copy_cmd.sh
enter you cmd :  bash
enter you cmd :  ifconfig
enter you cmd :  insmod
enter you cmd :  ping
enter you cmd :  mount
enter you cmd :  ls
enter you cmd :  cat
enter you cmd :  stat
mkdir: created directory '/mnt/sysroot/usr/bin'
enter you cmd :  ping
enter you cmd :  nmcli
mkdir: created directory '/mnt/sysroot/usr/lib64'
enter you cmd :  ip
enter you cmd :  stat
enter you cmd :  pwd
this is a buildin cmd, nothing todo,  input 'bash' for copy buildin cmd
enter you cmd :  bash
enter you cmd :  modprobe
enter you cmd :  rmmod
enter you cmd :  mount
enter you cmd :  quit

切根测试

[root@centos66 ~]$ chroot /mnt/sysroot/
bash-4.1# ls
bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  root  sbin  tmp  usr  var
bash-4.1# cd
bash-4.1# ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.454 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.030 ms
^C
--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1712ms
rtt min/avg/max/mdev = 0.030/0.242/0.454/0.212 ms
bash-4.1# nmcli
Usage: nmcli [OPTIONS] OBJECT { COMMAND | help }

OPTIONS
-t[erse]                                   terse output
-p[retty]                                  pretty output
-m[ode] tabular|multiline                  output mode
-f[ields] <field1,field2,...>|all|common   specify fields to output
-e[scape] yes|no                           escape columns separators in values
-v[ersion]                                 show program version
-h[elp]                                    print this help

OBJECT
nm          NetworkManager status
con         NetworkManager connections
dev         devices managed by NetworkManager

bash-4.1# exit
exit

[root@centos66 ~]$ modinfo  -n e1000
/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net/e1000/e1000.ko
[root@centos66 ~]$ mkdir /mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net
mkdir: cannot create directory '/mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net': No such file or directory
[root@centos66 ~]$ mkdir /mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net -pv
mkdir: created directory '/mnt/sysroot/lib/modules'
mkdir: created directory '/mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64'
mkdir: created directory '/mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel'
mkdir: created directory '/mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers'
mkdir: created directory '/mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net'
cp /lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net/e1000/e1000.ko /mnt/sysroot/lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net/e1000/e1000.ko

最后取出磁盘,作为新系统的第一个硬盘即可

练习2-

1、修改内核参数

[root@centos66 rules.d]$ echo 1 > /proc/sys/net/ipv4/ip_forward
[root@centos66 rules.d]$ sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
[root@centos66 rules.d]$ sysctl -p

2、给制定硬盘添加软连接

[root@centos66 rules.d]$ cat  /etc/udev/rules.d/80-disk.rules
SUBSYSTEM=="block", KERNEL=="sdb" ,SYMLINK="disk2"

28-2017-12-28-练习selinux

练习1-selinux

2、使用restore修复selinux

[root@centos74 html]$ ll -Z index.html
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
[root@centos74 html]$ cp index.html  /root
[root@centos74 html]$ ll -Z /root/index.html index.html
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 /root/index.html
[root@centos74 html]$ mv /root/index.html  .
mv: overwrite ‘./index.html’? y
[root@centos74 html]$ ll -Z
-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 index.html
[root@centos74 html]$ restorecon -R  /var/www/html/
[root@centos74 html]$ ll -Z
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html

3、查看semanager由那个包提供 ,并查看默认的安全上下文,添加安全上下文,删除安全上下文

[root@centos74 html]$ which semanage
/usr/sbin/semanage
[root@centos74 html]$ rpm -qf /usr/sbin/semanage
policycoreutils-python-2.5-17.1.el7.x86_64
[root@centos74 html]$ semanage fcontext -l
[root@centos74 app]$ semanage fcontext -a -t httpd_sys_content_t '/app(/.*)?'
[root@centos74 app]$ touch /app/11.txt
[root@centos74 app]$ restorecon -Rv /app
[root@centos74 app]$ ll -Z 11.txt
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 11.txt

4、添加ssh的监听端口20022,并测试

[root@centos74 app]$ vim /etc/ssh/ssh_config
[root@centos74 app]$ cat /etc/ssh/ssh_config  |grep Port
Port 22
Port 20022
[root@centos74 app]$ systemctl restart sshd
[root@centos74 app]$ netstat -tunlp |grep sshd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6252/sshd
tcp6       0      0 :::22                   :::*                    LISTEN      6252/sshd

[root@centos74 app]$ semanage port -l |grep ssh
ssh_port_t                     tcp      22
[root@centos74 app]$ semanage port -a -t ssh_port_t -p tcp 20002
[root@centos74 app]$ semanage port -l |grep ssh
ssh_port_t                     tcp      20002, 22

[root@centos74 app]$ setenforce 0
[root@centos74 app]$ systemctl status sshd.service
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2017-12-28 12:31:56 CST; 8s ago
        Docs: man:sshd(8)
                man:sshd_config(5)
Main PID: 6598 (sshd)
CGroup: /system.slice/sshd.service
                └─6598 /usr/sbin/sshd -D

Dec 28 12:31:56 centos74.magedu.com systemd[1]: Starting OpenSSH server daemon...
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on 0.0.0.0 port 20022.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on :: port 20022.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on 0.0.0.0 port 22.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on :: port 22.
Dec 28 12:31:56 centos74.magedu.com systemd[1]: Started OpenSSH server daemon.
[root@centos74 app]$ setenforce 1
[root@centos74 app]$ systemctl status sshd.service
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2017-12-28 12:31:56 CST; 36s ago
        Docs: man:sshd(8)
                man:sshd_config(5)
Main PID: 6598 (sshd)
CGroup: /system.slice/sshd.service
                └─6598 /usr/sbin/sshd -D

Dec 28 12:31:56 centos74.magedu.com systemd[1]: Starting OpenSSH server daemon...
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on 0.0.0.0 port 20022.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on :: port 20022.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on 0.0.0.0 port 22.
Dec 28 12:31:56 centos74.magedu.com sshd[6598]: Server listening on :: port 22.
Dec 28 12:31:56 centos74.magedu.com systemd[1]: Started OpenSSH server daemon.

[root@centos74 app]$ netstat -tunlp  |grep ssh
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6598/sshd
tcp        0      0 0.0.0.0:20022           0.0.0.0:*               LISTEN      6598/sshd
tcp6       0      0 :::22                   :::*                    LISTEN      6598/sshd
tcp6       0      0 :::20022                :::*                    LISTEN      6598/sshd

6、修改selinux的布尔值

[root@centos74 app]$ semanage boolean  -l |grep ftp |grep write
tftp_anon_write                (off  ,  off)  Allow tftp to anon write
ftpd_anon_write                (off  ,  off)  Allow ftpd to anon write
[root@centos74 app]$ setsebool  ftpd_anon_write=1 -P

7、编写一个脚本完成selinux各个状态切换的脚本

#!/bin/bash
#================================================
#FileName   :set_selinux.sh
#Author     :zhaojiedi
#Description:
#DateTime   :2017-12-28 13:39:06
#Version    :V1.0
#Other      :
#================================================

# show current status
has_disabled=0
#sestatus | grep -q "disabled"
current_status=`sed -rn '/^SELINUX/s@^SELINUX=(.*)@\1@p' /etc/sysconfig/selinux`

if [ "$current_status" -eq "disabled" ] ; then
                has_disabled=1
else
                has_disabled=0
fi


# case

case $1 in
enforcing)
                setenforce 1
                sed -i 's@SELINUX=.*@SELINUX=enforcing@' /etc/sysconfig/selinux
                ;;
permissive)
                setenforce 0
                sed -i 's@SELINUX=.*@SELINUX=permissive@' /etc/sysconfig/selinux
                ;;
disabled)
                setenforce 0
                has_disabled=1
                sed -i 's@SELINUX=.*@SELINUX=disabled@' /etc/sysconfig/selinux
                ;;
*)
                echo "Usage: set_selinux [ enforcing | permissive | disabled ]"
                exit 1
                ;;
esac

if [ "$has_disabled" -eq 1 ] ; then
                echo -e "\033[31myou need to reboot \033[0m"
fi

01-2017-07-练习-Linux简介练习

02-2017-11-08-练习-日期开机关机

03-2017-11-09-练习-glob

04-2017-11-09-练习-目录相关

05-2017-11-09-练习-head-tr-管道

06-2017-11-16-练习-用户管理

07-2017-11-10-练习-wc-useradd

08-2017-11-10-练习-grep-文本

09-2017-11-13-练习-find

10-2017-11-14-练习-vim

<no title>

12-2017-11-23-练习-bash

13-2017-11-25-练习-压缩

14-2017-11-28-练习-sed

15-2017-11-28-练习-rpm

16-2017-12-01-练习-磁盘管理

17-2017-12-03-练习-高级磁盘管理

18-2017-12-13-练习-网络

19-2017-12-15-练习-进程管理和作业管理

2017-12-16-练习-ip-nmcli

21-2017-12-16-练习-网络其他

22-2017-12-18-练习-脚本进阶循环

23-2017-12-18-练习-脚本进阶服务

24-2017-12-23-练习-常用启动故障修复

25-2017-12-26-练习-脚本进阶3

26-2017-12-23-练习-常用启动故障修复2

27-2017-12-27-练习-自定linux和编译内核

28-2017-12-28-练习selinux

课堂笔记

08-2017-11-20

上节课回顾

本节内容

08-2017-11-20

上节课回顾

本节内容

培训优点

  • 有一帮志同道合的人
  • 有人督促
  • 节约时间成本

书籍推荐: 如何从新手到大师

博客一周1-2篇

rhcsa -> rhce -> rhca

rhce 大概3k左右。 英文版的教材

选择改变人生,态度决定高度

李宗华老师, 班主任

关门, 饮水机

每周至少一篇

rom: 只读的 ram: 断电不丢失

去ioe化

  • ibm
  • oracle
  • emc

服务器分类

  • 塔式服务器: 样子和家用台式机的主机一样。
  • 机架式服务器:有标准尺寸的,一个机柜放几个服务器的。1u=1.75英寸(44.45mm),宽度19英寸(48.26cm)。
  • 刀片式服务器:一个机架式机箱内密集插入多个刀片样子的服务器。

CPU: center processing unit 中央处理单元

cpu公司

  • intel
  • amd
  • ibm

cpu 类型

  • x86
  • x64
  • ram
  • m68000
  • power
  • powerpc
  • Ultraparc
  • alpha
  • 安腾

bios内置有程序

08-2017-11-20

上节课回顾

网络

  • das:直接附加存储
  • nas:网络附加存储
  • san:存储区域网络
_images/das-nas-san.png

系统调用:system call 系统调用。运行在内核空间

函数库:运行在用户空间

abi:应用程序二进制接口

api:应用程序编程接口

用户空间

内核空间

编程语言 * 低级语言 * 中级语言 * 高级语言

本节内容

计算机发展史:

  • 手工
  • 磁带
  • 卫星机
  • 多道程序
  • 多终端
  • 多路信息计算系统multics 失败的项目
  • unix
  • linux

gnu

  • gnu:gnu is not unix
  • gpl: gnu general public license
  • free software foundation

发行版分支

软件分类

  • 商业
  • 共享
  • 自由

linux哲学思想(5条)

  • 一切皆文件
  • 组合小功能完成大功能
  • 功能单一
  • 避免用户界面
  • 配置文件使用文本

获取centos

  • aliyun
  • sohu
  • 163

转化windows的磁盘分区

convert e:/fs:ntfs window

网络连接方式

  • hostonly:相当与vm1之间连接一个交换机,只要都是hostonly的机器,都可以相互连接。无法和别的物理机器连接。
  • nat:虚拟交换机,你可以连接外面,外面连不到你。
  • 桥接:虚拟交换机, 3线互通。

分区类型

  • mbr:
  • gpt:
http://www.xitongcheng.com/jiaocheng/xtazjc_article_15051.html

硬盘

/dev/sd{a,b,c,d},1-4表示主分区或者扩展分区, 5之后表示逻辑分区

引导系统的一定要在主分区上。一个硬盘最多4个主分区

whoami

who am i

who

runlevel

startx

init 5

strace 查看系统调用

ltrace 查看库调用

命令总结

bc:计算器
free:查看内存
who: 查看用户
whoami: 查看终端
lsblk:查看块设备
halt:关机
poweroff:关机
init:运行级别
runlevel设置运行级别
startx:启动图形终端
tty:显示终端
reboot:重启终端
ifconfig:查看ip信息
uname :查看内核信息

上面各个命令练习: bc

[root@centos6 ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2^2
4
ibase=2
11
3
quit

free

[root@centos6 ~]# free -h
            total       used       free     shared    buffers     cached
Mem:          980M       818M       162M       2.4M        36M       450M
-/+ buffers/cache:       331M       648M
Swap:         2.0G         0B       2.0G

who,whoami who am i

[root@centos6 ~]# who
root     tty1         2017-11-07 16:20 (:0)
root     pts/0        2017-11-07 16:20 (:0)
root     pts/1        2017-11-07 16:34 (:0)
root     pts/2        2017-11-07 16:39 (192.168.27.1)
root     pts/3        2017-11-07 17:11 (192.168.27.1)
[root@centos6 ~]# whoami
root
[root@centos6 ~]# who -r
        run-level 5  2017-11-07 16:11
[root@centos6 ~]# who am i
root     pts/3        2017-11-07 17:11 (192.168.27.1)

lsblk

[root@centos6 ~]# lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sr0     11:0    1  3.7G  0 rom  /media/CentOS_6.9_Final
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    2G  0 part [SWAP]

显示上一次运行级别和本地的运行级别 runlevel

[root@centos6 ~]# runlevel
N 5

tty

[root@centos6 ~]# tty
/dev/pts/4

uname

[root@centos6 ~]# uname
Linux
[root@centos6 ~]# uname -a
Linux centos6.magedu.com 2.6.32-696.el6.x86_64 #1 SMP Tue Mar 21 19:29:05 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
[root@centos6 ~]# uname -r
2.6.32-696.el6.x86_64
[root@centos6 ~]# cat /etc/centos-release
CentOS release 6.9 (Final)

勿必完成任务:

  • 系统完整完毕
  • 使用xshell或者crt连接上去。
  • nano编辑器使用

安装流程

  • 语言键盘
  • 位置选择
  • 主机名
  • 网络配置
  • 分区
  • 时区选择
  • 包选择
  • license
  • 用户创建
  • 日期和时间
  • kdump设置

03-2017-11-08

上节课回顾

命令

nano:修改文本 gedit:图形边界器

本节内容

lscpu:查看cpu信息

L1d:数据缓存

L1i:指令缓存

lsblk:查看硬盘

free:查看内存

cat /proc/meminfo:查看内存

lsb_release:查看操作系统发行版本

cat /etc/motd : message of the day 登陆成功提示

rz :上传文件

图形界面不用输入密码

/etc/gdm/custom.conf
[deamon]
AutomaticLoginEnable=true
AutomaticLogin=root
代码含义:启动自动登录,设置自动登陆用户名

enable :查看所有内部命令,centos6,7都是61个

ctrl + d : 快速注销, 相当于执行logout。

help:查看所有命令,并提示有帮助信息

enable -n logout: 禁用logout的命令

enable logout:启用logout的命令

enable -n :查看所有被禁用的命令

命令执行步骤

  1. bash内置查找
  2. hash查找
  3. path环境变量目录找。

hash -d 清空指定命令的缓存

不使用别名用法: ls,或者使用单引号引这

hash -p /usr/bin/free f 给hash的命令起个别名

hash -r : 清空所有缓存

echo : bash 内建,也是外部命令。

不同shell集成的命令也是不同的。

外部命令依赖与PATH环境变量的设置。

alias:查看系统的所有别名

unalias cdnet:取消别名

centos6从500开始,centos7从1000开始。

ctrl + c : 终止任务。

ctrl + d : 正常退出

ctrl + l : 清空屏幕

多个命令可以使用;比如sleep 10 ; ls

一行命令可以分行写, 使用转义符

1970年1月1日作为时间记录基

reset 重置

timedatectl set-teimzone PACIFIC/TONGATAPU 设置时区

时区修改

centos7 : timedatectl
centos6 : tzselect

tz:windows上传到linux上

sz:linux传输文件到windows

screen:可以远程协助

iconv -l 查看编码

iconv -f gb2312 -t utf-8 in.txt -o out.txt

echo f1{,.bak} = f1 f1.bak

echo f{001..020}

~2tab显示系统所有用户

$2tab显示系统的变量

makewhatis:centos6 制作 whatis数据库

mandb:centos7 制作whatis数据库

man 章节

# 用户命令 # 系统调用 # 库调用 # 设备文件 # 配置文件 # 游戏 # 杂项 # 管理类 # 内核api

关系的章节是1,5,8

修改/etc/issue,man issue,man agetty

man -key password : 查找指定关键词相关的命令

info帮助文档的使用

sosreport:

tldp: the linux document project

slide

!ser:p 只是打印这个命令不执行。

!$:上一个命令的最后一个参数。

!^:上一个命令的第一个参数。

!* :上面的所有参数。

ctrl +r : 查找命令历史。根据关键词

ctrl+g:退出搜索。

esc + . : 自动补充上一个命令的最后一个参数。

` [root@centos7 ~ (84)]echo $PS1 \e[33m[\u@\h \W (\#)]\e[0m ` e 和033一样的。 e[33m相当与开始颜色配置,33代表指定的颜色,可以修改。 e[0m代表颜色结束控制。 u 用户名 w 当前目录名字 W当前目录基名 #开机后命令历史数

enable :查看说明内置命令

enable -n :查看所有禁用的内置命令

hash:

  • -l:显示
  • -p:给全路径起个简短的名字
  • -t:打印指定name的缓存路径
  • -d: 清空指定name的
  • -r:清空hash

重复执行上一条命令(4种): * 方向键上翻 * !! * !-1 * ctrl +p ``` !:0执行前一个命令,不加参数 !:n执行上一个命令的第几个参数。0代表命令本身。 !$:上一个命令的最后一个参数 !*:上一条命令的所有参数

ctrl + n :显示当前历史中的下一条命令, 但是不执行 ctrl + j:执行当前命令, 没有啥用 !str: 重复执行第一个str打头的命令 !?str:重复执行第一个包含str命令的 !str:p:只是打印,不执行

^str:删除上一条命令的第一个str ^str1^str2:将上一个命令的str1换成str2 !:gs/str1/str2:将上一条命令的所有str1都替换为str2

ctrl + r:在命令历史中搜索命令 ctrl + g:退出历史搜索 ```

``` # System wide environment and startup programs, for login setup # Functions and aliases go in /etc/bashrc

``` profile 这个文件主要是环境变量和启动设置先关 bashrc:函数和别名相关的。

ctl+ s : 阻止屏幕输出,锁定屏幕

ctrl + q:允许屏幕输出

ctrl + z: 挂起命令

man搜索使用技巧 * man -a keyword:列出关键词的所有文档 * man -k keyword:列出关键词相关的所有文档,模糊匹配的。 * man -w keyword:列出帮助文档的位置 * man -f keyword:列出文档的简要说明和帮助文档所属类型

man帮助文档翻页技巧 * space: 下翻一屏 * b: 上翻一屏 * d:下翻半屏 * u:上翻半屏 * return:下翻一行 * q:退出 * #:跳到第几行 * G:翻到文档的结果 * /?:查找 * n,N:上一个下一个

info使用技巧 * tab:移动到下一个连接 * d:显示目录 * enter:进入连接 * n,p:进入下一个,上一个连接 * u,l,上一层,最后一层连接 * s 文字搜索 * q:退出

08-2017-11-20

whatis = man - f

whereis = man -aw

上节课回顾

本节内容

chvt 3: 切换终端

history -p cmd:执行命令跳过记录

history -s cmd : 伪造历史

HISTTIMEFORMAT:修改history显示格式

HISTIGNORE

HISTCONTROL:

www.pathname.org/fhs:查看目录命令 filesystem hierarchy standard 文件系统层次标准

字符设备和块设备: * 字符:顺序读取。

echo “- - -” > /sys/class/scsi_host/host0/scan

自己写一个扫描硬件的脚本在使用脚本目录下scanscsi.sh

查看设备文件系统和类型 ```bash [root@centos7 sh]# lsblk -a -o+FSTYPE,TYPE NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT FSTYPE TYPE sda 8:0 0 200G 0 disk disk ├─sda1 8:1 0 1G 0 part /boot ext4 part ├─sda2 8:2 0 128G 0 part [SWAP] swap part ├─sda3 8:3 0 48.8G 0 part / ext4 part ├─sda4 8:4 0 1K 0 part part └─sda5 8:5 0 19.5G 0 part /app ext4 part sdb 8:16 0 1G 0 disk disk sr0 11:0 1 8.1G 0 rom /run/media/root/CentOS 7 x86_64 iso9660 rom

``` systemctl start autofs:启动autofs,自动实现挂载。/misc/cd目录

文件颜色 * 蓝色: 文件夹 * 绿色: 可执行 * 浅蓝色: 链接文件 * 红色: 压缩文件 * 灰色: 其他文件 * 粉色: socket文件 * 黄色: 管道文件

/etc/DIR_COLORS 定义目录颜色的。

pwd -P : 显示真正所在目录

ctime:关心的是元数据

mtime:

atime:访问时间

超过一天,文件修改。

如何屏蔽atime

recursive 递归。

ls -1: 列显示列表

ls -X:按照后缀去排序

f[A-C]:不仅仅是A-C的。

ls -a -I “[^.]*” = l. = ls -a .*

cp –preserve: 指定保留的属性。

cp -f : 覆盖其他人的文件

cp –backup : 给原有文件备份,然后复制。

mknod:创建特殊文件

rename “.log” “.log.bak” *log

定义别名完成rm成mv命令,完成数据删除都剪切到指定的目录

man 7 glob 查看glob相关的配置文件

05-2017-11-13

上节课回顾

本节内容

[root@centos7 boot]# lsof |grep deleted : 查看删除文件的信息

删除大文件方法, 可以使用重定向先制空,然后在删除文件。返值短时间内无法释放空间。

直接指针: 12个 12* 4k = 48k

间接指针: 1个, 1* 4k * 1024 = 4M

二级指针:1个,1* 4k * 1024 * 1024 =4G

三级指针: 1个,1*4k * 1024 * 1024 = 4T


watch -n 1 df -i /boot: 监控指定命令的结果


centos6: / inode 2,挂载点都是2

centos7: / inode 64

shred:shred -zvun 10 : 清空文件内容

软链接和硬链接区别
* 本质不同,硬链接是同一个文件,软链接不是同一个文件。
* 删除: 链接-1,软连接失效
* 创建:链接+1,链接不变
* 跨分区,不,可以
* 目录: 不,可以

软连接尽量使用相对路径。是相对你创建连接的相对路径

readlink 创建

file 命令不看具体后缀。

vim 使用/root/f1.swp文件。

(ls,pwd,ifconfig) >>all.log:几个命令的结果一起重定向到指定文件中去。

tr 命令使用

hexdump:查看16进制

cat > f1 :单行重定向

[root@centos7 app]# cat > f1 <<eof
> jfsljfs
> dfsjdfljsdf
> dfsjdlfjsdf
> eof


管道: 将前一个命令的标准输出作为了第二个命令的标准输

|& : 错误和正确都重定向

cmd1 2>&1 |: 错误和真气都重定向

tar -cvf - /home | tar -xvf -:

exec 8<>f1
ls /proc/$$/fd/8
ecec 8>&-

3A
* authentication:认证
* authorization:授权
* audition:审计


opt:运维组

dev:开发组


net user opt 123 /add
net localgroup opt /add

net user opt /del

www.178.linux.com

多行重定向: cat >f1 <<EOF

单行重定向: cat >f1

06-2017-11-15

上节课回顾

本节内容

主组:primary group

附加组:supplementary group

/etc/passwd: name:passwd:uid,gid,gecos:dir:shell

getent passwd root:查看指定用户信息

pwunconv: 将shadow的密码转到/etc/passwd中

pwconv:

重新登陆获取令牌信息。

root uid修改修复
1)菜单项e键盘进入设置 init=/bin/bash selinux=0
2)mount -o rw,remount /
3)vim
4)reboot

chfn : change finger 添加个人信息

chsh: 修改shell,或者usermod

$6:SHA512

$1:MD5

authconfig --passalgo=sha256 --update :更新加密算法

/etc/login.defs:定义登陆相关的配置

openssl rand -base64 30:产生随机数

空密码是可以登陆的。

centos5:可以使用usermod-U让用户无密码登陆,centos6不可以。


net accounts:windows查看账户信息

chage:修改口令有效期

passwd -e zhaojiedi:用户即使过期

chage -d 0 zhaojiedi:用户立即过期

group zhajiedi:查看用户组信息。

newgrp:切换主组

gpasswd:设置组信息,可以设置管理员

groupmems:组成员管理

vipw,vigr:编辑密码和组文件
pwck,grpck:文件检查

useradd -r:系统不会自动给系统用户创建家目录

rpm -qp --scripts a.rpm: 查看对应包的相关脚本

/etc/default/useradd:添加用户默认配置

/etc/skel:新建用户的摹本文件夹

newusers:创建用户根据一个文件。

新加一个文件, 用户名:密码

chpasswd:批量修改用户密码

groups root:查看指定用户组信息。


删除附加组: usermod -G "" zhao

fat格式文件系统不支持权限设置。 不支持所有者设置


chown root: file1 : =chown root:root file1


读写对root没控制的,但是执行对root有影响。

chown -R wang / app: 问题很大。

chmod -R a+X /app : 只给目录权限, 文件不添加。

07-2017-11-17

上节课回顾

本节内容

umask -p: 可以追加到bashrc文件
umake -S

suid:
* suid 只能作用在二进制上, 不能作用在scripts上。
* suid 将使用该程序的所有者的权限。

粘滞位: 即使你有目录的写权限,也无法删除文件, 重命名文件。

sgid:
* 文件, 让用户使用所属组的权限
* 文件夹: 这个目录新建的文件所属组集成目录的所属组

sticky:
* 文件上:用户只能删除自己文件的

chattr: +i:写保护。

chattr:+a:只能追加

chattr:+A:不更新accesstime

tune2fs -l /dev/sda3: 默认挂载选项

setfacl -m u:zhaojiedi:rw file1: file1上添加acl权限

mask:影响除了所有者其他人。

权限判定:
1. 判定所有,返回
1. 判定特定用户,effective权限
1. 判定组,判定特定组 effective权限
1. other

getfacl file1 | setfacl --set-file - f2|将f1的权限复制给f2

rev:abc=>cba

cat:行反转

paste:合并到一行。

08-2017-11-20

上节课回顾

本节内容

diff
patch -b f1 f1_f2.diff : 恢复文件

nmap -v -sP 172.18.0.0/24:查看网段ip

vim /etc/passwd +/^bin : 直接pattern进入

vim -d f1 f2 : 打开2个文件


:wq!:对普通用来来说是,删除文件在创建文件。

:x :保持推出

:r!hostname:将主机名字读入到vim中。

:H:当前屏幕的第一行, 行首
:L:当前屏幕的最后一行,
:M:当前屏幕的中间行。

xp:交换位置

~:大小写插件

J:删除后的换行符号

c$:删除并修改

09-2017-11-22

上节课回顾

正则表达式

.
*
?
[]
[^]
|


^
$
\<
\>
\{n\}
\{m,n\}
\{m,\}
\{,m\}

\1

本节内容

vim技巧

3"tyy:复制3行到t寄存器
tp:复制t寄存器的内容到节目上

vim -b a.binary:
:%!xxd:

ctrl+v:面向块的复制
 ,、、
:set ai :自动对齐
:set si :自动缩进
:set ic :忽略大小写
:set hlsearch:高亮搜索
:syntax on :开启语法
:set list :显示回车和tab键
:set ff=unix,ff=dos:设置文档格式
:set parse: 设置复制保留格式
:set cul : 设置光标所在行
:help option-list:获取帮助
:set all :获取帮助
bash编程 ::

unset:清空变量设置 $$:当前进程ide $PPID:当前进程的父 pstree -p:查看进程树

export:生成环境变量 declere -x:生成环境变 $SHLVL:查看shell的级别

$_:上一个命令的最后一个参数

declare -r :只读变量 (umask=066 touch a.txt):指定环境下创建一个文件

$*:全部参数何为一个字符串 $@:每个参数都是一个独立的字符串

shift:清空一个位置变量

10-2017-11-24

上节课回顾

本节内容

[]里面的测试都需要加个""。
=~使用扩展的表达式

双中括号里面才支持扩展正则表达式
==支持不支持正则, 支持glob

[ -v  var1 ]: 测试变量是否没有赋值

()是一个子进程执行
{}是一个函数执行

-r:实际的上是否有读取权限


read 没有设置,存放在REPLY中

echo $-: himBH

read -s:隐藏输入
read -n:只能输入指定字符数量

-samefile : 相同文件, 也就是硬链接的文件


$-:
    h: hash
    i:  交互模式
    m: job监控
    B: 大括号扩展
    H: 历史可用

11-2017-11-27

上节课回顾

本节内容

::
find -name “*.conf” -ok cp {} {}.bak ;

解压缩

file-rolla
zip -r 压缩文件夹

打包

-j:bz2
-J: xz
-z: gzip
-T:filelist

分割

split

sed

i,d,a,s,c,w
;可以多个命令顺序执行
P:
h:模式空间到保留空间
H:
g:
G:
x:互换
n:读取下一行覆盖模式空间
N:读取下一行追加模式空间
d:删除模式空间
D:删除第一个换行符号文本, 不读取继续循环

源码包

12-2017-11-29

上节课回顾

本节内容

分包

tool
tool-devel
tool-utils
tool-libs

管理工具

yum
apt-get
zypper
dnf

rpm重要的几个参数

-i 安装
-v 提示信息
-h 进度信息
-q 查询
-f 指定文件
-p 指定rpm全路径
-i 获取包的详细信息
--test 测试
--nosignature 不检查来源合法性
--nodigest 不检查完整性
--noscripts 不执行程序的包脚本
--nodeps 不考虑依赖性
--replacepkgs 替换包
--replacefiles 替换文件
--force 强制
--oldpackagekk 安装老版本的
--whatprovides 查询特定功能由那个包提供
--whatrequires 查询特定功能能由那些包依赖
--privides 查询包提供的功能
--import 导入公钥
-U 更新
-F 升级
-V 验证包提供的文件变换情况
-K 验证包
--script 脚本
--allmatches 所有匹配的

rpm包检查符号描述

-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

rpm

rpm2cpio a.rpm | cpio -id

数据库: /var/lib/rpm
epel : extra packages for enterprise linux

rpm搜索:
    http://pkgs.org
    http://rpmfind.org


rpm2cpio file.rpm |cpio -id ./file2

rpm -qa :查看所有包

rpm -qf :查询文件来自那个包

rpm -qlp : 包全名

--whatprovides : 那个包提供
--whatrequires : 被那个包依赖

--privides : 可以用命令

-R : 查询依赖那些包
--script : 查看相关的脚本

YUM

cachedir:
keepcache:
gpgcheck:
history:
repolist:

system stop firewalld system disable firewalld

chkconfig iptables off service iptables stop

13-2017-12-01

上节课回顾

etc作为配置文件

软件安装方式

  • rpm
  • yum
  • source
  • 直接那别人编译好的

本节内容

单位

MB: bytes
Mb: bit
rpm: rotations per minute
  • HDD
  • SSD

设备文件

/dev/vd:虚拟文件
gnome-disk:查看磁盘信息
palimpsest:查看磁盘信息

zbr:zoned bit recording

CHS:24位,cylinder,head,sector

LBA:48位,128PB 分区

MBR:0磁盘0扇区
446 :boot loader
64 : 分区表
2   : 55AA

硬盘存储术语

head :
track:
cylinder:
sector:

查看分区

ls /dev/sd*
cat /proc/partitions
lsblk
fdisk -l /dev/sdb

parted命令

添加了分区:partx -a /dev/dev/sda
删除了分区:partx -d --nr 6-7 /dev/sda

partprobe:centos7,centos5都可以

文件系统

ext2不支持日志

修复文件系统不能挂载状态中。

常见的文件系统

linux: ext2,ext3,ext4,xfs,btrfs,reiserfs,jfs
光盘: iso9660
window:fat32,vsfat,ntfs
unix : FFS,UFS,JFS2
网络文件系统:NFS,CIFS
集群文件系统:GFS2,OCFS2
分布式文件系统:FASTDFSceph ,glusterfs
RAW:裸设备

14-2017-12-04

上节课回顾

本节内容

::

lsof: fuser:查看用户使用挂载点信息 findmnt:查看指定目录是不是挂载点 cat /proc/mounts:查看挂载信息 mount dir1 dir2 –bind: 挂载指定目录

dd 创建一个大文件 mkfs.ext4创建文件系统 mount挂载 -o

losetup /dev/loop8 /app/partfile2 /etc/grub/grub.conf max_loop=100

/etc/fstab 后面的2个参数都要设置0 0

spwpon -s cat /proc/swaps pri=10

eject 弹出光驱

cp /dev/cdrom /root/centos7.iso mkisofs -r -o /app/etc/etc.iso /etc

sync:同步磁盘

dd conv=notrunc findmnt: 查找是不是挂载点

15-2017-12-06

上节课回顾

本节内容

resize2fs /dev/md0

逻辑卷

扩展方便
lvcconvert --merge /dev/vg0/lv0-snapshot

网络

应用层
表示层
会话层
传输层
网络层
数据链路层
物理层

iso:国际标准化组织,光盘格式
osi网络标准协议,开发系统互联
ios apple系统

all people seem to need data processing

单播
广播
多播

ieee:国际电子电器协议
mac:media access control

16-2017-12-11

上节课回顾

物理层
链路层
网络层
传输层
会话层
表示层
应用层

PDU : Protocol Data Unit

46-1521

本节内容

冲突监测的载波侦听多路访问CSMA/CD

HUB:多端口的中继器,带宽共享

单工:单向传递
双工:可以同时说
半双工:不能同时说, 轮流说

网桥和交换机: 隔断冲突域
路由器:路由表,屏蔽广播

冲突域
广播域

trunk 口
vlan : 灵活配置。

tcp/ip协议栈

应用层
传输层
internet层
网络访问层
https:443
mysql:3306
mssqlserver:
pop:110
imap:143

01-1023:系统端口
1024-49151:注册端口
49152-65535:动态端口


/proc/sys/net/ipv4/tcp_max_orphans
/proc/sys/net/ipv4/tcp_fin_timeout
/proc/sys/net/ipv4/tcp_retries1
/proc/sys/net/ipv4/tcp_retries2
/proc/sys/net/ipv4/icmp_echo_ignore_all

ttl:time to live

/proc/sys/net/ipv4/ip_default_ttl

arp:address resolutinon protocol ip->mac



urg:是否有紧急数据
ack:前面的确认号字段是否有效
psh:提示接收端应用程序应该立即从tcp接受缓冲区读走数据
rst:rst=1说明和主机有严重的错误,
syn:用来同步序号
fin:表示通知对方本地端要关闭连接了。



pdu:protocol data unit 协议数据单元对等层次的数据单位

物理层PDU:BIT
链路层PD:FRAME
网络层pdu:packet
传输层pdu:SEGMENT
应用层PDU:MESSAGE

repeater中继器

icmp:1
tcp:6
udp:17

17-2017-12-12

上节课回顾

本节内容

::
无类域间路由, 网络ID不按照整8位划分

18-2017-12-14

上节课回顾

主机数量计算
划分子网的网段数量计算
网络id计算
CIDR计算

超网的合并方式

dhcp
    discover
    offer
    request
    ack

ip addr ,link
ifconfig
route -n
ip neigh

rip
ospf
bgp
eigrp

本节内容

chkconfig NetworkManager off
service NetworkManager stop

MACADDR
HWADDR
DOMAIN


修改dns和host文件的优先级
nsswitch

nmtui
nmcli
nm:NetworkManager

网卡别名不支持动态获取

mtr
traceroute
tracepath

/usr/share/doc/initscripts-9.49.39/sysconfig.txt

19-2017-12-05

上节课回顾

::
ftp lftp lftpget wget links traceroute tracepath mtr host dig nslookup lsmod rmmod modprobe ethtool hostnamectl hostname

本节内容

mmu:memory management unit :逻辑地址和物理地址的转化

tlb:translation lookaside buffer;翻译后备缓冲器

ipc:inter process communication 进程间通信

signal,shm,semaphore,socket,rpc,mq
daemon守护进程
进程和线程的区别

pstree -ps 1400
pstree -ps $$

nice
renice

pidof
pgrep
uptime 超过cpu个数, 就认为cpu的负载比较大
pmap
glance
kill 0

jobs
bg
fg
nohup

进程的基本: 创建,就绪,阻塞,运行,终止
进程控制块: pcb process control block

进程优先级: 0-139 (centos4,5),0-98,99cenos6
实时优先级:99-0:数值越大优先级越高

system优先级
realtiem优先级
nice优先级
top(pr)

进程内存分配的单位是Page Frame页框
LRU:Least recently used
MMU:memory management unit
TLB:translation lookaside buffer翻译后备缓冲器,确保虚拟地址和物理地址的关系映射

IPC:进程间通信, inter process communication
同一个主机: 共享内存,信号,信号量semaphore
不同主机: 消息队列,rpc,socket

进程状态:
         运行
         就绪
         可中断睡眠
         不可中断睡眠
         停止
         僵死

 进程类型:
         守护进程
         前台进程
         后台进程

19-2017-12-05

上节课回顾

本节内容

at:suid的
删除at:rm -rf /var/spool/a*

corn:cornie
cornie-anacron:补充包
corntabs:系统维护

at.allow优先级最高。
at.deny

allow,deny都存在: 只有allow里面的用户才能使用
allow只有: 只有allow里面的用户才能使用
deny:只有deny不能使用,其他的都能使用
allow,deny都不存在:都不能访问的。

21-2017-12-20

上节课回顾

本节内容

::

while unitl post:power-on-self-test

ntsysv chkconfig 默认是2345

22-2017-12-22

上节课回顾

本节内容

::

PS1 PS2 PS3 PS4

declare -f f_name

rpm -ivh kernel.rpm –force –root=/sys/sysimage

chrooot /sys/sysimage grub-install /dev/sda

23-2017-12-25

上节课回顾

本节内容

::

${#var} ${var:offset:length} ${var: -length}

${var#*str} ${var##*str} readonly =declare -r

eval

title=ceo ceo=mage echo ${!title}

mktemp

install

expect -c ‘expect “n” {send “pressed entern”}’

640*480

/proc/cmdline

24-2017-12-27

上节课回顾

本节内容

sysctl -w parameter=val
sysctl -p parameter=val
sysctl -a

net.ipv4.ip_forward
net.ipv4.icmp_echo_ignore_all
vm.drop_caches

设备文件
/etc/udev/rules.d
/usr/lib/udev/rules.d

dac:
mac:

OFS
FS
RS
ORS
NF
NR
FNR
FILENAME
ARGC
ARGV

08-2017-11-20

08-2017-11-20

08-2017-11-20

03-2017-11-08

08-2017-11-20

05-2017-11-13

06-2017-11-15

07-2017-11-17

08-2017-11-20

09-2017-11-22

10-2017-11-24

11-2017-11-27

12-2017-11-29

13-2017-12-01

14-2017-12-04

15-2017-12-06

16-2017-12-11

17-2017-12-12

18-2017-12-14

19-2017-12-05

19-2017-12-05

21-2017-12-20

22-2017-12-22

23-2017-12-25

24-2017-12-27

博客作业

11月博客作业

12月博客作业

1月博客作业

3月博客作业

4月博客作业

11月博客作业

12月博客作业

1月博客作业

2月博客作业

3月博客作业

4月博客作业