欢迎查看zhaojiedi1992的linux学习笔记

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

基础类

LINUX简介

操作系统与硬件

分层结构如下:

  • 硬件

  • 内核

  • 应用程序

终端的概念

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

分类:

物理终端

本机自带的,显示器,键盘和鼠标等,表示为”/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

命令提示符

“[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自带。

外部命令

某路径下的可执行程序文件。

查看命令类型

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

文件系统

文件系统特性

  • 文件名区分大小写

  • 文件名除了’/’的任意字符都可以,不建议特殊字符

  • 文件名长度不能超过255字符

  • 所有’.’开头的文件都是隐藏文件或者目录

路径分类:

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

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

LINUX命令获取帮助方式

  1. COMMAND –help

  2. man

  3. info

  4. 程序自身的帮助文档,如README,INSTALL,CHANGELOG.

  5. 程序的官方文档

  6. 发行版的官方文档

  7. GOOGLE

基础命令学习

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记录的命令位置
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.
查询命令的所属章节
[root@centos74 test]$ man -f ls
ls (1)               - list directory contents
ls (1p)              - list directory contents
[root@mail user1]# whatis ls
ls (1)               - list directory contents
ls (1p)              - list directory contents
[root@mail user1]# man 1 ls
命令的分类
  1. 用户命令

  2. 系统调用

  3. 库调用

  4. 设备及特殊文件

  5. 配置文件

  6. 游戏

  7. 杂项

  8. 管理命令

man文档的配置文件
  • centos6: “/etc/man.config”

  • centos7: “/etc/man_db.conf”

man手册段落含义
  • name: 命令的名字或简要说明

  • description: 命令功能的详细描述

  • options: 支持的选项

  • sysnopsis: 使用格式

  • examples: 使用样例

  • notes:相关的注意事项

  • files:相关的配置文件

  • see also:相关的参考

练习

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
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:保存上一次目录的路径

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--:权限
.:这个位置有3个值,".","+","-"三个值。
1: 文件被硬连接的次数
root:文件的owner
root:文件的group
154:文件的大小
Sep 25 19:34: 文件最近修改的时间
adduserbat.sh: 文件名字

文件类型有一下几类

  • - 普通文件

  • d 目录文件

  • b 块设备文件

  • c 字符设备文件

  • s socket文件

  • p 管道文件

  • l 连接文件

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)
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:关闭字体功能
which
[root@mail ~]# which ls
alias ls='ls --color=auto'
  /usr/bin/ls
[root@mail ~]# which ls --skip-alias
/usr/bin/ls
whatis
[root@mail ~]# whatis ls
ls (1)               - list directory contents
ls (1p)              - list directory contents

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

LINUX文件系统

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

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

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相关的安全策略等信息

应用程序主要组成部分

  • 二进制程序: /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

LINUX上bash的基础特性(一)

命令历史

环境变量

  • HISTSIZE:命令历史的条数

  • HISTFILE:默认为’~/.bash_history’

  • HISTFILESIZE:HISTFILE文件记录历史的条数

history 常用命令

-d

删除指定的命令

-c

清空命令

-a

手工追加当前会话的命令历史到历史文件中去

调用历史命令

  • !#:重复执行第#条命令

  • !!:重复执行上一条命令

  • !str:执行指定str开头的命令(最后一个)

控制命令历史的记录方式

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

  • ignoredups:忽略重复

  • ignorespace:忽略空白开头

  • ignoreboth:上面2个都启用

命令补全

tab补全

路径补全

tab补全

目录管理类命令

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
tree

用法: tree [option] directory

-d

只显示目录

-L

只显示指定的level级别

-P

只显示匹配指定的路径

命令行展开

~,{},~username

命令的执行结果状态

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

文件查看命令

more

less

head

-n

获取前n行

-c

获取前n个字符

tail

-n

获取后n行

-c

获取后n个字符

-f

动态显示

文件管理

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

递归

LINUX上bash的基础特性(二)

命令别名

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

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

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

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

unalias:撤销别名

glob通配

  • * 代表任意长度的任意字符

  • ?: 表示任意单个字符

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

  • [^]:取反

  • [alnum]:所有字母和数字

  • [:alpha:]:字母

  • [:digit:]:数字

  • [:lower:]:小写字母

  • [:upper:]:大写字母

  • [:punct:]:标点符号

  • [:space:]:空白字符,不是仅仅空格

bash快捷键盘

  • ctrl+L:

  • ctrl+a:

  • ctrl+e:

  • ctrl+u:

  • ctrl+k:

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

文本处理工具

wc
-l

行数

-c

字符数量

-w

单词个数

cut
-d

分割符号

-f

提取

sort
-f

忽略大小写

-k

指定字段排序

-t

分割

-n

数字排序

-u

去重连续的重复

-r

逆序

uniq
-c

显示重复的次数

-d

只显示重复的行

-u

只显示不重复的行

linux用户和组管理

用户分类

  • 系统用户: 1-499(centos6),1-999(centos7)

  • 登陆用户: 500+(centos6),1000+(centos7)

主要配置文件分析

/etc/passwd
name:password:uid:gid:geocos:homedir:shell
[root@centos6 ~]# head -1 /etc/passwd
root:x:0:0:root:/root:/bin/bash
/etc/group
groupname:password:gid:userlist
[root@centos6 ~]# head -1 /etc/group
root:x:0:
/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:::
  • 用户名

  • 加密密码

  • 上次修改的密码

  • 最小使用时间

  • 最大使用时间

  • 密码警告时间

  • 密码禁用期

  • 账户过期日期

  • 保留字段

用户管理命令

useradd
-u

指定用户id

-g

基本组

-G

附加组

-c

注释信息

-s

shell类型

-d

用户的家目录

-r

系统用户

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
su
  • su username: 非登录切换,不会读取目标用户的配置文件

  • su -username:登陆切换,会读取目标用户配置文件,完全切换

usermod
-g

主组

-G

附加组

-u

用户名

-s

shell

-c

注释

-d

家目录

-l

新的登陆名

-L

锁定

-U

解锁

-e

指定过期日期

-f

指定非活动期限

passwd
-l

锁定用户

-u

解锁

-n

最短期限

-x

最大期限

-w

警告期限

-i

非活动期限

--stdin

接受终端输入

userdel
-r

删除用户家目录

groupdel
groupmod
-n

新名字

-g

新的id

gpasswd
-a

添加到指定的组

-d

从指定组删除

-A

设置用户列表

newgrp

用户临时切换基本组

chage
-d

修改用户最近一次修改时间

-I

修改用户的非活动期限

-E

过期日期

sudo

-l

查看用户可以执行的sudo

-k

清除下的令牌时间戳

-u

以指定用户运行命令

配置文件是/etc/sudoers

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

注意事项

  • ALL大写

  • 命令使用全路径

  • 组使用%

  • 别名 User_Alias User1 = magedu,centos,test

Linux上bash的基础特性(三)

编程环境

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:用于定义命令别名和本地变量

算数运算
  • 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
条件测试
  • test expr

  • [ expr ]

  • [[ expr ]]

测试类型
  • -gt

  • -lt

  • -eq

  • -ge

  • -le

  • -ne

字符测试
  • ==

  • >

  • <

  • !=

  • =~

  • -z

  • -n

文件测试
  • -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旧

组合测试
  • &&

  • ||

  • -a

  • -o

  • !

语句控制

if

if expr ; then
    sate
fi

for

for var in [] ; do
    sate
done

grep正则表达式

grep

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

分类:

  • 基本的

  • 扩展的

grep学习笔记

grep语法

--color

高亮显示匹配到字符串

-v

显示不能被匹配的行

-i

忽略大小写

-o

仅仅显示匹配到的

-q

静默模式

-A

后面几行

-B

前面几行

-C

前后几行

-E

启用扩展

基本的正则表达式

字符匹配
.                   任意字符一次
[]                  集合中任一个字符
[^]                 几集合之外任何一个
[:alpha:]           字母
[:alnum:]           字母数字
[:digit:]           数字
[:punct:]           标点符号
[:space:]           空白字符
[:upper:]           大写
[:lower:]           小写
次数匹配
*               多次
\?              0次或者1次
\+              1次或者更多次
\{m\}           精确m次
\{m,n\}         m到n次
\{0,n\}         小于等于n次
\{m,\}          大于等于m次
位置锚定
^           行首锚定
$           行尾锚定
\<          单词头锚定
\>          单词尾锚定
\b          单词边界锚定
分组
\(\)            分组
\1              分组后的后向引用

扩展正则表达式

Linux文件查找

文件的查找分为2种:

  • 实时查找

  • 非实时查找

locate

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

  • centos6 : makewhatis

  • centos7 : mandb

find

8.2.1 find的查找用法
find [选项] [查找路径] [查找条件] [处理动作]
查找条件
-name

名字查找

-iname

文件名字查找,忽略大小写

-user

用户

-group

-gid

组id

-nouser

没有属主

-nogroup

没有属组

组合条件查找
-a

同时满足

-o

满足一个即可

-not

条件取反

文件类型判断

-type 文件类型

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

-size [+|-] #UNIT

#UNIT                   #-1< X <= #
-UNIT                   0<= X < #
+UNIT                   X > #
根据时间戳
  • -atime [+|-] #UNIT

  • -ctime [+|-] #UNIT

  • -mtime [+|-] #UNIT

#UNIT                   #<= X <= #+1
-UNIT                   0<= X < #
+UNIT                   X >= #+1
根据权限

-perm [+|-] MODE

644                     精确匹配权限
+644                    任何一位满足就匹配
-644                    对应位置都满足
处理动作
-print

打印到屏幕

-ls

列出来

-delete

删除查找的文件

-fls

长格式写到指定文件中

-ok

交互的执行后续命令

-exec

执行后续命令

Vim编辑器

Vim有3种模式

  • 编辑模式

  • 输入模式

  • 末行模式

vim学习和练习

模式转化

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

退出文件

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

光标移动

字符间移动
h
l
j
k

单词之间移动
w
e
b

行内移动
^
0
$

句子内移动
(
)

段落内移动
{
}

行间移动
#G
G
gg

Vim的编辑命令

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

Vim可视化模式

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

翻屏操作

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

Vim末行模式

内容定界

startpos,endpos

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

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

修饰符:

  • i 忽略大小写

  • g 全局替换

多文件模式

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

窗口属性设置

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

Linux磁盘管理

设备的分类:

  • 块设备

  • 字符设备

磁盘设备的文件命名

  • IDE /dev/hd

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

centos7及以后没有差异了。都是sd的啦。

机械式硬盘

磁道

每个盘片上被分为N个同心圆,每个同心圆就是一个磁盘。

柱面

相同编号的磁道

扇区

每个磁道512个字节

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

MBR

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

磁盘分区管理命令

fdisk [DEVICE]

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

LINUX文件系统

常用文件系统

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

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

文件系统监测

fsck

-t

指定类型

-a

自动修复错误

-r

交互式修复

e2fs

-y

对问题自动回答yes

-f

强制进行检查

超级块

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

文件系统的挂载

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

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

挂载交互分区

swapon

-a

激活所有的交互分区

-p

指定优先级

文件系统的卸载

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

设备自动开机挂载

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

  1. 挂载的设备

  2. 挂载点

  3. 文件系统类型

  4. 挂载选项

  5. 转储频率

  6. 自检次序

硬链接

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

ln 源文件 目标文件

软连接

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

ln -s 源文件 目标文件

Linux文件系统上的权限

文件系统上的权限是指文件系统上文件和目录的权限,只要针对三种人群。

  • owner 所有者

  • group 所在组

  • other 其他

权限分为三种:

  • r 读取

  • w 写入

  • x 执行

权限表如下:

文件类型

r

w

x

文件

可以查看文件内容

可以写入文件

可以提交内核执行

目录

可以查看目录列表

可以在目录删除和添加文件

可以进入目录

权限表示方法:

字母表示法

二进制法

数值法

000

0

–x

001

1

-w-

010

2

-wx

011

3

r–

100

4

r-x

101

5

rw-

110

6

rwx

111

7

文件权限的修改chmod

修改权限方法有下面几种:

#1 : 直接设置所有权限的
chmod 644 file1
chmod a=rwx,g=rw,o=--- file1
#2 : 添加和去除权限的
chmod a+x file1
chmod o-x file1

可以指定”-R”选项来递归设置下。

文件所有者的修改chown

chown的使用案例

# 修改属主和属组
chown mysql.mysql file.txt
# 修改属主
chown mysql file.txt
# 修改属组
chown .mysql file.txt
# 修改属组
chgrp mysql file.txt

Note

文件的属主和属组仅root可以修改。

umask

遮罩码用于设置创建一个新的文件或者目录时候的默认权限。

  • file: 666-umask

  • dir: 777-umask

Note

如果相减只有还有x权限,就再对应权限为加1。

更详细的umask参考

umask查看和修改

[root@centos-155 ~]# umask
0022
[root@centos-155 ~]# umask 0002
[root@centos-155 ~]# umask
0002
[root@centos-155 ~]# umask 0022
[root@centos-155 ~]# umask
0022

特殊权限

在linux文件系统上,有是三个特殊权限,suid,sgid,sticky。

安全上下文:

前提条件: 进程有属主和属组,文件有属主和属组。

  1. 任何一个可执行程序文件能不能启动为进程,取决于发起者对程序文件是否有执行权限。

  2. 启动为进程之后,其进程的属主为发起者,进程的属组为发起者所属组。

  3. 进程访问文件时候的权限,取决于进程的发起者。

  4. 进程的发起者同文件的属主,则应用文件的属主权限。

  5. 进程的发起者同文件的属组,则应用文件的属组权限。

  6. 应用文件其他位权限。

suid

前提: 此类文件有可执行权限的命令

  1. 任何一个可执行程序文件能不能启动为进程,取决于发起者对程序文件是否拥有执行权限。

  2. 启动为进程之后,其进程的属主为原有程序文件的属主

这个地方有点绕,给大家举个示例吧,如果一个程序文件passwd,属主root,属组root,且属主、 属组和其他人都有执行权限,且还有suid权限,那么zhao用户来执行这个命令的时候,对zhao来说 有执行权限,但是passwd这个进程起来的时候,进程的属主是root,而不是zhao。

权限设定和查看

[root@centos-155 bin]# cd /usr/bin                      # 进入bin目录
[root@centos-155 bin]# ls -l vim                        # 查看默认权限信息
-rwxr-xr-x. 1 root root 2289640 Aug  2  2017 vim
[root@centos-155 bin]# chmod u+s vim                    # 添加suid
[root@centos-155 bin]# ls -l vim                        # 查看
-rwsr-xr-x. 1 root root 2289640 Aug  2  2017 vim
[root@centos-155 bin]# chmod a-x vim                    # 去除执行权限
[root@centos-155 bin]# ls -l vim                        # 查看
-rwSr--r--. 1 root root 2289640 Aug  2  2017 vim
[root@centos-155 bin]# chmod a+x vim                    # 恢复执行权限
[root@centos-155 bin]# chmod u-s vim                    # 去除suid权限
[root@centos-155 bin]# ls -l vim                        # 查看
-rwxr-xr-x. 1 root root 2289640 Aug  2  2017 vim

通过上面的实验,可以看出来原有属主有执行权限的时候添加suid对应执行权限位为s,如果 原有属主没有执行权限的时候,添加suid对应的执行权限为S。

Warning

suid设置有风险,普通用户可以通过suid权限临时使用属主身份修改重要文件。慎用!

sgid

默认情况下,用户创建文件时候,其属组为此用户所属的基本组。

一旦目录设置了sgid,则对此目录有写权限的用户在此目录创建的文件所属的组为此目录的属组。

权限的设定

chmod g+s dir
chmod g-s dir

Note

这个权限在团队开发中非常有用的, 一个目录,你创建的文件团队其他人没法访问是不是很尴尬。

sticky

对于一个多人可写的目录,如果设置了sticky,则每个用户仅能删除自己创建的文件。

权限的设定

chmod o+t dir
chmod o-t dir

Note

这个权限在团队开发中是非常有用的,防止恶意删除别人的文件。

RAID

raid(redundant arrays of independent disks,raid)廉价磁盘冗余阵列,raid可以透过一个 技术,将多个较小的磁盘整合为一个较大的磁盘装置,完成存储的扩容和数据保护功能。

raid的实现方式

  1. 外接式磁盘阵列,通过扩展卡提供适配能力。

  2. 内接raid,主板集成raid控制器。

  3. software raid,软件方式实现raid功能。

raid级别

  • raid0

  • raid1

  • raid3

  • raid5

  • raid10

  • raid01

常用的raid级别有0,1,5,10和01级别。

软raid的实现

在linux环境下需要使用mdadm这个命令创建软raid。

mdadm主要选项

-C

创建raid

-n

使用的磁盘个数

-l

级别

-a

自动创建目标raid的设置文件

-c

块大小

-x

空闲盘的个数

-D

详细信息

-A

装配模式,重新识别raid

-F

监控模式

-f

标记指定的磁盘为损坏

-a

添加磁盘

-r

移除磁盘

-S

停止软raid

查看命令

[root@centos-155 backup]# cat /proc/mdstat
[root@centos-155 backup]# mdadm -D /dev/md1

LVM

lvm(logical volume manager)逻辑卷管理的重点在于可以弹性的调整能够filesystem的容量,而非在于数据 的存储效率和安全上面。

基础的概念

pv(物理卷)

物理卷是指硬盘分区或从逻辑上与磁盘分区具有同样功能的设备,是lvm的基本存储逻辑块。

vg(卷组)

卷组类似与非lvm系统的物理硬盘,其由物理卷组成,可以创建一个或多个分区。

lv(逻辑卷)

逻辑卷类似非lvm系统的系统分区,在逻辑卷上建立文件系统

pv,vg,lv是如何关联的呢。

首先把分散的,大小不同的多个pv整合在一起组成一个vg卷组, 这个卷组的空间是比较大的, 然后在这个大的卷组上面去创建多个lv, 每个lv根据自己的需求大小去创建,不用管底层数据存储在那个pv上,那个磁盘上。

lvm的实现

创建pv

pv是逻辑卷管理的底层元素, 这个是基础,相关的命令也比较多。

pvcreate    创建实体pratition为pv
pvscan      搜索系统里面具有的pv资源
pvdisplay   显示目前系统的pv状态
pvremove    将pv属性移除
创建vg

vg相关的命令

vgcreate    创建vg的
vgscan      扫描系统的vg
vgdisplay   显示目前系统上面的vg信息
vgextend    在vg内添加额外的pv
vgreduce    在vg内移除pv
vgchang     配置vg是否启动
vgremove    删除一个vg
创建lv

lv相关的命令

lvcreate    创建lv
lvscan      扫描系统lv
lvdisplay   显示系统lv状态嘻嘻你
lvextend    扩展lv
lvreduce    缩减lv
lvremove    移除lv
lvresize    对lv进行大小调整
扩容lv
  1. 使用fdisk创建新分区(具有8e)

  2. pvcreate创建pv

  3. vgextend将新的pv加入到vg中

  4. lvresize 调整要扩展的大小

  5. 使用resize2fs来将文件系统的容量调整和lv同步。

Note

如果原有的vg空间足够大的话,前三步可以跳过。

缩减lv
  1. 先卸载已经挂载的lv

  2. 强制磁盘检查(e2fsck -f )

  3. resitefs来调整文件系统大小

  4. lvreduce来调整lv大小

  5. mount

快照

快照是当时的系统数据记录下来,在未来如果有数据变动,则会将变更前的数据放到快照去进行保存起来。 利用快照功能,可以轻松的完成长时间的备份工作,且保证数据是在同一个时刻状态下的。

创建快照和创建lv基本一样的, 只需要加入特性的选项-s 即可。 挂载的时候加入 ro选项即可。

Btrfs文件系统

解压缩

linux下有几种压缩工具

  • gzip

  • bzip

  • xz

  • zip

gzip的使用

gzip的主要选项

-d

解压缩,相当于gunzip

-c

将压缩的输出流到特定位置

-r

递归至目录对每个文件进行压缩

-n

指定压缩级别,范围1-9,默认是6

bzip的使用

bzip的主要选项

-d

解压缩,相当于bunzip2

-k

压缩后保留原文件

-n

指定压缩比

xz的使用

xz的主要选项

-d

解压缩,相当于bunzip2

-k

压缩后保留原文件

-n

指定压缩比

zip的使用

zip可以将多个文件压缩成单个文件

归档工具

tar
-c

创建归档

-v

提示信息

-f

指定压缩目标位置

-z

使用gzip压缩

-j

使用bzip压缩

-J

使用xz压缩

Linux系统程序包管理

linux环境下有2种软件管理软件,分别是rpm和dpkg。

发行版代表

软件管理机制

使用命令

线上升级机制

Red Hat/Fedora

RPM

rpm,rpmbuild

yum

Debian/Ubuntu

DPKG

dpkg

apt-get

rpm包格式

样例: ftp-0.17-54.el6.x86_64.rpm

ftp             软件名称
0.17            软件版本
54              编译次数
el6             红帽企业6
x86_64          适合的硬件平台,有i386,i586,i686,x_86_6,noarch
.rpm            rpm的扩展名

rpm的优点

  1. rpm内部宝航已经编译过程序和配置等数据,可以让用户免去重新编译的困扰。

  2. rpm在被安装之前,会自动检查磁盘容量,操作系统环境,避免错误安装。

  3. rpm文件本身提供软件信息,依赖性软件,方便用户了解软件信息

  4. 便于升级、移除、查询和验证工作。

rpm包管理

安装

安装相关的选项

-h

以#来表示安装的进度

-v

显示安装过程的详细信息

-vvv

更详细的信息

--test

不执行真正的安装,只是测试下

--nodeps

忽略依赖关系,可能安装成功,但是没法使用

--replacepkgs

覆盖安装

--force

强制安装

升级

升级相关的选项

--oldpackage

降级到旧版本

-U

升级或者安装

-F

升级

卸载

卸载相关的选项

-e

卸载

--allmatches

如果一个安装包安装多个版本,就都卸载

查询

查询相关选项

-q

查询

-a

所有包

-f

查询文件有那个包安装的

-i

查询安装的包信息

-l

列出包安装提供的文件列表

-c

列出安装的配置文件

-d

列出安装的帮助文档信息

--changlog

列出版本变化信息

--provides

列出包提供的能力,能使用的命令

--requires

查询包依赖于那个包

--scripts

查询包安装前和安装后脚本,preinstall,preuninstall,postinstall,postuninstall

校验

校验包使用-V选项

S size          文件大小被修改了
M mode          文件的类型或者属性被修改了。
5 md5           文件的指纹信息不同了
D device        文件的主设备号变了
L link          文件link路径变化了
U user          所有者变了
G group         所属组变了
T time          创建时间变了
P capabilities 提供能力变化
额外选项
-K

验证包

--nosignature

不检查包来源合法性

--nodigest

不检查完整性

--initdb

初始化数据库

--rebuliddb

重建数据库

yum

yum是通过分析rpmde 标头信息,根据各个软件的依赖关系制作出有依赖关系的解决方案, 然后可以自动处理软件的依赖问题,以解决软件安装或移除与升级的问题。

yum的配置

yum的配置需要配置到/etc/yum.repo.d目录下,且以repo作为后缀。 主要片段

[repoid]        仓库名字,全局唯一的
name            仓库名字
url             仓库的地址,支持ftp,http,file三种协议
enabled         是否启用
gpgcheck        是否包校验
gpgkey          gpgkey文件路径
cost            代价,默认1000,越小越优先

yum命令

子命令

功能

样例

install

安装包

yum install tree

update

更新包

yum update tree

downgrade

降级

yum downgrade tree

check-update

检查那些升级可用

yum check-update

remove

移除包

yum remove tree

list

列出包

yum list all |grep tree

info

查看包详细信息

yum info tree

provides

查看包提供信息

yum provides tree

clean

清空特定缓存

yum clean all

makecache

制作缓存

yum makecache

groupinstall

包组安装

yum groupinstall ‘development tools’

grouplist

包组列表

yum grouplist ‘development tools’

groupremove

包组卸载

yum groupremvoe ‘development tools’

groupinfo

包组详细信息

yum groupinfo ‘development tools’

search

搜索相关包

yum search top

localinstall

本地安装

yum localinstall tree*.rpm

reinstall

重新安装包

yum reinstall tree -f

deplist

查看包依赖列表

yum deplist tree

repolist

查看仓库列表

yum repolist

history

安装历史

yum histrory

yum history 这个是个比较好用的工具,支持redo和undo的。

样例:

[root@centos-155 backup]# yum history
Loaded plugins: fastestmirror
ID     | Command line             | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    39 | install mdadm            | 2018-02-10 17:34 | Install        |    2
    38 | install MariaDB-server M | 2018-02-08 18:55 | I, O           |    5 EE
    37 | remove mysql             | 2018-02-08 18:50 | Erase          |    2 EE
    36 | install mariadb-server   | 2018-02-06 15:38 | Install        |    4
    35 | install libsemanage-pyth | 2018-02-06 14:47 | Install        |    1
    34 | install libselinux-stati | 2018-02-06 14:45 | Install        |    4
    33 | install cifs-utils       | 2018-02-06 10:14 | Install        |    1
    32 | install samba-client     | 2018-02-06 09:39 | Install        |    3
    31 | install samba            | 2018-02-06 09:37 | Install        |   14
    30 | install nfs-utils        | 2018-02-04 18:18 | Install        |   16
    29 | install bind bind-utils  | 2018-01-21 03:10 | Install        |    1
    28 | remove bind              | 2018-01-21 01:42 | Erase          |    1 EE
    27 | install psmisc           | 2018-01-20 13:29 | Install        |    1
    26 | install wget             | 2018-01-20 11:12 | Install        |    1
    25 | remove Maria*            | 2018-01-20 10:59 | Erase          |    6 EE
    24 | install mariadb-server   | 2018-01-20 10:22 | Install        |    2
    23 | remove MariaDB-server Ma | 2018-01-20 09:47 | Erase          |    2
    22 | install MariaDB-server M | 2018-01-20 09:32 | I, O           |   10 EE
    21 | reinstall mariadb-server | 2018-01-19 16:53 | Reinstall      |    2
    20 | install mariadb-server   | 2018-01-19 16:51 | Install        |   10
history list
[root@centos-155 backup]# yum history undo 39

源码编译安装

源码编译大概流程

  1. ./configure –help

  2. ./configure

  3. make && make install

  4. 添加bin目录到path环境变量

  5. 创建软连接到/usr/include下

  6. 在帮助文档配置文件安装的帮助man目录

  7. 额外文件的配置,比如服务文件,默认配置文件等。

Linux系统网络属性管理

ip/netmask 主要用于确定自身所处的网络

gateway 主要用于本主机和其他网络主机通信使用

routey 主要用户建立路由条目,分为三种

  • 网络路由 目标是一个网络范围

  • 主机路由 目标是一个主机ip

  • 默认路由 目标是所有非本地网络

地址管理

查看网络设备
[root@centos-155 backup]# dmesg  |grep eth
[    1.015300] e1000 0000:02:01.0 eth0: (PCI:66MHz:32-bit) 00:0c:29:ad:b0:f2
[    1.015305] e1000 0000:02:01.0 eth0: Intel(R) PRO/1000 Network Connection
[    1.360766] e1000 0000:02:05.0 eth1: (PCI:66MHz:32-bit) 00:0c:29:ad:b0:fc
[    1.360770] e1000 0000:02:05.0 eth1: Intel(R) PRO/1000 Network Connection
[    1.711270] e1000 0000:02:06.0 eth2: (PCI:66MHz:32-bit) 00:0c:29:ad:b0:06
[    1.711273] e1000 0000:02:06.0 eth2: Intel(R) PRO/1000 Network Connection
使用ifconfig设置ip信息
ifconfig ifname ip/netmask up
ifconfig ifname ip/prefix up

Note

通过ifconfig命令配置的ip信息会立即生效,但是不会永久生效的。

使用ip命令来配置网络ip地址参数

ip命令用起来还是比较麻烦的,选项也是特别的多。

ip [options] object {command}
object:
        link: 链接接口
        addr: 管理接口上的地址
        route:管理路由的

link的帮助:

set 设置device接口属性
show 显示接口状态信息

addr的帮助:

add 添加
del 删除
示例: ip addr add 172.18.200.1/16 dev eth0

show 查看所有地址信息
flush 清楚协议地址

route的帮助:

list 列出route信息
add 添加路由
    样例:  ip route add default via 172.18.0.1
           ip route add 172.18.0.0/16 via 172.18.4.4
del 删除路由
    样例: ip route del 192.168.0.0/24
图形界面设置

在centos6下可以使用setup命令来配置ip信息,而centos7下使用更强大的工具nmtui命令。

网络信息的主要配置说明
DEVICE          设备
BOOTPROTO       配置协议, none,static,dhcp
HWADDR          硬件地址
NM_CONTROLLED   是否受到networkManager控制,centos建议设置为no
ONBOOT          开机启动
TYPE            类型,ethernet,team,bound
UUID            设备的uuid
IPADDR          IP 信息
NETMASK         子网掩码
GATEWAY         网关
DNS1            第一个dns
DNS2            第二个dns
USERCTL         是否运行其他用户控制
PREFIX          设置掩码的,cidr格式的
PEERDNS         是否运行dhcp服务器提供的dns服务覆盖本地的dns
配置dns
[root@centos-155 backup]# vim  /etc/resolv.conf
[root@centos-155 backup]# cat /etc/resolv.conf
# Generated by NetworkManager
search DHCP HOST
nameserver 59.108.61.61
nameserver 219.232.48.61

nameserver用于设置dns服务器。

路由管理

动态配置
# 查看路由
[root@centos-155 backup]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.46.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
# 添加主机路由
[root@centos-155 backup]# route add -host 192.168.46.200 gw 192.168.46.1
[root@centos-155 backup]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.46.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
192.168.46.200  192.168.46.1    255.255.255.255 UGH   0      0        0 ens33
# 添加网络路由
[root@centos-155 backup]# route add -net 172.18.0.0/16 gw 192.168.46.1
[root@centos-155 backup]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.18.0.0      192.168.46.1    255.255.0.0     UG    0      0        0 ens33
192.168.46.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
192.168.46.200  192.168.46.1    255.255.255.255 UGH   0      0        0 ens33

# 删除路由
[root@centos-155 backup]# route del -net 172.18.0.0/16  gw 192.168.46.1
[root@centos-155 backup]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.46.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
192.168.46.200  192.168.46.1    255.255.255.255 UGH   0      0        0 ens33

上面我们使用route配置只是理解生效的,开机就会没有的。

静态配置

可以在/etc/syssconfig/network-scripts/route-ifname文件中添加如下记录

192.168.0.0/24 via 172.16.0.2
192.168.1.1 via 172.16.0.3

这样去添加一个网络路由和主机路由开机也是不会丢掉的。

主机名修改

修改主机名方法比较多

  1. hostname

  2. echo “you_host_name” >> /proc/sys/kernel/hostname

  3. 编辑/etc/sysconfig/network和/etc/hosts

  4. hostnamectl命令的(centos7有,centos6没有此命令)

网络管理常用命令

ping

监测目标主机网络是否可以到达,以及网络相关延时信息。

traceroute

监测到达目标主机之间所经过的网络设备

mtr

合并了ping和traceroute命令的诊断工具

网络状态查看工具

netstat

主要选项

-r

显示路由表

-n

数字显示

-t

tcp

-u

udp

-l

监听

-a

显示所有连接

-p

显示进程相关信息

样例:

[root@centos-155 backup]# netstat -tunlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      916/sshd
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      687/rsync
tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd
tcp6       0      0 :::22                   :::*                    LISTEN      916/sshd
tcp6       0      0 :::873                  :::*                    LISTEN      687/rsync
tcp6       0      0 :::3306                 :::*                    LISTEN      1132/mysqld

Note

nestat命令效率低下,推荐使用ss命令

ss

主要选项

-e

扩展信息

-m

显示使用信息

-o

状态

-n

数字显示

-t

tcp

-u

udp

-l

监听

-a

显示所有连接

-p

显示进程相关信息

样例

[root@centos-155 backup]# ss -tunl
Netid  State      Recv-Q Send-Q                                       Local Address:Port                                                      Peer Address:Port
tcp    LISTEN     0      128                                                      *:111                                                                  *:*
tcp    LISTEN     0      128                                                      *:22                                                                   *:*
tcp    LISTEN     0      5                                                        *:873                                                                  *:*
tcp    LISTEN     0      128                                                     :::111                                                                 :::*
tcp    LISTEN     0      128                                                     :::22                                                                  :::*
tcp    LISTEN     0      5                                                       :::873                                                                 :::*
tcp    LISTEN     0      80                                                      :::3306                                                                :::*

Linux进程及作业管理

进程通信方法:

同一个主机:

  • signal

  • shm

  • semerphor

不同主机:

  • rpc

进程分类

守护进程

在系统引导过程中启动的进程,和终端无关

前台进程

跟终端有关,通过终端启动的进程

进程的状态

  • 运行态

  • 就绪态

  • 睡眠态

  • 僵死态

  • 停止态

进程管理

ps

用于查看系统当前进程的运行情况

选项和参数

-A

所有进程列出来

-a

和终端无关的所有进程

-u

与用户相关的进程

常用组合方式

  • ps -ef

  • ps aux

  • ps axo

样例:

[root@centos-155 backup]# ps aux  |head -n 3
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          1  0.0  0.3 125340  3872 ?        Ss   Feb10   0:00 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
root          2  0.0  0.0      0     0 ?        S    Feb10   0:00 [kthreadd]

user: 用户
pid: 进程id
%cpu: cpu占比
%mem: 内存占比
vsz: 虚拟内存大小
rss: 固定内存大小
tty: 终端
stat: 状态
    R: 运行
    S:可中断睡眠
    D:不可终端睡眠
    T:停止
    Z:僵死
    s:进程领导者
    +:前台进程
    l:多线程
    <:高优先级
    N:低优先级进程
start time: 启动时间
command: 命令
pgrep

选项

-U

仅仅显示特定用户运行的进程

-G

仅仅显示特定用户组运行的进程

-l

显示pid和进程名字

top

ps是相对一个时间点的进程信息,有时候我们需要动态去观察进程状态,就需要top命令了

选项:

-b

批次处理

-n

显示的次数

-d

指定延迟的时间,单位秒

_images/top.png
第一行:
        当前时间
        系统启动时间
        已经登陆的用户数
        系统在1,5,15分钟的负载情况

第二行:
        任务的总个数
        运行个数
        睡眠个数
        停止个数
        僵死个数

第三行:
        us:用户空间cpu占比
        sy:系统空间cpu占比
        ni:改变优先级的cpu占比
        id:系统空闲cpu占比
        wa:等待io的cpu占比
        hi:硬件中断的cpu占比
        si:软件终端的cpu占比

第四行:
        total:物理内存总量
        free:物理内存空闲大小
        userd:物理内存的使用量
        buff/cache: 物理内存的buffercache大小

第五行:
        totol:交换内存的总大小
        free:交换分区的空闲大小
        userd: 交换内存的使用大小
        avail: 可用内存

命令有:
        P:cpu排序
        M: 内存排序
        T: cpu时间片总占用排序
        q: 退出
        k: 终止特定进程

表头行:
        PID: 进程id
        USER:用户所属组
        PR:进程优先级
        NI:nice值
        VIRT:进程需要的虚拟内存大小
        RES:进程当前使用的内存大小,不包括swap
        SHR:进程和其他进程共享的内存大小
        S:进程的状态
        %CPU:cpu占比
        %MEM:内存占比
        TIME+:cpu使用时间累计
htop

htop是top的增强版本,系统默认是没有安装,在epel源中。

vmstat
[root@centos-155 backup]# vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
2  0      0 495732  15588 292884    0    0    11    20   97  124  0  0 100  0  0

procs:
        r: 等待运行的进程个数(队列的长度)
        b: 处理不可中断睡眠状态进程个数(io阻塞队列长度)

memory:
        free: 空闲空间大小
        buff: 缓冲空间大小
        cache:缓存空间大小

swap:
        si: 从swap进入系统的速率
        so: 从系统出去到swap的速率
io:
        bi: 从磁盘到系统的速率
        bo:从系统到磁盘的速率

system:
        in: 中断速率
        cs: 进程切换速率

cpu:
        us: 用户空间cpu占比
        sy: 系统空间cpu占比
        id: 空闲cpu占比
        wa: 等待iocpu占比
        st:  被偷走的cpu占比
glances

glances是一款开源命令行系统监控空间,他使用python语言开发,能够监视cpu、负载、内存、 磁盘、网络流量、系统温度等信息。

安装

yum install glances

glances的使用

glances是分客户端和服务端的,

# 服务端执行
glances -s
# 客户端执行
glance -c service-ip
dstat

dstat是一个可以拒贷vmstat,iostart,netstat和ifstat这些命令的多功能产品。

常用选项

--top-cpu

显示最占用cpu的进程

--top-bio

显示最占用block io的进程

--top-io

显示最占用io的进程

--top-mem

显示最占用内存的进程

--ipc

显示进程间通信速率

--raw

显示raw套接的相关信息

--tcp

显示tcp套接字相关的数据

--udp

显示udp套接字相关的数据

--unix

显示unixsock接口相关的统计数据

--socket

显示socket信息

kill

进程的管理就是给进程发送特定的信息,来完成对进程的管理控制。

查看信号

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

常用的信号:

全名

简写

数值

描述

SIGHUP

HUP

1

通知进程重读配置文件

SIGINT

INT

2

打断正在运行的进程,相当于ctrl+c

SIGKILL

KILL

9

强行中止正在运行的进程

SIGTERM

TERM

15

安全中止正在运行的进程

SIGSTOP

STOP

19

暂停进程

SIGCONT

CONT

18

继续运行指定的进程

发送信号样例

[root@centos-155 backup]# kill -9 3110

作业管理

作业的查看
[root@centos-155 backup]# jobs
[1]+  Stopped                 vim a.txt
作业控制
  • fg jobid 把特定的作业调回到前台

  • bg jobid 把调往后台的指定的作业启动起来

  • kill jobid 终止特定作业

Linux任务计划

计划任务的分类:

  • 一次性的

  • 周期性的

at

at是由atd服务提供的。

at的主要选项

-l 列出目前系统上面的当前用户的at队列 -d 取消一个在at排程的工作。 -v 可以使用明显的时间格式流出at的工作列表 -f 把at要执行的所有任务放置于文件中,让at读取此文件作为要运行的任务。 -c 用于查看特定job的详细信息

time的几种格式

HH:MM
HH:MM YYYY-MM-DD
HH:MM MONTH DATE
HH:MM + number [minutes|hour|days|weeks]
[root@centos-155 ~]# at 10:30
at> date
at>
at> <EOT>
job 1 at Sun Feb 11 10:30:00 2018
Can't open /var/run/atd.pid to signal atd. No atd running?
# 上面的这一句提示我们没有开启atd服务的
[root@centos-155 ~]# systemctl start atd
[root@centos-155 ~]# systemctl enable atd
# 查看
[root@centos-155 ~]# at -l
1   Sun Feb 11 10:30:00 2018 a root
# 查看job1的详细信息
[root@centos-155 ~]# at -c 1
# 删除job1
[root@centos-155 ~]# at -d 1
# 再次查看
[root@centos-155 ~]# at -l

Note

at的命令输入需要ctrl+d结束。

crontab

crontab是由crond服务提供的。

cron任务分为2种

系统cron

系统级别的例行性任务计划

用户cron

用户自定义的例行性任务计划

系统配置文件格式

[root@centos-155 ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59) 分钟
# |  .------------- hour (0 - 23)   小时
# |  |  .---------- day of month (1 - 31) 天
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 月
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat 星期
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

时间表示法 :

17 表示单独的时间点
*/3 表示每3(时间单位)
3-5 表示3-5这个区间
2,4,5 表示几个离散的时间点

crontab命令

-l

列出已经定义的所有任务

-e

打开编辑界面定义任务

-r

移除所有任务

anacron

anacron主要解决因断电或者关机原因导致的任务没有执行问题。anacron是一个程序,而非一个服务。

服务类

Centos系统启动流程与Grub

系统启动流程

  1. 加点自检,由bios程序实现,这个程序是固化在硬件里面的。

  2. 选择启动顺序,加载mbr,其中启动顺序的管理由boot loader提供。

  3. 加载系统内核kernel,执行系统初始化信息。

  4. 启动用户空间的第一个执行程序/sbin/init

init的配置文件

centos5: 采用sysv方式

centos6: 采用upstart方式

centos7: 采用systemd方式,启动非常快

init的主要级别

0  关机
1  单用户
2  多用户,没有nfs
3  多用户,文本界面
4  备用
5  图形界面
6  重启

init的处理流程

  1. 获取默认level

  2. 使用/etc/rc.d/rc.sysinit初始化

  3. 读取对应levle下的服务 /etc/rc.d/rc{level}.d目录下的服务

  4. 配置ctrl + alt + del 功能件

  5. 配置不断电系统pf和pr两种机制

  6. 启动mintty6个终端

  7. 如果是5级别,就启动图形界面

sysinit的处理流程

  1. 设置主机名字

  2. 打印欢迎信息

  3. 激活selinux和udev

  4. 挂载/etc/fstab定义的文件系统

  5. 挂载swap设备

  6. 重新读写挂载根文件系统

  7. 设置系统时钟

  8. 根据/etc/sysctl.conf文件设置内核参数

  9. 激活lvm和raid

  10. 加载额外的驱动设备

  11. 清理工作

grub

grub运行阶段

linux将bootloader的程序运行和配置项分成三个阶段来运行。

stage1:

运行bootloader主程序,这个程序必须要被安装在启动区,也就是mbr中。因为空间有限,因此mbr当中 仅仅安装bootloader的最小主程序,并没有安装bootloader的相关配置文件

stage1_5:

在mbr随后的扇区中存放,主要用于与stage2所在分区的文件系统进行交互。

stage2:

通过bootloader加载所有配置文件及其相关的环境参数信息,这些配置文件及其相关的环境参数都放在磁盘分区的 /boot目录下。

grub.conf文件
[root@centos6 ~]$ cat /etc/grub.conf
default=0
timeout=5
title centos6.9
kernel /vmlinuz-2.6.32-696.el6.x86_64 root=/dev/sda2
initrd /initramfs-2.6.32-696.el6.x86_64.img

主要配置项

(hd0,0)                     表示第一个磁盘的第一个分区
default=0                   表示默认是的启动条目
timeout=5                   选择等待时间
splashimage                 背景图片
hiddenmenu                  启动是否显示菜单
title                       定义各个操作系统的菜单
root                        定义内核文件存放的位置
kernel                          内核的名称一些启动的核心参数
initrd                      虚拟的根文件系统
password                    保护作用

Linux Kernel

kernel是操作系统的核心,掌控着所有硬件设备的控制权。

linux系统是单内核,模块化体系。

uname的使用

[root@centos6 ~]$ uname -a
Linux centos6.linuxpanda.tech 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 ~]$ uname -n
centos6.linuxpanda.tech

内核模块管理

查看模块
# 方法1:
[root@centos6 ~]$ lsmod
Module                  Size  Used by
rfcomm                 71047  4
sco                    17493  2
bridge                 85706  0
bnep                   16370  2
l2cap                  54210  16 rfcomm,bnep
autofs4                27000  3
bnx2fc                 91541  0
#############省去下面的行#################

# 方法2
[root@centos6 ~]$ cat /proc/modules
rfcomm 71047 4 - Live 0xffffffffa0676000
sco 17493 2 - Live 0xffffffffa066c000
bridge 85706 0 - Live 0xffffffffa064e000
bnep 16370 2 - Live 0xffffffffa0646000

# 方法3
[root@centos6 ~]$ modinfo e1000
filename:       /lib/modules/2.6.32-696.el6.x86_64/kernel/drivers/net/e1000/e1000.ko
version:        7.3.21-k8-NAPI
license:        GPL
装载模块
[root@centos6 ~]$ insmod /lib/modules/2.6.32-696.el6.x86_64/kernel/net/bluetooth/bluetooth.ko
[root@centos6 ~]$ modprobe  bluetooth
卸载模块
[root@centos6 ~]$ rmmod /lib/modules/2.6.32-696.el6.x86_64/kernel/net/bluetooth/bluetooth.ko
[root@centos6 ~]$ modprobe -r bluetooth

内核参数

修改内核参数

# 方法1
[root@centos6 ~]$ echo "1" > /proc/sys/net/ipv4/ip_forward
# 方法2
[root@centos6 ~]$ sysctl -w  net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
# 方法3
[root@centos6 ~]$ vim /etc/sysctl.conf
[root@centos6 ~]$ sysctl -p

编译内核

参考

编译内核的情况:

  • 有新的功能需求,如支持虚拟化

  • 原来的内核太过臃肿

  • 升级来提高稳定性

  • 个人定制或专业用途

  • 个人学习

编译内核的步骤

  1. 查看硬件设备信息

  2. 开发环境和源码

  3. 下载并解压源码

  4. 复制系统的默认的编译配置

  5. make menconfig

  6. make -j 4

  7. make modules_install

  8. make install

screen命令

screen可以让执行的命令脱离终端和终端无关。

选项:

-d

将指定的screen作业离线

-r

恢复指定的作业

-S

创建一个作业

-ls

查看作业

使用样例:

# 创建一个test名字的
[root@centos-155 ~]# screen -S test
[detached from 14681.test]
# 使用ctrl + a +d 来离线

# 查看作业
[root@centos-155 ~]# screen -ls
There is a screen on:
    14681.test      (Detached)
1 Socket in /var/run/screen/S-root.
# 恢复特定的作业
[root@centos-155 ~]# screen -r test

文本处理工具之sed,awk

这个地方就不在写了。

sed

my-study-sed

my-study-sed-bak

awk

my-study-gawk

my-study-gawk-bak

grep

my-study-grep

my-study-grep-bak

Openssl

ssl(secure socket layer)安全套接字协议,是一种应用层协议,主要用于传输数据加密, 而openssl是ssl协议的开源实现,是广泛使用的商业及ssl工具。

常见的加密算法和协议

对称加密

对称加密: 加密和加密使用同一个秘钥,依赖于算法和秘钥,但其安全性依赖于秘钥而非算法。

常见对称加密算法:

  • DES

  • 3DES

  • AES

  • Blowfish

  • Twofish

  • IDEA

  • RC6

  • CAST5

对称加密的特点

  1. 加密和解密使用同一秘钥

  2. 将明文分割为固定大小的块,逐个进行加密

  3. 秘钥过多

  4. 密码分发复杂

非对称加密

非对称加密: 采用的是公钥加密方法,需要私钥来解密。公钥可以公开,私钥只能个人使用。

特点:

  • 可以身份认证,私钥加密的,对应公钥才能解密

  • 公钥加密只能私钥解密,私钥加密只能公钥解密。

  • 秘钥长度较大

常要的非对称加密算法:

  • RSA

  • DSA

  • ELGamal

单向加密

只能加密,不能解密。

特点:

  • 定长输出

  • 同样数据,每次结果都一样

  • 不同数据,计算结果不同

  • 雪崩效应,数据修改一点点,结果变换很大

  • 不可逆

常见的单向加密算法

  • MD5

  • SHA1

  • SHA256

  • SHA384

  • SHA512

  • CRC32

用处:

  • 数据完整性校验

  • 系统账号密码校验

秘钥交换

秘钥交互(internet key exchange): 双方通过交互秘钥来实现数据加密解密。

交互方法:

  • 公钥加密

  • DH

一次加密通信过程

发送方:

  1. 使用单向加密算法提取生成数据的特征码

  2. 使用自己的私钥加密特征码放到数据后面

  3. 生成用于对称加密的临时秘钥

  4. 用临时秘钥来加密数据和私钥加密后的特征码

  5. 使用接受方的公钥加密临时秘钥,附加到对称加密后的数据后方

接受方:

  1. 使用自己的私钥解密临时秘钥,获取对称秘钥

  2. 使用对称秘钥解密数据,得到数据和特征码的密文

  3. 使用发送的公钥来解密特征码的密文,获取特征码

  4. 使用对方同样的单向加密算法来计算数据的特征码和获取到的特征码进行比较

数字证书

ca是一个证书颁发机构,这个机构负责证书的颁发。

ca只是pki(public key infrastructure 公钥基础设施)的一个组成部分。pki包括:

  • 签证机构ca

  • 注册机构ra

  • 证书吊销列表crl

  • 证书存放库

数字证书格式:

  • 版本号

  • 序列号

  • 签名算法标志

  • 发行者的名称

  • 有效期

  • 证书主体名称

  • 证书主体公钥信息

  • 发行商的唯一标示

  • 证书主体的唯一标示

  • 扩展信息

  • 签名(ca对证书的签名)

证书样例:

[root@centos-155 CA]# openssl x509 -in cacert.pem -noout -text
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            98:6c:25:23:b5:0a:bd:8c
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=cn, ST=henan, L=nanyang, O=linuxpanda, OU=opt, CN=ca.linuxpanda.tech
        Validity
            Not Before: Feb 11 11:27:19 2018 GMT
            Not After : Feb  9 11:27:19 2028 GMT
        Subject: C=cn, ST=henan, L=nanyang, O=linuxpanda, OU=opt, CN=ca.linuxpanda.tech
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:da:74:2d:f7:bd:ca:8f:ea:88:c0:f9:c4:1f:be:
                    80:7d:30:7e:ad:2a:dc:25:84:1f:3c:54:82:3a:f3:
                    ed:63:5f:93:5b:84:d1:24:58:32:12:cb:b5:ff:09:
                    07:06:fa:33:96:bf:4e:cf:10:b0:6c:2b:27:52:58:
                    38:76:d5:42:47:9c:cb:fc:f1:72:cf:22:f8:5a:f4:
                    a6:d5:58:b5:99:3f:ec:41:3f:09:63:d8:dd:ec:19:
                    1a:d2:59:f8:cb:7d:36:1d:0e:ef:cf:01:7c:53:49:
                    70:6d:1d:f3:da:44:dd:a0:c4:55:7b:d0:8b:b4:f7:
                    44:a5:29:13:b3:16:f9:8d:c9:0b:65:5c:d8:a1:95:
                    9a:57:95:e0:76:d5:13:a7:7a:46:d0:0e:3f:91:6e:
                    f3:de:ef:0b:b8:19:42:52:48:ea:fb:53:8d:c5:9f:
                    6f:f5:ad:f6:99:85:45:ec:02:1b:57:84:74:c8:16:
                    70:b4:17:c0:a2:80:83:e4:3a:46:07:91:72:45:7b:
                    53:24:b5:fc:d3:a2:a8:28:04:ce:38:e6:e5:0c:3e:
                    21:54:17:7a:40:fe:59:76:71:ab:e2:de:c2:eb:7e:
                    07:5f:8e:46:f5:da:a6:45:d7:cb:73:bf:05:f7:70:
                    5f:ab:e5:0a:0f:20:28:ac:80:75:88:eb:fe:83:77:
                    c6:1f
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                67:61:B2:E8:29:18:2A:CD:80:6C:98:03:3F:80:DF:A4:85:06:A0:69
            X509v3 Authority Key Identifier:
                keyid:67:61:B2:E8:29:18:2A:CD:80:6C:98:03:3F:80:DF:A4:85:06:A0:69

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
        ae:de:c6:64:88:8d:a1:8d:0d:86:8c:b5:ae:5e:20:eb:07:9c:
        dc:c1:68:17:28:f5:7c:e8:fa:c3:2d:24:7b:fe:34:73:fd:0f:
        1a:f6:51:1b:f4:2d:49:03:d3:24:ca:83:ac:8b:7e:df:bf:6c:
        56:f3:0c:76:30:31:76:a2:dd:7a:63:aa:7b:d4:55:49:a2:ae:
        aa:c3:5e:58:71:f7:43:9b:d3:11:4c:d8:1e:29:69:bc:77:b4:
        47:d6:eb:09:15:2b:a2:96:ba:11:1c:ba:c6:1b:ff:ed:02:15:
        3b:17:58:eb:f2:c8:66:c9:ef:02:a8:f0:8b:1a:67:91:07:b5:
        11:67:38:de:22:31:0b:0f:06:3c:14:39:ba:77:08:fe:3d:14:
        2d:ee:3d:5c:46:91:ce:67:10:4d:79:ce:b0:22:cd:81:70:14:
        b9:63:ba:79:23:80:24:0a:1d:18:92:9a:3f:d6:16:63:91:74:
        90:cc:0f:2b:87:ff:d1:22:63:ae:64:3f:eb:a2:94:78:6d:fc:
        3d:17:26:68:e4:88:a3:93:8a:15:10:2d:7c:db:d0:04:2d:89:
        f2:f8:26:aa:a2:b7:b4:74:01:61:dd:a7:15:6c:d7:ba:d9:4d:
        54:e5:df:b5:c1:55:5a:f8:ad:24:b8:89:f2:1f:98:45:4c:d4:
        3a:4f:61:97

ssl

ssl(secure sockets layers 安全套接层) 是为网络通信提供安全及数据完整性的一种安全协议。

tls(translater layer secure 传输层安全) 是ssl的继承版本,与sslzai 传输层对网络连接进行加密。

openssl

openssl是ssl的一个开源项目,由三部分组成。

加密文件

des,3des,aes,blowfish ,twofish,idea,CAST5

单向加密

md5,sha1,

生成用户密码

passwd

生成随机数

rand

样例:

# 加密文件和解密文件
[root@centos-155 ~]# cat /root/test.sh
date
df -h
[root@centos-155 ~]# openssl  enc -e -a -salt -in /root/test.sh  -out /root/test.sh.enc
[root@centos-155 ~]# cat /root/test.sh.enc
ZGF0ZQpkZiAtaAo=
[root@centos-155 ~]# openssl  enc -d -a -salt -out /root/test.sh.dec  -in /root/test.sh.enc
[root@centos-155 ~]# cat /root/test.sh.dec
date
df -h

# 单向加密
[root@centos-155 ~]# openssl dgst  /root/test.sh
MD5(/root/test.sh)= 220f72b1a4e636373d4b9310569cf027

# 生成密码
[root@centos-155 ~]# openssl passwd -1
Password:
Verifying - Password:
$1$QfprG3kQ$WrY4N1mbw4IdQc0uFyvBF/

# 生成随机数
[root@centos-155 ~]# openssl rand 24  -base64  | head -c 8
VnNpgcFj

# 生成公钥和秘钥
VnNpgcFj[root@centos-155 ~]# openssl genrsa -out test 1024
[root@centos-155 ~]# ll test
-rw-r--r-- 1 root root 887 Feb 11 19:16 test
[root@centos-155 ~]# openssl rsa -in test -pubout  -out test.pub
[root@centos-155 ~]# cat test.pub
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9agUiRyfROeBNy2ZPIduxwcwo
mRssh2gMv7I7EIHA/GNKJiW8znjq/uuZDERD699+y9d1C8Q4sh761Za6ec0DU5eP
QcTEuOByi4Dh34B6Ofco00d+30nku8AaXE+vBouE9oL95vJbYz0uCcVNXycZQL42
qYmtfutw/Qnek44a1QIDAQAB
-----END PUBLIC KEY-----

数字证书的获取

自建ca

# 1 生成自己的私钥
[root@centos-155 ~]# (umask 066; openssl genrsa -out /etc/pki/CA/private/cakey.pem 2048)

# 2 给自己颁发证书
[root@centos-155 ~]# openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650

# 3 查看辅助文件
[root@centos-155 ~]# cat /etc/pki/tls/openssl.cnf  |grep dir
dir         = /etc/pki/CA           # Where everything is kept
certs               = $dir/certs            # Where the issued certs are kept
crl_dir             = $dir/crl              # Where the issued crl are kept
database    = $dir/index.txt        # database index file.
new_certs_dir       = $dir/newcerts         # default place for new certs.
certificate = $dir/cacert.pem       # The CA certificate
serial              = $dir/serial           # The current serial number
crlnumber   = $dir/crlnumber        # the current crl number
crl         = $dir/crl.pem          # The current CRL
private_key = $dir/private/cakey.pem# The private key
RANDFILE    = $dir/private/.rand    # private random number file
dir         = ./demoCA              # TSA root directory
serial              = $dir/tsaserial        # The current serial number (mandatory)
signer_cert = $dir/tsacert.pem      # The TSA signing certificate
certs               = $dir/cacert.pem       # Certificate chain to include in reply
signer_key  = $dir/private/tsakey.pem # The TSA private key (optional)

# 4 创建辅助文件
[root@centos-155 ~]# touch /etc/pki/CA/index.txt
[root@centos-155 ~]# echo "01" >> /etc/pki/CA/serial


# 5 节点生成自己的证书请求
[root@centos-155 ~]# (umask 066; openssl genrsa -out test 1024)
[root@centos-155 ~]# openssl req -new -days 365 -key test -out test.csr

# 6 ca颁发证书
[root@centos-155 ~]# openssl ca -in test.csr -out /etc/pki/CA/certs/test.pem -days 300

吊销证书

# 查看吊销证书编号
[root@centos-155 ~]# openssl x509 -in /etc/pki/CA/cacert.pem  -noout  -serial  -subject
serial=986C2523B50ABD8C
subject= /C=cn/ST=henan/L=nanyang/O=linuxpanda/OU=opt/CN=ca.linuxpanda.tech

# 吊销证书
[root@centos-155 ~]# openssl ca -revoke /etc/pki/CA/cacert.pem
# 生成吊销证书编号
[root@centos-155 ~]# echo 01 >> /etc/pki/CA/crlnumber
# 更新证书吊销列表

Nssitch、pam

nsswitch

nsswitch是network service switch的简写,叫做网络服务转换,主要用于调整网络服务 的名称解析机制。

nss的配置文件

nss的配置文件是/etc/nsswitch.conf,格式比较简单。

格式:
    解析库: 解析库类型

样例:
    # 密码通过文件去验证
    passwd: files
    # 主机需要去文件找,没有再去dns找
    hosts: files dns

解析库:

  • files

  • ethers

  • group

  • hosts

  • netgroup

  • networks

  • passwd

  • protocols

  • rpm

  • services

  • shadow

解析库类型:

  • files

  • dns

  • compat

  • dbm

  • hesiod

  • winbind

  • nis

  • nisplus

查询结果:

  • SUCCESS 成功

  • NOTFOUND 没有找到

  • UNAVIL 服务不可用

  • TRYAGAIN 临时失败

默认找到一个成功就返回了,后续的就不判断了,如果出现没有找到就继续找下一个配置项,我们可以修改默认配置。

# 这个含义就是如果文件没有找到的话,后续的工作(去dns查找)就不做了。
hosts: files[NOTFOUND=return] dns

其他命令

[root@centos-155 ~]# getent shadow root
root:$6$Y1.nEGyQRYQrX.8l$R6QPw5uthWgpv6RlY.9YfEVv5TrBwbNjWX7Di2f4kKbFsgP1W0T2Z4qyVk.N3XuSOTxp01iEvQC0y9GkDh3sB.::0:99999:7:::

pam

pam是可插入式认证模块,nss用于实现名称解析,pam用于实现认证工作。

pam的主配置文件是/etc/pam.conf。次级配置目录有/etc/pam.d/目录下的所有文件。

配置文件格式

type control  module-path module-arguments

type:
    account: 账号相关的非认证功能
    auth: 认证和授权
    password: 用户密码修改时候使用
    session: 用户获取到服务器之前或使用服务完成之后要进行的一些附属性操作。
control:
    这个control代表同一种功能的多种检查之间的如何配合组合,有两种方式。
    1、 使用一个关键词
        required: 这个条件必须通过才可以
        requisite: 一票通过
        sufficient: 一票拒绝
        optional: 无关紧要的
        include: 使用其他文件的认证信息来检查


    2、 使用一道多组“return value=action”
        value: 提示特定的返回值
        action: 采取的操作
        module-path: 模块路径
        module-arguments: 模块参数

文件共享服务

常见的文件共享服务有ftp,nfs,samba这三种,其中ftp是一种应用层的服务,nft是基于 内核来实现的网络文件共享服务,samba是在linux上实现cifs协议来解决扩平台的文件共享 服务。

网络集中式存储模型

DAS:

直接附加存储,也就是直接附加在主板上的存储设备。

NAS:

网络附加存储,通过网络文件服务的形式来提供文件共享存储。

SAN:

存储区域网络,通过块儿级别协议来实现将数据存储在远程主机上的共享存储模式

一些区别:

nas是文件系统级别的,san是块级别的,nas工作在应用层空间上,san工作在内核模式的, nas拿过来就是文件系统,直接可以存储,而san拿过来相当一块新的磁盘,自己格式化才能存储。

ftp

ftp数据传输模式:

主动模式:
  1. 客户端先随机一个端口如5000去连接服务器的21端口来建立命令传输连接

  2. 服务器以20端口来主动连接客户端的5001(5000+1)端口,来进行数据传输

被动模式:
  1. 客户端先随机一个端口如5000去连接服务器的21端口来建立命令传输连接

  2. 服务器通过命令传输连接告诉客户端自己的监听端口如6000

  3. 服务器就以5001(5000+1)去连接服务器的6000端口来进行数据传输

提供ftp的软件:

  • wu-ftpd

  • proftpd

  • pureftp

  • vsftp

  • ServU

客户端工具:

  • ftp

  • lftp

  • lftpget

  • wget

  • curl

  • filezilla

  • gftp

  • flashfxp

  • cuteftp

ftp用户分类:

实体账号:

取到的权限比较完整

匿名用户:

取到的权限很小,通常只是一些公共下载资源

vsftpd的安装
[root@centos-155 ~]# yum install vsftpd
常见配置项
1、 匿名用户的配置
    anonymouns_enable=YES 是否启用匿名
    anon_upload_enable=YES
    anon_mkdir_write_enable=YES
    anon_other_write_enable=YES

2、 系统用户的配置
    local_enable=YES
    write_enable=YES
    local_umask=022
3、 禁锢所有的本地用户访问自己的家目录
    chroot_local_user=YES
4、 禁锢文件中指定的用户在其家目录
    chroot_list_enable=YES
    chroot_list_file=/etc/vsftpd/chroot_list
5、 日志
    xferlog_enable=YES
    xferlog_std_format=YES
    xferlog_file=/var/log/xferlog
    dual_log_enable=YES
    vsftpd_log_file=/var/log/vsftpd.log
6、 改变上传文件的属主
    chown_uploads=YES
    chown_usernmae=root
7、 vsftpd使用pam完整用户身份认证
    pam_service_name=vsftpd
8、 是否启用控制用户登陆的列表
    userlist_enable=YES
    userlist_deny=YES
9、 连接限制
    max_clients
    max_per_ip
10、传输速率
    anon_max_rate
    local_max_rate
11、ssl
    ssl_enable=YES
    allow_anon_ssl=NO
    force_local_data_ssl=YES
    force_local_login_ssl=YES
    ssl_tlsv1=YES
    ssl_tlsv2=YES
    ssl_tlsv3=YES
    rsa_cert_file=/etc/vsftpd/vsftpd.pem

12、其他相关设置
    connect_from_port_20
    listen_port
    listen
    pasv_enable=YES
    connect_timeout=60
    accept_timeout=60
    data_connection_timeout=300
    pasv_min_port
    pasv_max_port
    tcp_wrappers
基于虚拟用户的vsftpd

主要步骤:

  1. 创建虚拟用户账户和密码文件,并使用db_load转化

  2. 创建本地账户,修改权限

  3. 添加pam文件

  4. 配置文件添加guest相关项目,pam_service_name,user_config_dir

  5. 创建user_config_dir目录,在目录下创建虚拟用户同名的文件,添加配置项

  6. 重启服务,测试。

详细步骤参考: ftp基于文件的验证

lftp

命令样例

# 直接输入用户密码和端口等详细信息的方式
[root@centos-155 virtualftp]# lftp -p 21 -u panda1:panda1 192.168.46.155
lftp panda1@192.168.46.155:~> ls
drwxr-xr-x    3 1017     1020           15 Feb 12 08:34 pub
lftp panda1@192.168.46.155:/> help
    !<shell-command>                     (commands)                           alias [<name> [<value>]]             attach [PID]                         bookmark [SUBCMD]
    cache [SUBCMD]                       cat [-b] <files>                     cd <rdir>                            chmod [OPTS] mode file...            close [-a]
    [re]cls [opts] [path/][pattern]      debug [<level>|off] [-o <file>]      du [options] <dirs>                  exit [<code>|bg]
    get [OPTS] <rfile> [-o <lfile>]      glob [OPTS] <cmd> <args>             help [<cmd>]                         history -w file|-r file|-c|-l [cnt]
    jobs [-v] [<job_no...>]              kill all|<job_no>                    lcd <ldir>                           lftp [OPTS] <site>
    ln [-s] <file1> <file2>              ls [<args>]                          mget [OPTS] <files>                  mirror [OPTS] [remote [local]]       mkdir [-p] <dirs>
    module name [args]                   more <files>                         mput [OPTS] <files>                  mrm <files>                          mv <file1> <file2>
    [re]nlist [<args>]                   open [OPTS] <site>                   pget [OPTS] <rfile> [-o <lfile>]     put [OPTS] <lfile> [-o <rfile>]      pwd [-p]
    queue [OPTS] [<cmd>]                 quote <cmd>                          repeat [OPTS] [delay] [command]      rm [-r] [-f] <files>                 rmdir [-f] <dirs>
    scache [<session_no>]                set [OPT] [<var> [<val>]]            site <site-cmd>                      source <file>
    torrent [-O <dir>] <file|URL>...     user <user|URL> [<pass>]             wait [<jobno>]                       zcat <files>                         zmore <files>
lftp panda1@192.168.46.155:/> quit

# 后输入用户和密码方式
[root@centos-155 virtualftp]# lftp localhost
lftp localhost:~> user panda1
Password:
lftp panda1@localhost:~> ls
drwxr-xr-x    3 1017     1020           28 Feb 12 08:44 pub
lftp panda1@localhost:/> cd pub/
lftp panda1@localhost:/pub> ls
drwx------    2 1017     1020            6 Feb 12 08:34 a
-rw-r--r--    1 0        0               0 Feb 12 08:44 a.txt
lftp panda1@localhost:/pub> get a.txt
wget

wget是gpl许可的一个文件下载软件包,支持http,https,ftp协议,支持代理服务器和断点续传功能。

主要常用选项:

-r

递归下载

-b

后台下载

-m

镜像

-c

断点续传

-I

指定下载目录列表

-A

指定接受和拒绝下载列表

--proxy

代理

-t

重试次数

-nc

不覆盖原有的

-N

只下载新的文件

-nd

不进行目录结构创建

-x

强制创建目录结构

-nH

不继承主机主机目录结构

-P

设置目录前缀

nfs

nfs是network filesystem的缩写,能通过网络在不同主机之间彼此实现资源共享。

nfs是通过rpc调用来实现文件共享的,先启动rpc服务,在启动nfs服务,这样nfs的端口就被注册到 了rpc了,用户使用网络文件系统先通过rpc获取nfs的监听端口,然后在给监听的端口通信,来获取数据。

nfs的配置比较简单

[root@centos-155 ~]# vim /etc/exports
# 添加如下行
/data 192.168.46.7/24(rw,sync,no_root_squash)

# 格式就是  数据 限定ip(选项)
#启动服务
[root@centos-155 ~]# systemctl restart rpcbind nfs

#查看共享出来的信息
[root@centos-155 ~]# showmount -e 192.168.46.155
Export list for 192.168.46.155:
/data/nfs 192.168.46.0/24
# 创建目录
[root@centos-155 ~]# mkdir /mnt/nfs
[root@centos-155 ~]# mkdir /data/nfs
# 挂载
[root@centos-155 ~]# mount 192.168.46.155:/data/nfs /mnt/nfs

# 开机自动挂载
[root@centos-155 ~]# tail -n 1 /etc/mtab  >> /etc/fstab

一个简单的nfs配置就是这么简答,有些命令比较实用

export -ar   重新导入所有的文件系统
export -au   关闭导出的所有文件系统
export -u FS 关闭指定的文件系统

samba

samba是为window和linux之间共享文件而生的。

安装

[root@centos-155 ~]# yum install samba

创建密码使用smbpasswd命令就可以了,不过要本地有这个用户。

样例参考: 2018-02-03-练习网络文件共享2

DNS域名解析服务

dns是domain names system的简写,主要作用就是将主机名解析成ip地址的过程。

dns是一个分布式、分层次的主机名管理架构,通过配置dns服务器地址,主机不需要知道对应的 ip地址就能通过主机名的形式访问互联网。

fqdn是full qualified domain name的简写,焦作完整主机名

dns解析过程

假定访问www.linuxpanda.tech这个主机的话

  1. 本机先查询本地的hosts文件是否有对应blog.linuxpanda.tech这个主机和ip对应关系,如果直接给与, 否则进行第二步。

  2. 本机想自己的dns server1 发送查询请求,ns1在收到客户端的请求后,会及时的查询自己缓存记录,如果有就 反馈给客户端,没有没有,进行第三步。

  3. ns1会主动想根域名服务器发起查询blog.linuxpanda.tech的请求,根只告诉.tech的相关信息,ns1去.tech的 机器查询,告诉linuxpanda这个域, 最终linuxpanda的dns服务来告诉ns1整整的blog主机所在的ip。

  4. ns1缓存下这个查询结果,然后反馈结果给客户端,客户端也会缓存一份。

查询方式:

递归查询:

发生在客户机和服务器之间,客户端只需要发送一次请求,剩下的工作都交给了服务器来完成。

迭代查询:

发生在dns服务器和dns服务器之间,每次查询都只是一个提示,都需要自己去查询下一个dns服务器来获取结果。

dns是一个网络服务,需要监听在固定的端口的,dns监听在tcp,udp的53端口,通常查询就是走的udp协议,一旦没有办法查询 到完整的信息,会以tcp协议来进行重新查询,因此dns在启动的时候会开启tcp的53和udp的53端口。

Linux系统防火墙

Linux Syslog系统日志管理

Web Service

练习题11月

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

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

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

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"

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

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

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" -o

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
[root@localhost ~]# ss -tn  | awk 'BEGIN{ PROCINFO["sorted_in"]="@val_num_desc"} NR >1  {gsub(/:[0-9]+/,"") ; ips[$NF]++;}END{for (ip in ips){print ip,ips[ip]} }'

练习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
[root@localhost ~]# cat /etc/passwd |awk -F ":"  ' $3 < 1000 { print $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"
[root@localhost ~]# echo "welcome to magedu linux"  | awk -F "" 'BEGIN{PROCINFO["sorted_in"]="@ind_str_asc"}{for (i=1;i<=NF; i++){if($i ~ /[a-zA-Z]/){num[$i]++}}} END{ for (i in num){print i}}'

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

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 -113

练习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 -113

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文件中的enabled=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@

2017-11-15-练习-mount

练习1-mount

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--

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 "g:g2:rw" -R /testdir/dir/
[root@centos6 dir]# groupadd g3
[root@centos6 dir]# useradd tom -G g3
[root@centos6 dir]# setfacl -m "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                        # -b ==--remove-all
[root@centos6 testdir]# setfacl --restore /root/acl.txt
[root@centos6 testdir]# getfacl -R dir

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
[root@7 ~]# cat /etc/passwd |awk -F ":" ' {if(NR==10 || NR==20 ){sum+=$3}} END{print sum}'

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

Note

初始化脚本托管到github上了, My_Study_Bash

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

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

tar 命令配合压缩选项:

-J

xz

-j

bz

-z

gzip

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]$ cpio -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

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

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种结果必须是一致的。

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

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

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-rpm基础使用

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

练习题12月

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

练习1-故障修复

1、 mbr损坏的修复

[root@centos7 ~]$ dd if=/dev/sda of=/app/mbr bs=1 count=512
512+0 records in
512+0 records out
512 bytes (512 B) copied, 0.000847418 s, 604 kB/s
[root@centos7 ~]$ scp /app/mbr 172.18.1.159:
root@172.18.1.159's password:
mbr                                                                                 100%  512   428.1KB/s   00:00
[root@centos7 ~]$ dd if=/dev/zero of=/dev/sda bs=1 count=512
512+0 records in
512+0 records out
512 bytes (512 B) copied, 0.000467582 s, 1.1 MB/s
#进入救援模式
[root@centos7 ~]$ ifconfig ens33 172.18.1.250
[root@centos7 ~]$ scp root@172.18.1.159:/root/mbr .
[root@centos7 ~]$ dd if=mbr of=/dev/sda bs=1 count=512
[root@centos7 ~]$ reboot

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. 列出当前系统识别到的所有磁盘设备

  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

mkdvdiso.sh

练习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

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的使用.

练习3-raid


要求: 1、创建一个10g的raid1 2、创建一个可用空间为10g的raid5设备,要求其chunk大小为256k,文件系统为ext4,开机可自动挂载到/backup目录, 支持acl功能,有一个空闲盘。

要求1:

[root@centos-155 ~]# yum install mdadm
[root@centos-155 ~]# fdisk  /dev/sdb
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 type:
p   primary (0 primary, 0 extended, 4 free)
e   extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-41943039, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-41943039, default 41943039): +1G
Partition 1 of type Linux and of size 1 GiB is set

Command (m for help): n
Partition type:
p   primary (1 primary, 0 extended, 3 free)
e   extended
Select (default p): p
Partition number (2-4, default 2):
First sector (2099200-41943039, default 2099200):
Using default value 2099200
Last sector, +sectors or +size{K,M,G} (2099200-41943039, default 41943039): +1G
Partition 2 of type Linux and of size 1 GiB is set

Command (m for help): p

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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: dos
Disk identifier: 0x489a4915

Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048     2099199     1048576   83  Linux
/dev/sdb2         2099200     4196351     1048576   83  Linux

Command (m for help): t
Partition number (1,2, default 2):
Hex code (type L to list all codes): l

0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris
1  FAT12           27  Hidden NTFS Win 82  Linux swap / So c1  DRDOS/sec (FAT-
2  XENIX root      39  Plan 9          83  Linux           c4  DRDOS/sec (FAT-
3  XENIX usr       3c  PartitionMagic  84  OS/2 hidden C:  c6  DRDOS/sec (FAT-
4  FAT16 <32M      40  Venix 80286     85  Linux extended  c7  Syrinx
5  Extended        41  PPC PReP Boot   86  NTFS volume set da  Non-FS data
6  FAT16           42  SFS             87  NTFS volume set db  CP/M / CTOS / .
7  HPFS/NTFS/exFAT 4d  QNX4.x          88  Linux plaintext de  Dell Utility
8  AIX             4e  QNX4.x 2nd part 8e  Linux LVM       df  BootIt
9  AIX bootable    4f  QNX4.x 3rd part 93  Amoeba          e1  DOS access
a  OS/2 Boot Manag 50  OnTrack DM      94  Amoeba BBT      e3  DOS R/O
b  W95 FAT32       51  OnTrack DM6 Aux 9f  BSD/OS          e4  SpeedStor
c  W95 FAT32 (LBA) 52  CP/M            a0  IBM Thinkpad hi eb  BeOS fs
e  W95 FAT16 (LBA) 53  OnTrack DM6 Aux a5  FreeBSD         ee  GPT
f  W95 Ext'd (LBA) 54  OnTrackDM6      a6  OpenBSD         ef  EFI (FAT-12/16/
10  OPUS            55  EZ-Drive        a7  NeXTSTEP        f0  Linux/PA-RISC b
11  Hidden FAT12    56  Golden Bow      a8  Darwin UFS      f1  SpeedStor
12  Compaq diagnost 5c  Priam Edisk     a9  NetBSD          f4  SpeedStor
14  Hidden FAT16 <3 61  SpeedStor       ab  Darwin boot     f2  DOS secondary
16  Hidden FAT16    63  GNU HURD or Sys af  HFS / HFS+      fb  VMware VMFS
17  Hidden HPFS/NTF 64  Novell Netware  b7  BSDI fs         fc  VMware VMKCORE
18  AST SmartSleep  65  Novell Netware  b8  BSDI swap       fd  Linux raid auto
1b  Hidden W95 FAT3 70  DiskSecure Mult bb  Boot Wizard hid fe  LANstep
1c  Hidden W95 FAT3 75  PC/IX           be  Solaris boot    ff  BBT
1e  Hidden W95 FAT1 80  Old Minix
Hex code (type L to list all codes): fd
Changed type of partition 'Linux' to 'Linux raid autodetect'

Command (m for help): t
Partition number (1,2, default 2): 1
Hex code (type L to list all codes): fd
Changed type of partition 'Linux' to 'Linux raid autodetect'

Command (m for help): p

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 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: dos
Disk identifier: 0x489a4915

Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048     2099199     1048576   fd  Linux raid autodetect
/dev/sdb2         2099200     4196351     1048576   fd  Linux raid autodetect

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

Calling ioctl() to re-read partition table.
Syncing disks.

[root@centos-155 ~]# mdadm -C /dev/md0 -a yes -l 1 -n 2 /dev/sdb1 /dev/sdb2

要求2 :

# 创建raid
[root@centos-155 ~]# mdadm -C /dev/md1 -a yes -c 256 -l 5 -n 2 /dev/sdb5 /dev/sdb6 -x 1 /dev/sdb7
# 导出配置
[root@centos-155 ~]# mdadm -Ds > /etc/mdadm.conf
# 格式化
[root@centos-155 ~]# mkfs.ext4 /dev/md1
# 启用acl
[root@centos-155 ~]# tune2fs -o +acl /dev/md1
tune2fs 1.42.9 (28-Dec-2013)
# 创建挂载目录
[root@centos-155 ~]# mkdir /backup
# 挂载
[root@centos-155 ~]# mount /dev/md1 /backup
[root@centos-155 ~]# cd /backup
# 测试acl
[root@centos-155 backup]# touch a.txt
[root@centos-155 backup]# getfacl a.txt
# file: a.txt
# owner: root
# group: root
user::rw-
group::r--
other::r--
[root@centos-155 backup]# setfacl -m "u:zhao:rwx" a.txt
[root@centos-155 backup]# su - zhao
[zhao@centos-155 ~]$ cat /backup/a.txt
[root@centos-155 /]# vim /etc/fstab
/dev/md1                  /backup               ext4    acl             0  0
# 测试备用盘情况
[root@centos-155 backup]# mdadm -D /dev/md1
/dev/md1:
        Version : 1.2
    Creation Time : Sat Feb 10 17:45:54 2018
        Raid Level : raid5
        Array Size : 5238784 (5.00 GiB 5.36 GB)
    Used Dev Size : 5238784 (5.00 GiB 5.36 GB)
    Raid Devices : 2
    Total Devices : 3
    Persistence : Superblock is persistent

    Update Time : Sat Feb 10 18:00:52 2018
            State : clean
    Active Devices : 2
Working Devices : 3
    Failed Devices : 0
    Spare Devices : 1

            Layout : left-symmetric
        Chunk Size : 256K

Consistency Policy : resync

            Name : centos-155:1  (local to host centos-155)
            UUID : 5d7284f1:8e854b7f:66a789ce:33565d50
            Events : 18

    Number   Major   Minor   RaidDevice State
    0       8       21        0      active sync   /dev/sdb5
    3       8       22        1      active sync   /dev/sdb6

    2       8       23        -      spare   /dev/sdb7

    (/dev/sdb5) is listed
[root@centos-155 backup]# mdadm /dev/md1 -f /dev/sdb5
mdadm: set /dev/sdb5 faulty in /dev/md1

[root@centos-155 backup]# mdadm -D /dev/md1
/dev/md1:
        Version : 1.2
    Creation Time : Sat Feb 10 17:45:54 2018
        Raid Level : raid5
        Array Size : 5238784 (5.00 GiB 5.36 GB)
    Used Dev Size : 5238784 (5.00 GiB 5.36 GB)
    Raid Devices : 2
    Total Devices : 3
    Persistence : Superblock is persistent

    Update Time : Sat Feb 10 18:08:36 2018
            State : clean, degraded, recovering
    Active Devices : 1
Working Devices : 2
    Failed Devices : 1
    Spare Devices : 1

            Layout : left-symmetric
        Chunk Size : 256K

Consistency Policy : resync

    Rebuild Status : 53% complete

            Name : centos-155:1  (local to host centos-155)
            UUID : 5d7284f1:8e854b7f:66a789ce:33565d50
            Events : 28

    Number   Major   Minor   RaidDevice State
    2       8       23        0      spare rebuilding   /dev/sdb7
    3       8       22        1      active sync   /dev/sdb6

    0       8       21        -      faulty   /dev/sdb5

2017-12-13-练习-网络

练习1-子网划分

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

1.分析32个子网,需要5位借位
    10.00000 000.0.0
2.最大的子网为
    10.11111000.0.0/13即10.248.0.0/13
3.ip范围为
    10.248.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.测试

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

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

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

练习2-作业管理练习

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

_images/作业状态.png

练习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":{"method":"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

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

2017-12-17-练习计划任务

练习1-ftplftp使用

1、每4小时执行一次对/etc目录的备份,备份到/backup目录中,保存的目录名为/etc-2017-12-01-12-00

[root@centos-155 ~]# vim backup_etc.sh
[root@centos-155 ~]# cat backup_etc.sh
#!/bin/bash

cp -a /etc /backup/etc-$(date +"%Y-%m-%d-%H-%M") &>/dev/null

[root@centos-155 ~]# crontab  -e
crontab: installing new crontab
[root@centos-155 ~]# ll backup_etc.sh
-rw-r--r-- 1 root root 76 Feb 11 10:43 backup_etc.sh
[root@centos-155 ~]# chmod a+x backup_etc.sh
[root@centos-155 ~]# crontab -l
* */4 * * * /root/backup_etc.sh

2、 每周2,4,6备份/var/log/message文件到/backup/message_logs目录中,保存的文件名形如message-20150402

3、 每天每小时去当前系统/proc/memeinfo文件中的S开头的信息到/stats/memory.txt中。

4、 工作日的工作时间内,没两个小时执行一次echo ‘howdy’

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

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)

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

练习1-centos6基础故障

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

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文件

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

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"

2017-12-28-练习awk

awk学习笔记

练习1-awk

1、统计/etc/fstab文件中每个文件系统类型出现的次数

[root@centos74 test]$ cat /etc/fstab |awk ' /^[^#]/ {print $3}' | sort  |uniq -c
        3 ext4

[root@centos74 test]$ cat /etc/fstab |awk ' /^[^#]/ {arr[$3]++} END{for (i in arr){print arr[i],i}}'
3 ext4

2、统计/etc/fstab文件中每个单词出现的次数

[root@centos74 test]$ cat /etc/fstab | awk '{for (i=1;i<=NF;i++){arr[$i]++}} END { for(i in arr){print i,arr[i]}}'

3、提取出字符串Yd$C@M05MB%9&Bdh7dq+YVixp3vpw中的所有数字

[root@centos74 test]$ echo "Yd$C@M05MB%9&Bdh7dq+YVixp3vpw"  |tr -dc "[:digit:]"

[root@centos74 test]$ echo "Yd$C@M05MB%9&Bdh7dq+YVixp3vpw"  |awk -F "" '{for (i=1;i<=NF;i++){if ($i ~ /[[:digit:]]/){printf "%s" , $i }}print ""}'
05973

4、解决DOS攻击生产案例:根据web日志或者或者网络连接数,监控当某个IP并发连接数或者短时内PV达到100,即调用防火墙命令封掉对应的IP,监控频率每隔5分钟。防火墙命令为:iptables -A INPUT -s IP -j REJECT

netstat -tup | awk '/tcp/ {socket=$5; split(socket,tmps,":");ss[tmps[1]]++} END {for (i in ss){if (ss[i] >0){cmd="iptables -A INPUT -s "i" -j REJECT"; system(cmd);} }}'

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

练习题1月

2018-01-02-练习systemd

练习1

1、为编译安装的httpd服务,实现service unit文件

2、破解centos7 口令

方法1:

  1. 在启动的时候添加内核参数rd.break

  2. chmount -o remount,rw /sysroot ; chroot /sysroot

  3. passwd ;

  4. touch /.autorelabel

方法2:

  1. 启动的时候修改r为rw,添加内核参数init=/sysroot/bin/bash

  2. chroot /sysroot

  3. passwd

  4. touch /.autorelabel

3、修改默认的启动内核为新编译内核

1. 查看新内核在/boot/grub2/gurb.cfg里面的menuententry。
2. 修改/etc/default/grub中GRUB_DEFAULT=1
3. grub2-mkconfig
4. 重启即可

4、启动时临时禁用SELinux

selinux=0

5、启动时进入emergency模式

systemd.unit=emergency.target

6、卸载编译安装的新内核

1. 删除/boot目录对应文件
2. 删除/lib/modules对应文件
3. grub2-mkconfig
4. 重启

2018-01-03-练习加密

练习1-加密

1、在centos7使用gpg公钥加密数据,给centos6机器,完成解密

先分别在2个主机上使用gpg命令生成各自的公钥和秘钥

[root@centos74 ~]$ gpg --gen-key
gpg (GnuPG) 2.0.22; Copyright (C) 2013 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Please select what kind of key you want:
(1) RSA and RSA (default)
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection?
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
                0 = key does not expire
        <n>  = key expires in n days
        <n>w = key expires in n weeks
        <n>m = key expires in n months
        <n>y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y

GnuPG needs to construct a user ID to identify your key.

Real name: root-centos7
Email address: root@linuxpanda.tech
Comment:
You selected this USER-ID:
        "rootroot <root@linuxpanda.tech>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o
You need a Passphrase to protect your secret key.

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 51307618 marked as ultimately trusted
public and secret key created and signed.

gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
pub   2048R/51307618 2018-01-04
        Key fingerprint = FD85 7BE3 43C4 635A 112F  22D2 3874 E874 5130 7618
uid                  root-centos7 <root@linuxpanda.tech>
sub   2048R/3572455E 2018-01-04

# 同样的gpg --gen-key在centos6上执行一次

互相copy公钥

[root@centos66 ~]$ gpg -a --export -o /app/centos6.pubkey
[root@centos66 ~]$ cat /app/centos6.pubkey
[root@centos66 ~]$ scp /app/centos6.pubkey root@172.18.46.7:/app/


#同样的操作在centos7上执行一次。

导入彼此公钥

[root@centos74 ~]$ gpg --import /app/centos6.pubkey
gpg: key EA73F7F7: public key "rootroot <root@linuxpanda.tech>" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
[root@centos74 ~]$ gpg --list-key
/root/.gnupg/pubring.gpg
------------------------
pub   2048R/51307618 2018-01-04
uid                  root-centos7 <root@linuxpanda.tech>
sub   2048R/3572455E 2018-01-04

pub   2048R/EA73F7F7 2017-12-22
uid                  root-centos6 <root@linuxpanda.tech>
sub   2048R/43E98B8A 2017-12-22

# 同样操作在对方机器操作

centos7加密,传送给centos6并解密

[root@centos74 test]$ gpg -e -r root-centos6 fstab
gpg: 694F10F7: There is no assurance this key belongs to the named user

pub  2048R/694F10F7 2018-01-04 root-centos6 <root@linuxpanda.tech>
Primary key fingerprint: EE7C 0929 A144 AD51 A8A2  765F 5F63 760E 1E0F 2C2F
        Subkey fingerprint: 3FA5 2D57 3347 3747 F9AD  5206 4171 C8E3 694F 10F7
It is NOT certain that the key belongs to the person named
in the user ID.  If you *really* know what you are doing,
you may answer the next question with yes.

Use this key anyway? (y/N) y
[root@centos74 test]$ scp fstab
fstab      fstab.gpg
[root@centos74 test]$ scp fstab
fstab      fstab.gpg
[root@centos74 test]$ scp fstab.gpg  172.18.46.6:/app/
root@172.18.46.6's password:
fstab.gpg                                                                                     100%  795   616.3KB/s   00:00

[root@centos66 ~]$ cd /app
[root@centos66 app]$ file fstab.gpg
fstab.gpg: data
[root@centos66 app]$ gpg -d fstab.gpg

You need a passphrase to unlock the secret key for
user: "root-centos6 <root@linuxpanda.tech>"
2048-bit RSA key, ID 694F10F7, created 2018-01-04 (main key ID 1E0F2C2F)

can't connect to '/root/.gnupg/S.gpg-agent': No such file or directory
gpg: encrypted with 2048-bit RSA key, ID 694F10F7, created 2018-01-04
        "root-centos6 <root@linuxpanda.tech>"

#
# /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
#UUID=a0516c4f-40e6-4919-905a-8b44db12ff7b swap                           swap    defaults,pri=0        0 0
#/dev/sdb2 /test ext4 rw,seclabel,relatime,data=ordered 0 0
#/dev/sdb1 /home xfs rw,seclabel,relatime,attr2,inode64,usrquota,grpquota  0 0
[root@centos66 app]$ gpg -d fstab.gpg  >newfstab

You need a passphrase to unlock the secret key for
user: "root-centos6 <root@linuxpanda.tech>"
2048-bit RSA key, ID 694F10F7, created 2018-01-04 (main key ID 1E0F2C2F)

can't connect to '/root/.gnupg/S.gpg-agent': No such file or directory
gpg: encrypted with 2048-bit RSA key, ID 694F10F7, created 2018-01-04
        "root-centos6 <root@linuxpanda.tech>"
[root@centos66 app]$ cat newfstab

#
# /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
#UUID=a0516c4f-40e6-4919-905a-8b44db12ff7b swap                           swap    defaults,pri=0        0 0
#/dev/sdb2 /test ext4 rw,seclabel,relatime,data=ordered 0 0
#/dev/sdb1 /home xfs rw,seclabel,relatime,attr2,inode64,usrquota,grpquota  0 0

2、使用gpg对称加密文件,并解密数据

[root@centos74 app]$ vim 11.txt
[root@centos74 app]$ cat 11.txt
abc
[root@centos74 app]$ gpg -c 11.txt
[root@centos74 app]$ cp 11.txt.gpg /root/
[root@centos74 app]$ cd /root
[root@centos74 ~]$ gpg -d 11.txt.gpg  >a.txt
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
[root@centos74 ~]$ cat a.txt
abc

3、加密生成的秘钥, 如果使用代理免去输入密码

免密码登陆

4、配置免密码登陆

免密码登陆

5、批量配置免密码登陆

免密码登陆

2018-01-05-练习ssh

练习1-ssh

1、复制centos7下目录的/etc/sysconfig 到centos6的/app目录下去。复制centos6对应目录到centos7 。复制保留权限且静默。

scp -aq /etc/sysconfig 172.18.46.6:/app/
scp -aq /etc/sysconfig 172.18.46.7:/app/

2、熟练掌握pssh命令使用

pssh详细参考

pssh详细参考2

[root@centos74 ~]$ pssh --help
Usage: pssh [OPTIONS] command [...]

Options:
--version             show program's version number and exit
--help                show this help message and exit
-h HOST_FILE, --hosts=HOST_FILE
                        hosts file (each line "[user@]host[:port]")
-H HOST_STRING, --host=HOST_STRING
                        additional host entries ("[user@]host[:port]")
-l USER, --user=USER  username (OPTIONAL)
-p PAR, --par=PAR     max number of parallel threads (OPTIONAL)
-o OUTDIR, --outdir=OUTDIR
                        output directory for stdout files (OPTIONAL)
-e ERRDIR, --errdir=ERRDIR
                        output directory for stderr files (OPTIONAL)
-t TIMEOUT, --timeout=TIMEOUT
                        timeout (secs) (0 = no timeout) per host (OPTIONAL)
-O OPTION, --option=OPTION
                        SSH option (OPTIONAL)
-v, --verbose         turn on warning and diagnostic messages (OPTIONAL)
-A, --askpass         Ask for a password (OPTIONAL)
-x ARGS, --extra-args=ARGS
                        Extra command-line arguments, with processing for
                        spaces, quotes, and backslashes
-X ARG, --extra-arg=ARG
                        Extra command-line argument
-i, --inline          inline aggregated output and error for each server
--inline-stdout       inline standard output for each server
-I, --send-input      read from standard input and send as input to ssh
-P, --print           print output as we get it

Example: pssh -h hosts.txt -l irb2 -o /tmp/foo uptime

3、ssh端口转发

3.1 在外部操作

[root@centos74 ~]$ ssh -L 9527:192.168.1.111:23 192.168.1.110 -Nf
The authenticity of host '192.168.1.110 (192.168.1.110)' can't be established.
ECDSA key fingerprint is SHA256:DZfkxQNLDfBgnRSvByer8Xfl+UpJWGiLbkgWZoPEiso.
ECDSA key fingerprint is MD5:be:6e:9b:d4:97:3f:46:ab:54:98:d7:36:ff:40:57:5e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.110' (ECDSA) to the list of known hosts.
root@192.168.1.110's password:
[root@centos74 ~]$ telnet 127.0.0.1 9527
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.

Kernel 3.10.0-693.11.1.el7.x86_64 on an x86_64
station login: zhao
Password:
Last login: Fri Jan  5 09:19:20 from ::ffff:192.168.1.7
[zhao@station ~]$ exit
logout
Connection closed by foreign host.

3.2 在内部操作

[root@station ~]# ssh -R 9527:192.168.1.111:25 192.168.1.7 -Nf
The authenticity of host '192.168.1.7 (192.168.1.7)' can't be established.
ECDSA key fingerprint is SHA256:f/BWWhLUjmhdSZob0AZ7EaMrntJ0XDvj92t9hGl0woo.
ECDSA key fingerprint is MD5:1d:04:a6:1f:cb:6d:35:00:aa:2a:30:4e:68:80:ec:fe.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.7' (ECDSA) to the list of known hosts.
root@192.168.1.7's password:

3.3 翻墙

[root@centos74 ~]$ ssh -D 1080 192.168.1.110 -Nf
root@192.168.1.110's password:
[root@centos74 ~]$ curl --socks5  127.0.0.1:1080 http://192.168.1.111/index.html
<h1>test</h1>

练习2-dropbear

1、编译安装dropbear

wget http://matt.ucc.asn.au/dropbear/releases/dropbear-2017.75.tar.bz2
tar xf dropbear-2017.75.tar.bz2
cd dropbear-2017.75/
./configure  --prefix=/usr/local/dropbear --disable-zlib
vim INSTALL
make PROGRAMS="dropbear dbclient dropbearkey dropbearconvert scp"
vim INSTALL
make PROGRAMS="dropbear dbclient dropbearkey dropbearconvert scp" install
cd /usr/local/dropbear
tree
mkdir /etc/dropbear
dropbearkey -t rsa -f /etc/dropbear/dropbear_rsa_host_key
dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key
dropbearkey -t ecdsa -f /etc/dropbear/dropbear_ecdsa_host_key

dropbear -p 9527  -FE

练习3-aide

1、监控系统重要文件。

[root@centos74 aide]$ yum install aide
[root@centos74 aide]$ vim /etc/aide.conf
这行后面的都删除, 我这里值关注boot目录的变换情况
/boot/   CONTENT_EX
[root@centos74 boot]$ touch t1 >>/boot/t1.txt
[root@centos74 boot]$ mkdir t2
[root@centos74 boot]$ cd /var/lib/aide/
[root@centos74 aide]$ mv aide.db.new.gz aide.db.gz
[root@centos74 aide]$ aide --check
AIDE 0.15.1 found differences between database and filesystem!!
Start timestamp: 2018-01-08 18:45:46

Summary:
Total number of files:      321
Added files:                        2
Removed files:              0
Changed files:              0


---------------------------------------------------
Added files:
---------------------------------------------------

added: /boot/t1.txt
added: /boot/t2

2018-01-06-练习sudotcpwrap

练习1-sudo

sudo

练习2-tcpwarp

tcpwarp

2018-01-08-练习tcpwrap,rsync

练习1-sudo

sudo

练习2-tcpwarp

tcpwrap

练习3-tcpwarp

1、仅开放本机两个IP地址中的一个地址172.16.0.X上绑定的sshd和vsftpd服务给172.16.0.0/16 网络中除了172.16.0.0/24网络中的主机之外的所有主机,但允许172.16.0.200访问,每次的用户访 问都要记录于日志文件中注:其中X为学号。

2018-01-09-练习pam,自动化安装

练习1-pam

1、使用pam_nologin,pam_security,pam_limit,pam_shell

pam_shell

vim /etc/pam.d/login 第一行添加如下行
auth      required  pam_shells.so

pam_nologin

[root@centos74 pam.d]$ man pam_nologin
[root@centos74 pam.d]$ grep nologin ./*
./gdm-autologin:account    required    pam_nologin.so
./gdm-fingerprint:account     required      pam_nologin.so
./gdm-password:account     required      pam_nologin.so
./gdm-pin:account     required      pam_nologin.so
./gdm-smartcard:account     required      pam_nologin.so
./login:account    required     pam_nologin.so
./pluto:account required pam_nologin.so
./ppp:account    required   pam_nologin.so
./remote:account    required     pam_nologin.so
./sshd:account    required     pam_nologin.so
[root@centos74 pam.d]$ touch /etc/nologin
[root@centos74 pam.d]$ ssh zhao@localhost
zhao@localhost's password:
Authentication failed.

pam_limit

[root@centos74 limits.d]$ man 5 limits.conf
[root@centos74 limits.d]$ ulimit  -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7823
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7823
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

[root@centos74 limits.d]$ vim 20-nproc.conf
[root@centos74 limits.d]$ cat 20-nproc.conf
# Default limit for number of user's processes to prevent
# accidental fork bombs.
# See rhbz #432903 for reasoning.

*          soft    nproc     4096
root       soft    nproc     unlimited
zhao           hard    nproc     5

ulimit: ulimit [-SHacdefilmnpqrstuvx] [limit]
    Modify shell resource limits.

    Provides control over the resources available to the shell and processes
    it creates, on systems that allow such control.

    Options:
    -S      use the 'soft' resource limit               # 软限制
    -H      use the 'hard' resource limit               # 硬限制
    -a      all current limits are reported             # 列出限制
    -b      the socket buffer size                      # socket 缓冲大小
    -c      the maximum size of core files created      # 最大核心文件创建
    -d      the maximum size of a process's data segment# 最大进程数据段大小
    -e      the maximum scheduling priority ('nice')    # 最大nice值
    -f      the maximum size of files written by the shell and its children # 最大的文件大小
    -i      the maximum number of pending signals       # 最大的暂停信号
    -l      the maximum size a process may lock into memory # 最大的锁到内存的进程数
    -m      the maximum resident set size                   #
    -n      the maximum number of open file descriptors     # 最大打开的文件数量
    -p      the pipe buffer size                            # 管道缓冲区大小
    -q      the maximum number of bytes in POSIX message queues # 最大字节关于post消息队列
    -r      the maximum real-time scheduling priority           # 实时调度优先级最大值
    -s      the maximum stack size                              # 最大栈大小
    -t      the maximum amount of cpu time in seconds           # 最大cpu用时
    -u      the maximum number of user processes                # 最大用户进程数量
    -v      the size of virtual memory                          # 虚拟内存大小
    -x      the maximum number of file locks                    # 最大文件锁定个数

2、编写脚本/root/bin/checkip.sh,每5分钟检查一次,如果发现通过ssh登录失败次数超过10次,自动将此远程IP放入Tcp Wrapper的黑名单中予以禁止防问

#!/bin/awk -f
/sshd.*Failed password/{ip=$(NF-3); ips[ip]++}
END{
        for (i in ips){
                if(ips[i]>4){
                        cmd="echo sshd:"i">>/etc/hosts.deny"; system(cmd)
                }
        }
}

# crontab -e
*/5 * * * *  /root/bin/checkip.awk /var/log/secure

3、限制centos用户只能够在工作时间通过ssh远程连接本机

# vim /etc/pam.d/sshd  # 添加如下行
account  required  pam_time.so
# vim /etc/security/time.conf # 添加行
sshd;*;test1;Wd0800-1800

4、限制只有admins组内的用户可ssh到本机

# 编辑 /etc/ssh/sshd_config 文件,添加AllowGroups admins
# 重启sshd服务。

练习2-自动化安装

1、通过光盘启动,安装局域网的系统

linux askmethod ip=172.18.46.105 netmask=255.255.0.0

2、不使用大光盘, 直接自制一个小光盘,然后安装网络的系统

linux ks=http://172.18.46.6/pub/ks/ks7-mini.cfg ip=172.18.46.105 netmask=255.255.0.0

3、制作可启动U盘,自动安装系统

[root@station /]# find /centos6/ -name TRANS.TBL -exec rm -rf {} \;
[root@centos66 centos6]$ rm -rf repodata/*
[root@centos66 centos6]$ cp /mnt/cdrom/repodata/43d8fd068164b0f042845474d6a22262798b9f0d1f49ad1bf9f95b953089777d-c6-x86_64-comps.xml repodata/

[root@station centos6]# createrepo  -g repodata/38b60f66d52704cffb8696750b2b6552438c1ace283bc2cf22408b0ba0e4cbfa-c7-x86_64-comps.xml  .
[root@station centos6]# mkisofs -R -J -T -v --no-emul-boot --boot-load-size 4 --boot-info-table -V "centos 6 boot" -b isolinux/isolinux.bin -c isolinux/boot.cat -o /var/www/html/iso/c66.iso /centos6
#修改linuxiso下的linuxiso.cfg文件ks.cfg文件
#记得ks.cfg有reboot行

参考1

参考2

2018-01-11-练习自动化安装

参考1

参考2

2018-01-13-练习ansible

2018-01-15-练习ansible2

2018-01-17-练习rsync

2018-01-19-练习dns

2018-01-20-练习mysql安装

2018-01-23-练习mysql

2018-01-25-练习httpd

2018-01-27-练习lamp

2018-01-29-练习日志

练习题2月

2018-02-03-练习网络文件共享2

练习1-建立samba服务器


建立samba服务器,共享目录为/data,要求如下: 1 共享名字为shared,工作组为linuxpanda。 2 添加组develop,添加用户panda1,panda2,panda3,其中panda1,panda以develop为附加组,

panda3不属于develop组,密码 同用户名

3 添加samba用户,panda1,panda2,panda3密码都是panda 4 此samba共享shared仅允许develop组具有写权限,其他用户只能只读访问 5 此samba共享服务仅仅运行来自192.168.46.0、24的网络主机访问。

# 添加组和用户
[root@centos-155 home]# groupadd develop
[root@centos-155 home]# useradd -G develop panda1
[root@centos-155 home]# useradd -G develop panda2
[root@centos-155 home]# useradd panda3
# 配置系统密码和samba密码
[root@centos-155 home]# echo panda1  |passwd --stdin panda1
[root@centos-155 home]# echo panda2  |passwd --stdin panda2
[root@centos-155 home]# echo panda3  |passwd --stdin panda3
[root@centos-155 home]# smbpasswd  -a panda1
[root@centos-155 home]# smbpasswd  -a panda2
[root@centos-155 home]# smbpasswd  -a panda3
# 创建目录设置权限
[root@centos-155 home]# mkdir /data
[root@centos-155 home]# setfacl -R -m "g:develop:rwx" /data
# 编辑配置文件
[root@centos-155 home]# systemctl restart smb nmb
[root@centos-155 home]# netstat -tunlp |grep mb
# 另一个机器查看
[root@centos-152 yum.repos.d]# smbclient -L  192.168.46.155 -U panda1
Enter SAMBA\panda1's password:
Domain=[CENTOS-155] OS=[Windows 6.1] Server=[Samba 4.6.2]

    Sharename       Type      Comment
    ---------       ----      -------
    print$          Disk      Printer Drivers
    pub             Disk      this is samba pub for windows
    shared          Disk      this this test
    IPC$            IPC       IPC Service (Samba 4.6.2)
    panda1          Disk      Home Directories
Domain=[CENTOS-155] OS=[Windows 6.1] Server=[Samba 4.6.2]

    Server               Comment
    ---------            -------

    Workgroup            Master
    ---------            -------
    SAMBA                CENTOS-155
    WORKGROUP            DESKTOP-31DI5AI

# 挂载
[root@centos-152 yum.repos.d]# mkdir /mnt/panda1
[root@centos-152 yum.repos.d]# mount -o username=panda1,password=oracle //192.168.46.155/shared /mnt/panda1/
# 尝试创建一个文件
[root@centos-152 panda1]# mkdir a
[root@centos-152 panda1]# ls
a  新建文本文档.txt

# 挂载2
[root@centos-152 yum.repos.d]# mkdir /mnt/panda3
[root@centos-152 panda1]# mount -o username=panda3,password=oracle //192.168.46.155/shared /mnt/panda3/
[root@centos-152 panda1]# cd /mnt/panda3
[root@centos-152 panda3]# touch a.txt
touch: cannot touch ‘a.txt’: Permission denied

练习题3月

2018-03-01-练习防火墙

练习1-防火墙入门练习

要求如下:

说明:以下练习INPUT和OUTPUT默认策略均为DROP
1、限制本地主机的web服务器在周一不允许访问;新请求的速率不能超过100个每秒;web服务器包含了admin字符串的页面
不允许访问;web服务器仅允许响应报文离开本机
2、在工作时间,即周一到周五的8:30-18:00,开放本机的ftp服务给172.16.0.0网络中的主机访问;数据下载请求的次数
每分钟不得超过5个
3、开放本机的ssh服务给172.16.x.1-172.16.x.100中的主机,x为你的学号,新请求建立的速率一分钟不得超过2个;仅
允许响应报文通过其服务端口离开本机
4、拒绝TCP标志位全部为1及全部为0的报文访问本机;
5、允许本机ping别的主机;但不开放别的主机ping本机
# 特殊,我这里使用xshell远程,考虑到后面需要设置默认为drop,所以需要放行下192.168.46.1的所有
[root@centos-151 ~]# iptables -A INPUT -s 192.168.46.1/32 -j ACCEPT
[root@centos-151 ~]# iptables -A OUTPUT -d 192.168.46.1/32 -j ACCEPT
[root@centos-151 ~]# iptables -P INPUT DROP
[root@centos-151 ~]# iptables -P INPUT DROP

# 第一条
[root@centos-151 ~]# iptables -A INPUT -d 192.168.46.151 -p tcp --dport 80 -m state --state  NEW  -m limit --limit 100/second  -m time ! --weekdays 1 -j ACCEP
[root@centos-151 ~]# iptables -A INPUT -d 192.168.46.151 -p tcp --dport 80 -m state --state ESTABLISHED  -j ACCEPT
[root@centos-151 ~]# iptables -A OUTPUT -s 192.168.46.151 -p tcp --sport 80 -m string --algo bm ! --string "admin" -j ACCEPT
# 第二条
[root@centos-151 ~]# iptables -A INPUT -s 192.168.46.0/24 -d 192.168.46.151 -p tcp --dport 21 -m state --state NEW,ESTABLISHED    -m time --weekdays 1,2,3,4,5 --timestart 00:30:00 --timestop 10:00:00
[root@centos-151 ~]# iptables -A INPUT -s 192.168.46.0/24 -d 192.168.46.151 -p tcp --dport 21 -m state --state  RELATED -m limit --limit 5/min -j ACCEPT
# 看了网络的, 有人在这里添加了一条方向established的。 添不添加看你情况。
# 如果不添加的话, 原有的连接在指定的时间范围内, 一直连接者, 时间到了禁止的点了,就直接拒绝了。
# 如果到添加的话, 原有连接还可以一直使用,如果里面在断开就没法连接了。
[root@centos-151 ~]# iptables -A OUTPUT -d 192.168.46.0/24 -s 192.168.46.151 -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT

# 第三条

[root@centos-151 ~]# iptables -A INPUT -p tcp --dport 22 -m iprange --src-range 192.168.46.160-192.168.46.200 -d 192.168.46.151 -m state --state NEW -m limit --limit 2/min -j ACCEPT
[root@centos-151 ~]# iptables -A INPUT -p tcp --dport 22 -m iprange --src-range 192.168.46.160-192.168.46.200 -d 192.168.46.151 -m state --state ESTABLISHED  -j ACCEPT
[root@centos-151 ~]# iptables -A OUTPUT -p tcp --sport 22 -m iprange --dst-range 192.168.46.160-192.168.46.200 -s 192.168.46.151 -m  state --state ESTABLISHED -j ACCEPT


# 第四条
# 默认规则是drop, 我们前面已经添加了几个accept, 这个要求是拒绝非正常的数据包,需要放到相对前面的,至少不能放到那几个accept的后面。
[root@centos-151 ~]# iptables -I INPUT 1  -d 192.168.46.151 -p tcp --tcp-flags ALL ALL -j DROP
[root@centos-151 ~]# iptables -I INPUT 1  -d 192.168.46.151 -p tcp --tcp-flags ALL NONE -j DROP

# 第五条,这里有个问题, 本机ping 本机192.168.46.151的时候无法ping通。  当然可以考虑-s ,-d 对ip详细限制下。
[root@centos-151 ~]# iptables -A INPUT -p icmp --icmp-type 0 -d 192.168.46.151 -j ACCEPT
[root@centos-151 ~]# iptables -A OUTPUT -p icmp --icmp-type 8 -s 192.168.46.151 -j ACCEPT

# 最终的规则查看

[root@centos-151 ~]# iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT DROP
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP
-A INPUT -s 192.168.46.1/32 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --dport 80 -m state --state NEW -m limit --limit 100/sec -m time --weekdays Tue,Wed,Thu,Fri,Sat,Sun --datestop 2038-01-19T03:14:07 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --dport 80 -m state --state ESTABLISHED -j ACCEPT
-A INPUT -s 192.168.46.0/24 -d 192.168.46.151/32 -p tcp -m tcp --dport 21 -m state --state NEW,ESTABLISHED -m time --timestart 00:30:00 --timestop 10:00:00 --weekdays Mon,Tue,Wed,Thu,Fri --datestop 2038-01-19T03:14:07
-A INPUT -s 192.168.46.0/24 -d 192.168.46.151/32 -p tcp -m tcp --dport 21 -m state --state RELATED -m limit --limit 5/min -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --dport 22 -m iprange --src-range 192.168.46.160-192.168.46.200 -m state --state NEW -m limit --limit 2/min -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m tcp --dport 22 -m iprange --src-range 192.168.46.160-192.168.46.200 -m state --state ESTABLISHED -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A OUTPUT -d 192.168.46.1/32 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p tcp -m tcp --sport 80 -m string ! --string "admin" --algo bm --to 65535 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -d 192.168.46.0/24 -p tcp -m tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p tcp -m tcp --sport 22 -m iprange --dst-range 192.168.46.160-192.168.46.200 -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p icmp -m icmp --icmp-type 0 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p icmp -m icmp --icmp-type 8 -j ACCEPT

练习1-防火墙实用练习

要求如下:

1 实现主机防火墙:
放行telnet, ftp, web服务
放行samba服务
放行dns服务(查询和区域传送)

2 实现网络防火墙:
放行telnet, ftp, web服务
放行samba服务
放行dns服务(查询和区域传送)

网络防火墙的我这里不做了 , 主要是在forward链上操作。 一般都是买的专业的硬件防火墙, 这里只做主机防火墙的实验。

# 上面实验有配置,考虑不影响下面的配置, 我这清理下。
[root@centos-151 ~]# iptables -P INPUT ACCEPT
[root@centos-151 ~]# iptables -P OUTPUT ACCEPT
[root@centos-151 ~]# iptables -F
[root@centos-151 ~]# iptables -nvL
Chain INPUT (policy ACCEPT 36 packets, 2448 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 8 packets, 672 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 16 packets, 1520 bytes)
pkts bytes target     prot opt in     out     source               destination

# 特殊,我这里使用xshell远程,考虑到后面需要设置默认为drop,所以需要放行下192.168.46.1的所有
[root@centos-151 ~]# iptables -A INPUT -s 192.168.46.1/32 -j ACCEPT
[root@centos-151 ~]# iptables -A OUTPUT -d 192.168.46.1/32 -j ACCEPT
[root@centos-151 ~]# iptables -P INPUT DROP
[root@centos-151 ~]# iptables -P INPUT DROP



# 主机防火墙

[root@centos-151 yum.repos.d]# yum install telnet-server vsftpd httpd samba bind

[root@centos-151 yum.repos.d]# systemctl start telnet.socket

##  telnet,ftp,web
[root@centos-151 ~]# iptables -R INPUT 2 -p tcp -m multiport --dports 23,80,443,21 -d 192.168.46.151 -j ACCEPT
[root@centos-151 ~]# iptables -R OUTPUT 2 -p tcp -m multiport --sports 23,80,443,21 -s 192.168.46.151 -j ACCEPT
[root@centos-151 ~]# iptables -I INPUT 2 -m state --state ESTABLISHED,RELATED -s 192.168.46.151  -j ACCEPT
[root@centos-151 ~]# iptables -I OUTPUT 2 -m state --state ESTABLISHED,RELATED  -d 192.168.46.151  -j ACCEPT


# 在152上测试下telnet配置
[root@centos-152 ~]# telnet 192.168.46.151
Trying 192.168.46.151...
Connected to 192.168.46.151.
Escape character is '^]'.
Kernel 3.10.0-693.el7.x86_64 on an x86_64
centos-151 login: zhao
Password:
Last login: Sat Mar  3 13:14:37 from ::ffff:192.168.46.1
[zhao@centos-151 ~]$ logout

# 在152上测试下web配置
[root@centos-152 ~]# curl 192.168.46.151
www

# 在152上测试下ftp配置
[root@centos-152 ~]# ftp 192.168.46.151
Connected to 192.168.46.151 (192.168.46.151).
220 (vsFTPd 3.0.2)
Name (192.168.46.151:root): ftp
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
227 Entering Passive Mode (192,168,46,151,153,42).
150 Here comes the directory listing.
drwxr-xr-x    2 0        0               6 Aug 03  2017 pub
226 Directory send OK.
ftp> quit
221 Goodbye.


# 放行samba服务

[root@centos-151 ~]# vim /etc/samba/smb.conf
[root@centos-151 ~]# tail -5 /etc/samba/smb.conf

[test]
    comment =test
    path = /tmp
    public = Yes
    read only = YES

[root@centos-151 ~]# systemctl start smb
[root@centos-151 ~]# systemctl start smb nmb
[root@centos-151 ~]# netstat -tunlp |grep mb
tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      18820/smbd
tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      18820/smbd
tcp6       0      0 :::139                  :::*                    LISTEN      18820/smbd
tcp6       0      0 :::445                  :::*                    LISTEN      18820/smbd
udp        0      0 172.18.255.255:137      0.0.0.0:*                           18832/nmbd
udp        0      0 172.18.46.151:137       0.0.0.0:*                           18832/nmbd
udp        0      0 192.168.46.255:137      0.0.0.0:*                           18832/nmbd
udp        0      0 192.168.46.151:137      0.0.0.0:*                           18832/nmbd
udp        0      0 0.0.0.0:137             0.0.0.0:*                           18832/nmbd
udp        0      0 172.18.255.255:138      0.0.0.0:*                           18832/nmbd
udp        0      0 172.18.46.151:138       0.0.0.0:*                           18832/nmbd
udp        0      0 192.168.46.255:138      0.0.0.0:*                           18832/nmbd
udp        0      0 192.168.46.151:138      0.0.0.0:*                           18832/nmbd
udp        0      0 0.0.0.0:138             0.0.0.0:*                           18832/nmbd
# 还需要添加用户, 这里我就不添加了。 自行添加。 然后在152的机器上测试挂载即可。
[root@centos-152 ~]# mount -o username=smbuser //192.168.46.151/test /mnt/test
Password for smbuser@//192.168.46.151/test:  ******
[root@centos-152 ~]# ll /mnt/test
total 24
drwx------ 3 root root    0 Mar  3 11:15 systemd-private-63249d2097d14289a36dc98acf680875-httpd.service-J1rUuI
drwx------ 3 root root    0 Mar  3 11:18 systemd-private-63249d2097d14289a36dc98acf680875-mariadb.service-gPUdp0
drwx------ 3 root root    0 Feb 18 19:47 systemd-private-63249d2097d14289a36dc98acf680875-vgauthd.service-IO27zv
drwx------ 3 root root    0 Feb 18 19:47 systemd-private-63249d2097d14289a36dc98acf680875-vmtoolsd.service-Mw5wCZ
drwx------ 3 root root    0 Feb 18 18:50 systemd-private-c39b1eee959e41999dee80095c373d20-vgauthd.service-zw95HP
drwx------ 3 root root    0 Feb 18 18:50 systemd-private-c39b1eee959e41999dee80095c373d20-vmtoolsd.service-ntZbfa
-rw------- 1 root root  242 Feb 18 18:59 yum_save_tx.2018-02-18.18-59.UD0ejW.yumtx
-rw------- 1 root root  242 Feb 18 19:00 yum_save_tx.2018-02-18.19-00.o7GAer.yumtx
-rw------- 1 root root 4611 Feb 25 09:45 yum_save_tx.2018-02-25.09-45.cs4qy6.yumtx
-rw------- 1 root root  237 Mar  3 13:07 yum_save_tx.2018-03-03.13-07.wruNr0.yumtx
-rw------- 1 root root  378 Mar  3 13:10 yum_save_tx.2018-03-03.13-10.rQvpAJ.yumtx


## dns

[root@centos-151 ~]# netstat -tunlp  |grep named
tcp        0      0 172.18.46.151:53        0.0.0.0:*               LISTEN      18881/named
tcp        0      0 192.168.46.151:53       0.0.0.0:*               LISTEN      18881/named
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN      18881/named
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN      18881/named
tcp6       0      0 ::1:953                 :::*                    LISTEN      18881/named
udp        0      0 172.18.46.151:53        0.0.0.0:*                           18881/named
udp        0      0 192.168.46.151:53       0.0.0.0:*                           18881/named
udp        0      0 127.0.0.1:53            0.0.0.0:*                           18881/named

[root@centos-151 named]# iptables -A INPUT -d 192.168.46.151 -p tcp  -m multiport --dports 53,953 -j ACCEPT
[root@centos-151 named]# iptables -A INPUT -d 192.168.46.151 -p udp   --dport 53 -j ACCEPT
[root@centos-151 named]# iptables -A OUTPUT -s 192.168.46.151 -p tcp -m multiport --sports 53,953 -j ACCEPT
[root@centos-151 named]# iptables -A OUTPUT -s 192.168.46.151 -p udp --sport 53 -j ACCEPT

# 152测试
[root@centos-152 ~]# dig www.linuxpadna.tech @192.168.46.151

; <<>> DiG 9.9.4-RedHat-9.9.4-50.el7 <<>> www.linuxpadna.tech @192.168.46.151
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 1923
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

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

;; Query time: 2 msec
;; SERVER: 192.168.46.151#53(192.168.46.151)
;; WHEN: Sat Mar 03 13:55:37 CST 2018
;; MSG SIZE  rcvd: 48


# 最终规则查看

[root@centos-151 named]# iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT DROP
-A INPUT -s 192.168.46.1/32 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m multiport --dports 23,80,443,21 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m multiport --dports 139,445 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p udp -m udp --dport 137:138 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p tcp -m multiport --dports 53,953 -j ACCEPT
-A INPUT -d 192.168.46.151/32 -p udp -m udp --dport 53 -j ACCEPT
-A OUTPUT -d 192.168.46.1/32 -j ACCEPT
-A OUTPUT -d 192.168.46.151/32 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p tcp -m multiport --sports 23,80,443,21 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p tcp -m multiport --sports 139,445 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p udp -m udp --sport 137:138 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p tcp -m multiport --sports 53,953 -j ACCEPT
-A OUTPUT -s 192.168.46.151/32 -p udp -m udp --sport 53 -j ACCEPT

2018-03-11-练习nginx.rst

练习1-nginx

1、nginx虚拟主机配置

虚拟主机配置

2、实现lnmp,提供多个虚拟主机http, 提供wordpress, 提供pma

练习2-nginx


1、nginx–> AMPs(wordpress) 2、nginx–> FPMs(wordpress) 3、自定义错误404和5xx错误页,文本静态内容传输压缩 4、实现动静分离:动态资源存储一组服务器、图片资源存在一组服务器、静态的文本类资源存储在一组服务器

nginx–>images servers ( imgs.magedu.com) location ~* .(jpg|png|gif|jpeg)$ { … } nginx–>dynamic content servers (shop.magedu.com) location ~* .php$ { … }

实验:rewrite 实现http跳转到https

实验:防盗链

实验:动静分离

练习题4月

课堂笔记11月

2017-11-20

上节课回顾

本节内容

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内置有程序

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设置

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:退出历史搜索

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:退出

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

查看设备文件系统和类型

[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相关的配置文件

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

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 : 只给目录权限, 文件不添加。

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:合并到一行。

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$:删除并修改

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:清空一个位置变量

2017-11-24

上节课回顾

本节内容

[]里面的测试都需要加个""。
=~使用扩展的表达式

双中括号里面才支持扩展正则表达式
==支持不支持正则, 支持glob

[ -v  var1 ]: 测试变量是否没有赋值

()是一个子进程执行
{}是一个函数执行

-r:实际的上是否有读取权限


read 没有设置,存放在REPLY中

echo $-: himBH

read -s:隐藏输入
read -n:只能输入指定字符数量

-samefile : 相同文件, 也就是硬链接的文件


$-:
    h: hash
    i:  交互模式
    m: job监控
    B: 大括号扩展
    H: 历史可用

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:删除第一个换行符号文本, 不读取继续循环

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

课堂笔记12月

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:裸设备

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: 查找是不是挂载点

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

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

2017-12-12

上节课回顾

本节内容

::

无类域间路由, 网络ID不按照整8位划分

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

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

进程状态:
         运行
         就绪
         可中断睡眠
         不可中断睡眠
         停止
         僵死

 进程类型:
         守护进程
         前台进程
         后台进程

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都不存在:都不能访问的。

2017-12-20

上节课回顾

本节内容

while
unitl
post:power-on-self-test

ntsysv
chkconfig  默认是2345

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

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 enter\n"}'

640*480

/proc/cmdline

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

2017-12-29

上节课回顾

本节内容

time cmd:计算命令的执行时间

课堂笔记1月

2018-01-02

上节课回顾

本节内容

systemd
/etc/systemd/system/
/lib/systemd/system/
sysv
/etc/init.d/

systemctl -l status httpd:

service name condrestart ==> systemctl try-restart name.service

systemctl resload-or-restart name.service
systemctl reload-or-try-restart name.service

systemctl mask(unmask) name.service

systemctl list-units -t service -a

systemctl daemon-reload

systemctl isolate graphical.target

systemctl resuce


Unit片段
Description
After
Before
Requires
Wants
Conflicts
保密性
完整性
可用性
可控制性
不可否认性

telnet ip 25
helo a.com
mail from:god@heaven.com
rcpt to:root
data
subject: hello
I miss you
.
quit


md5sum --check f1.sh f1.sh.md5

gpg -c f1.sh
gpg -d f1.sh.gpg

2018-01-03

上节课回顾

systemd

本节内容

openssl enc -des3 -a -in a.file -out a.file.des3

openssl dgst -md5 a.file

rand
genrsa -out centos6.key 1024

2018-01-05

上节课回顾

搭建私有ca的主要过程

(umask 066 ; openssl genrsa -out /etc/pki/CA/private/cakey.pem)
openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650
touch 01 >/etc/pki/CA/serial
touch /etc/pki/CA/index.txt

(umask 066; openssl genrsa -out http.pem)
openssl req -new -key http.pem -out http.csr

scp

openssl ca -in http.csr -out /etc/pki/CA/certs/http.crt -days 365

scp

本节内容

rsync

rsync -av /etc/sysconfig/ remote:/app
rsync -av /etc/sysconfig remote:/app

pssh

pssh -H 172.18.46.6 -i getenforce
pssh -H "172.18.46.6 ip2" -i getenforce
pssh -h ip.txt -i getenforce

-o 指定一个目录, 每个ip会生成一个文件,存储信息。

后续命令可以使用双引号。

aide

aide --init

aide --check

visudo -c

visudo -f file

sudoedit

2018-01-08

上节课回顾

sudo
sudoedit

本节内容

hosts.allow
hosts.deny

centos6不支cidr

tcpmatch -d sshd 192.168.27.7

pam文件
/lib64/security/
/etc/security/
/etc/pam.conf
/etc/pam.d/

application type control module-path arguments

type control module-path arguments

required:如果失败就game over
requisite:如果失败就exit
sufficient: 一票通过
option:没有影响,仅供参考

pam_nologin
pam_securitytty
pam_limits

domain  type   item value
ftp     soft    nproc   20


自动化系统安装

检查光盘
运行anaconda
欢迎界面
语言
键盘
存储
存储警告初始化
hostname
配置网络
时区
root密码
分区信息
grub配置
软件包
reboot


vim-enhanced

system-config-kickstart

linux ks=ftp://172.18.0.6/pub/ks6-mini.cfg ip=172.18.46.100 netmask=255.255.0.0

[development]

syslinux

isohybrid boot.iso


删除TRANS.TBL
删除repodata,保留xm文件
create -g repodata/43*.xml ./
mkdir ksdir
cp ks.conf ksdir/
修改linuxiso.cfg
制作iso

2018-01-10

上节课回顾

tcpdmatch:测试当前目录的tcpwarp的配置文件的。

本节内容

::

bootp: boot protocal mac与ip静态绑定

dhcp 67,客户端68

discover offer request ack nak recline release inform

跨网段dhcp rfc 1542 中继

dhcp,dnsmasq,

dhcp服务 安装, rpm -ql查看 cp配置文件

dhcpclient前台查看

service dhcpd configtest

tfp: 69端口

eula –agreed

htdigest -c /etc/cobbleer/users.digest Cobbler cobbleradmin

ansible

laas,paam,saas

ace: ali cloud en

crm

本地部署: 基础设施即服务iaas 平台即服务paas 软件即服务saas

2018-01-12

上节课回顾

1 httpd,tfpt-server syslinux
2 vim dhcpd.conf
3. start service
4. /var/www/html/centos/{6,7}
5. kickstart
6. /var/lib/tfpboot, vmlinuz,initrd,img,menu,c32,pxelinux.0 pxelinux.cfg/default
7.

本节内容

exec bash

host_key_checking = False
ansible -l
ansible -M ping


update_cache=yes

ansible ansible-vault

2018-01-15

上节课回顾

setup 包含主机信息

tags
notify

本节内容

ansible-playbook -e pkname=vsftpd

vars

定义主机的时候定义变量

j2 文件使用setup里面的变量

when: ansible_distribution_major_version=="6"

with_items:
   - item1
     item2

hping3

{% for i in list %}
{% endfor %}

{%if i is undefined %}
{%endif%}

tags: [ 'nginx' , 'web' ]

memcached : 11211 端口

dns: domain name service
dns: 53端口。

fqdn: www.baidu.com  full q domain name
www: 主机名或者别名
baidu.com 域名
url : 统一资源定位符

正向: fqdn->ip
反向: ip->fqdn

nis:

bind
isc

2018-01-17

上节课回顾

本节内容

bind 服务名named
53端口。

 /etc/rc.d/init.d/named
 /usr/lib/systemd/named.service

/etc/named.conf
/etc/named.rfc1992.zones

/var/named/zone_name.zone

soa: 起始授权记录
ns:
a:
aaaa:
ptr:
cname:
srv:
txt:

优先级: 数字越低优先级越高

host www.suhu.com

smtp
pop

name ttl IN rr_type value

admin@magedu.com 写成admin.magedu.com

type ,filename

$TTL 1D ,默认是秒单位

serial
refresh
retry
expire: 从服务器的持续时间
minimum: 不成功的返回结果持续时间。

rndc reload: 重新加载dns的配置文件

aa权威服务器。

localhost: 在dns中为所有ip

named-checkconf 检查错误

name-checkzone 检查区域 name-checkzone linuxpanda.tech /var/named/linuxpanda.tech

any: 任意主机
192.168.27.0/24;172.18.0.0/16

host www.linuxpanda.tech 192.168.0.1
dig www.linuxpanda.tech @192.168.0.1

nslookup : server

dig -x

dig -t

dig -t axfr

nslookup : set q=NS

$generate 1-254 HOST$ A 1.2.3.$

linuxpanda.tech
xxxxx.linuxpanda.tech

allow-transfer {    }
rndc querylog
rndc reload
rndc status

dns安全, 子域授权需要设置

rndc flush

2018-01-17

上节课回顾

::

主 从 子域

本节内容

dns acl :
acl beijingnet {192.168.46.0/24;};

match-clietnos{beijingnet;};

dig  . a.root-server.net. >> named.ca

mysql

acid

3306,
1521oralce
1433,mssqlserver

disable_user_list

myisam不支持事务的。
innodb支持事务的。

select user();


vim /etc/gconf/gconf.xml.defaults/%gconf-tree.xml
disable_user_list

2018-01-22

上节课回顾

本节内容

mysql_install_db
mysql -e 'show variables like "basedir" ;'

port=3307

select user,password,host from mysql.user;

update mysql.user set password=password("root") ;

drop user ''@localhost;

flush privileges;

select user();
skip-grant-tables

delete from mysql.user where  host="centos7.localdomain"

create usr wang@'192.168.46.1' identified by 'oracle';

select * from mysql.user/G;

注释:
--
/* */
#
show tables

create database if not exists panda.
show create database panda.
show character set

select table status from mysql;
show engines;

create table newt1 select * from t1;

insert into nett2 select * from t1;

show columns from t1;
truncate table t1;

explain

show indexes from students

drop index index_name on t1;

values (v1,v2), (v3,v4);

insert into t1 set id=5,name="zhaojiedi";

--safe-updates
-U

order by -col1 desc;

limit 3

litmit 3,4 ; 跳过3个取4个。

between 10 and 20 ; 左封闭右封闭

2018-01-24

上节课回顾

mysql多实例
连接

本节内容

show processlist

socket: ip+port

sock_stream
sock_dgram
sock_raw

hyper text transfer protocol

mime: multipurepose internet mail extension

mailcap:/etc/mime.types

curl http://192.168.46.7/index.html -I

url: uniform resorce locator
urn uniform resource name

pv访问量
uv独立访客

ServerRoot


http -t

httpd-tools

ab -c 2000 -n 10000 http://www.baidu.com

2018-01-26

上节课回顾

发请求
dns
处理请求
访问资源
构建响应
响应
日志记录

本节内容

aliasmatch ^/imgs(/.*)+$ "/data/img/$1"

httpasswd -c .httpusers http1

authtype base
authname  "admini "
authuserfile
require user  http1


allowoverride all

satisfy all|any

<ifmodule module_userdir>
  userdir abled
  userdir publicweb
</ifmodeule>

setfacl -m "u:apache:x" ~/zhaojiedi/

serversignature

servertype inetd,standalone

namevirtualhost *:80


200
301
302
304
401
403
404
500
502
503
504

combined

mod mod_deflate

openssl x509 -in a.crt --noout --text

2018-01-26

上节课回顾

本节内容

proxypass "/" "http://www.example.com/"
proxypassreverse "/" "http://www.example.com/"


proxy_httpmodule

httpd -t

apache portable run-time library

lamp

zend->opcode
#
;

apc

xcache

2018-01-26

上节课回顾

本节内容

日志

sysklogd: syslogd ,klogd
rsyslog:centos7下,多线程, 支持tcp

/var/log/message
时间,主机,进程,事件描述

man logger

auth,authpriv,cron,daemon,ftp,kern,lpr,mail,news,security,user,uucp,
syslog,local0-local7

alert,critical,debug,emerg,err,panic,warning warn,error,alert,emerg

/etc/rsyslog.conf

设施.级别;
-/var/log/maillog : -代表异步写入。
*代表登陆到主机的所有用户

logger -p local0.info "this is a test  log"

启动日志服务器
udp和514行启用

远程主机 @ip
@走udp,@@走tcp

|command

btmp
secure
lastb:只记录失败的。
wtmp
last: 只记录成功的

lastlog
dmesg 内核发生的事件

ftp -A 主动模式, -p被动模式

ftp状态码:
125数据连接打开
200命令ok
230登陆成功
425不能打开数据连接
530不能登陆

pasv_min_port=6000
pasv_max_port=6010

修改时间为北京时间
use_localtime=yes

课堂笔记2月

2018-02-02

上节课回顾

本节内容

tcpdump -nn -i eth0 -X port 21

make vsftpd.pem

2018-02-07

上节课回顾

本节内容

view虚表

通过视图可以改表的,但是统计的视图不可以修改。

mysql options
server system variable
server status variable

show warnings

锁
事务
mvvc
聚集索引

sql_no_cache

explain

use_stat

show index_statistics;

optimize table tb_name

lock table tb_name

unlock tables

flush tables tb_name

2018-02-09

上节课回顾

本节内容

log_bin
sql_log_bin


show binary logs ;
show master logs ;
show master status ;

mysqlbinlog -d dbname

gtid : global transation id

purge binary logs to 'mariadb-log-0000003'

reset master to 1 ;

flush logs ;

mysqldump ;

mysqlbackup

2018-02-23

上节课回顾

本节内容

主从复制,从去还原,使用--master-data=1

mysqldump -F 刷新日志

flush logs 属性日志

log-bin 启用日志

innodb_file_per_table 每个表单独文件

--single-transaction 单事务的

-d 备份表结构, -t 只有数据

--flush-privileges

-f  忽略sql错误,继续执行

--quick 配合--single-transaction 使用

flush tables with read lock 给全局读锁。

mysqlbinlog --start-position=245

set sql-log_bin 0

unlock tables ;

nouuid,norecovery

innobackupex --apply-log /app/2018-02-23_11-55-57/

innobackupex --copy-back /app/2018-02-23_11-55-57/

chown mysql.mysql /var/lib/mysql

--readonly

alter table student discard tablespace ;
alter table student import tablespace;

start slave
start slave io_thread
start slave sql_thread

2018-02-24

上节课回顾

本节内容

replaction slave

dump: 二进制日志发送
io: 接受二进制日志
sql: 执行sql


change master to

show slave status

默认中从是异步的,主成功后给客户返回成功,然后在复制给从。

确保传送给1个从就返回客户端。

show plugs  查看插件信息

show global variables like '%semi%'

openssl req -newky rsa:1024 -nodes -days 365 -keyout master.key > master.csr

required ssl 必须加密


ids : 入侵监测与管理系统
ips: 入侵防御系统
firewall: 防火墙


dmz: 非军事化区
军事化区

2018-02-26

上节课回顾

本节内容

netfilter是组件,内核自带的。

iptables是配置命令

raw,mangle,nat,filter

ping 最大值65507

--line-number

iptable -D INPUT 1

iptables -S

基本的:
s
d
p
i
o

man iptables-extension
--syn

iptables-restore < /etc/sysconfig/iptables

2018-02-28

上节课回顾

本节内容

iptables -t nat -A PREROUTING -d 172.16.100.10 -p tcp --dport 80 -j REDIRECT --to-ports 8080

端口转发

memcached
redis

heartbeat
cman +rgmanager
coresync pacemaker

keepalived vrrp协议。

argignore

arp

课堂笔记3月

2018-03-02

上节课回顾

本节内容

lc
wlc
sed
nq

chrony 提供时间服务,端口udp323

123

2018-03-06

上节课回顾

本节内容

nginx的内置io模型是非常有优势的。

1,3,10,

perfork
worker
event

pio: 程序输入输出模型
dma: 直接内存访问

linux + nginx + mariadb + python

nginx -t 检查配置文件

nginx -s stop

ps axo cmd,pid,psr |grep nginx

2018-03-08

上节课回顾

本节内容

sni support enabled 才可以多虚拟主机多个证书。

2018-03-10

上节课回顾

本节内容

weight权重
max_conns最大并发限制
backup 备用
down 不可用


lvs的调度算法。


一致性hash算法。

src/http/ngx_http_herader

2018-03-12

上节课回顾

本节内容

haproxy
envoy,traefik,nginx
ceph,redis
puppet

分布式应用架构
restful表征状态转移
microservices微服务

蓝绿发布:
灰度发布:
金丝雀发布:

发布,变更,故障处理。

人工,版本控制,配置中心

结构化数据,非结构化数据,半结构化数据

NOSQL存储系统, redis

tps每秒的事务数量

redis可以缓存数据

vanish可以缓存网页

绝不允许没有监控的服务器上限。

sre: 站点可靠性工程师

qa质量保证。

版本控制系统。

ansible小规模的系统,puppet,saltstack等重量级的

分布式配置中心,

4层调度和7层调度。

https:
贵,慢
四层调度,后端服务器都要配置证书。

pv 2000-3000之间基本nginx就可以了。

haproxy

bind :80,:443
bind ip:80,
bind /var/run/s.sock

ipc 进程间通信

balance algo argv

roundrobin 轮调

支持权重的动态调正

会话追踪
会话粘性, 会话复制集群,集中会话。

网络层监测
传输层检查
应用层监测


统计页面

acl可以同名, 表示或者关系。

acl

2018-03-14

上节课回顾

本节内容

 iaas基础架构及服务。
 paas平台及服务
 saas软件及服务

 cdn , content deviled network

 gslb 全局服务复杂均衡


 cname解析。

 php 模块方式
 fpm 方式运行

 nginx + php

 if-modified-since
 3.4 not modified

 etag 扩展标签

 if-none-match

 squid
 varnish

 ipfs

 manager ,cacher 进程
 varnish_listen_port 6081


 varnish_reload_vcl

 varnishlog.service
 varnishlog.service
 varnishncsa.servee

 param.show



有限状态机

vcl_init
vcl_finit

 vcl.load test1  default.vcl
 vcl.use test1

2018-03-17

上节课回顾

本节内容

jvm java虚拟机

tomcat 是java的参考实现。

jsp java server page

gc 垃圾收集器 。

分布式存储, 分兼容文件系统和不兼容文件系统。

xml,json,yaml

mangdb 文档存储,

开发环境, 测试环境, 生成环境。

servlet 分离工作

j2se
j2ee
j2me

tomcat

test.jsp -> jasper-> test.java -> servlet -> test.class -> jvm

work目录, 用于存储编译好的结果。

engine

jvm加载类  classloader类加载器。

引擎, 连接器。

tomcat server可以有多个service,每个service只有一个引擎。

java 1.6.0,1.7.0,1.8.0
多版本并存,使用alternatives调整默认的版本使用。

java一次编译,到处运行。

tomcat-docs-w
tomcat ebapp
tomcat-lib
tomcat-admin-webapps


index.jsp index.html

web-inf 当前webapp的私有资源路径。

jar,当前webapp提供的类

.war 打包的站点应用程序
.jar  ejb的类打包文件
.rar  资源适配器类打包文件
.ear  企业级别webapp



直接访问tomcat
调度过来到tomcat的

httpd支持http,ajp等连接方式。

proxy_ajp
mod_jk
porxy_http

ajp 8009

set,add,replace,append,prepend,class
get,gets
其他

2018-03-19

上节课回顾

本节内容

 jsp,php,asp

 Jetty,Jboss



msm memache session manager

2018-03-21

上节课回顾

本节内容

存储系统是核心的。

基础支撑层, sa
存储系统   dba
应用运维
业务运维

ioe
aix
oracle
emc

节点即冗余
分片的分布式架构

列存储
文档存储 elastic,mongodb
kv存储   dynamodb,riak,redis
图式存储  neo4j,titan,
混合模式
对象数据库
xml数据库
多维数据库
多值数据库
时间序列或者流存储



-a mima

auth mima

缓存的时候可以使用lru

存储系统

2018-03-23

上节课回顾

本节内容

流处理, spark


采集数据
存储数据
数据可视化
报警系统

snmp simple network management protocol
  c/s:
  v1,v2,v3

ssh

agent

grafana


cacti

zabbix: 独立完整的系统

promethus:
cadvisor,heapster,influxdb,grafana

网络发现, 模板

2018-03-25

上节课回顾

本节内容

2018-03-27

上节课回顾

本节内容

cpu,ram,io

内核模式,特权指令只能内核运行。

mmu: 内存管理单元

tlb: 转化后援器

bt 二进制转化

完全虚拟化
准虚拟化

ept: 扩展的页表

grp : 通用路由封装

cpu:
    bt
    hvm
io:

type-II

type-I

hypervisor layer : 有操作系统和虚拟功能。

vmm: 虚拟机管理端。

xen,kvm,virtualbox 主机虚拟化

cpu和内存, 虚拟机来虚拟io


privileged domain
unprivileged domain

kvm kernel-base vm

支不支持容器是内核的问题。


容器引擎runC
镜像格式标准

openvz


cirros

ctrl + }

2018-03-28

上节课回顾

本节内容

libvirt


主机级别虚拟化
容器级别虚拟化

xen -> kvm
lxc - > openvz -> docker

type-i: hypervisor ,vm
type-ii: host -> vmm -> vm

主机级别分类
 模拟器
 完全虚拟化
 半虚拟化


 glibc:

 pos portable os ix

 ovs : openvswith

2018-03-31

上节课回顾

本节内容

虚拟化: 对资源的抽象化,将资源与应用逻辑分离,形成松耦合关系。

为啥虚拟化:
            丰富使用方式
            资源利用率

平台虚拟化, 资源虚拟化,应用程序虚拟化

supervisor: 管理多个进程的, 一般只监控一个。

课堂笔记4月

2018-04-01

上节课回顾

本节内容

elk,elfk

通用搜索引擎, 站内搜索引擎


gfs,mapreduce,bigtable
hdfs,mapreduce,hbase    hadoop

elastic


会啥不重要,做过啥重要。

间接经验和直接经验

至少2个项目工作经验

简历匹配度至少80。

曾经实现, 经常使用,曾构建

专业化。

语句简洁,专业化。

red,yellow,green

green: 所有shard主副分片都正常可用
yellow: 存在缺失
red: 都缺失

9200
9300

timedatectl set-timezone Asia/Shanghai

elk: elasticsearch
e: elasticsearch
l: logstash
k:

2018-04-04

上节课回顾

本节内容

容器就是一个工具。

kubernetes(k8s)

openshift(paas)

busybox ,cirros,alpine

docker help ps

docker ps -a

docker attach b1

容器进程一定前台启动

docker kill

docker help exec 额外执行其他命令