Introduction to Linux and history command (5)

1 Introduction

Linux Philosophy:

  • Everything is a file (hardware devices are also represented as files)

    In Linux, almost all resources are regarded as files, including hardware devices, such as network interfaces, disks, etc., are organized into file formats, and hardware resources can be accessed by accessing files.

  • Consists of many small programs with a single purpose; a program only does one thing, and must do it well;

              The programs and executable files provided in linux are generally single-function, short and concise, which ensures the high-speed operation of linux.

  • Combining small programs to complete complex tasks;

              Because each linux command has a simple function, if you want to achieve complex tasks, you can achieve complex functions by connecting multiple simple programs, which can ensure the efficiency of a single program, and also ensure that complex programs are also efficient

  • Avoid interacting with users as much as possible;

    Goal: Realize script programming to automatically complete the dictation function;

  • Use plain text files to save configuration information;

    Goal: A simple text editor can complete the system configuration work

  • provide mechanisms, not policies;

              This is one of the linux ideas. The so-called mechanism is "what function to provide", and the strategy is "what function to realize". This unique design idea provides designers with more space to better realize it. Therefore, freedom has always been the core idea of ​​linux

2 Briefly introduce the file system of Linux

      In Linux, the absolute starting position is the root (/), which is called the root file system; the path of Linux is an inverted tree structure, which uses a hierarchical structure to represent the file path; when specifying the path, there must be an initial Position, if there is no other position that can exist after specifying a starting position, then this starting position is the absolute starting position.

What is a directory?

A directory is just a path mapping method. A directory: is a namespace, and a directory is a special file.

What is a document?

The file must have a name, and the file content occupies disk space.

A file has two types of data in Linux

Metadata: metadata, metadata is the attribute information of the file, not a part of the file number, and the metadata points to the data of the file;

Data: data

Linux file names are strictly case-sensitive

   The file name can use any character except / , but special characters are not recommended. The maximum length of the file name cannot exceed 255 characters. All files starting with . are hidden files.

Note: / is the root directory and is also a path separator

path:

In Linux, a simple understanding of the path of a file refers to the location where the file is stored.

For example, /home/file indicates the location where the file file is stored. As long as we tell the Linux system the exact location of a file, it can find the file.

We know that all files (directories) in the Linux system are organized into an inverted tree structure starting with the root directory "/", as shown in the figure.

Absolute path:

      The absolute path must start from the root directory /. For example, use the absolute path to indicate the location of the bin file, and the path should be written as /usr/bin

relative path

      Unlike absolute paths, relative paths are not written from the root directory /, but from the current working directory. When using a relative path to indicate the storage location of a file, two special directories are often used, namely the current directory (indicated by .) and the parent directory (indicated by ..).

Example:

When we log in to the Linux system as root, the current working directory defaults to /root. If you need to adjust the current working directory to another subdirectory of root, you can of course use an absolute path. For example, there is a data subdirectory under the root directory, and the method of using an absolute path to enter the subdirectory is as follows:

root@ubuntn:~# pwd        <-- Display the current working path

/root

root@ubuntn:~# cd /root/data/

root@ubuntn:~/data# pwd

/root/data

root@ubuntn:~/data#

Note: For the pwd and cd commands used here, you only need to know their functions at present, and the specific usage will be explained in detail in subsequent articles.

As you can see, by using the absolute path, we have successfully changed the current working path. But other than that, it's easier to use relative paths. Because it is currently in the location of /root, and data is located in the current directory, so:

root@ubuntn:~# pwd <-- Display the current working path

/root

root@ubuntn:~# cd ./data/

root@ubuntn:~/data# pwd

/root/data

root@ubuntn:~/data#

In this example, ./data indicates the path of the data file relative to /root. Here, ./ can be omitted when entering other subdirectories under the root directory.

In short, the absolute path is relative to the root path /, as long as the file does not move, its absolute path is constant; while the relative path is relative to the current directory, with the execution of the program, The current directory may change, so the relative path of the file is not fixed.

3 Linux commands

      To learn Linux, you first need to know the basic format and usage of commands, as well as the help of corresponding query commands, because Linux mainly implements various operations in the form of commands, and there are many command entries, it is also very important to learn how to get help from commands .

Linux commands are mainly divided into two types

Internal commands: commands that come with the shell program

External command: There is an independent executable program file, which is located in a certain directory of the file system, and the file name is the command name.

3. 1. View the help of bash internal commands

          help command

For example:

root@ubuntn:~# 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 position OFFSET. Negative

                offsets count back from the end of the history list

   

      -a        append history lines from this session to the history file

      -n        read all history lines not already read from the history file

                and append them to the history list

      -r        read the history file and append the contents to the history

                list

      -w        write the current history to the history file

   

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

   

    Exit Status:

    Returns success unless an invalid option is given or an error occurs.

root@ubuntn:~#

3.2 外部命令

都有一个可执行程序,位于文件系统某目录下:

(1)、COMMAND --help

例如:

(2)、使用手册(manual)

格式为:man # command (命令)

手册:有章节之分,man1---man9,man9一般没有什么用

手册页路径:/usr/share/man/

man1:用户命令,查看命令的帮助

man2:系统调用,查看可被内核调用的函数的帮助

man3:程序库调用,查看函数和函数库的帮助

man4:设备及特殊文件,查看特殊文件的帮助(主要是/dev目录下的文件)

man5:配置文件格式,查看配置文件的帮助

man6:游戏

man7:杂项,惯例与协议等,例如Linux文件系统、网络协议、ASCII code等等的说明

man8:管理类的命令,查看系统管理员可用的命令的帮助

man9:内核内部指令,查看内核相关文件的帮助

注意:有些关键在不止一个章节中存在帮助手册;

要看指定章节手册:man # COMMAND

man命令的配置文件:/etc/man.config

MANPATH /PATH/TO/SOMEWHERE 指明新的手册文件搜索位置

# man -M /PATH/TO/SOMEWHERE COMMAND :到指定位置下搜索COMMAND命令的手册页并显示

如何查看指定命令在哪些章节下有帮助:

whatis COMMAND

注意:

如果使用whatis无法找到,这是因为whatis是根据数据库执行查找操作的,此库为系统定期更新;可使用makewhatis手动更新,

如果提示无法找到makewhatis这条命令,那么这是因为安装的版本不同或者没有安装,这时输入mandb更新。

帮助中命令语法的一些符号说明

[] :表示的是可选

…: 表示的可以存在多个参数

|:表示是可选的

<>:必填

{}:表示作为一个整体存在的

使用man查看命令手册示例:

root@ubuntn:~# man ip

 3.3 man的使用机制:

   翻屏:

空格键、Ctrl+f、Ctrl+V:向文件尾部翻一屏

b、Ctrl+B: 向文件首部翻一屏

回车键:向文件尾部翻一行

k: 向文件首部翻一行

Ctrl+d: 向文件尾部翻半屏

Ctrl+u: 向文件首部翻并屏

q:退出

#:跳转至第#行

1G:回到文件首部

G:翻至文件尾部

    字串搜索:

/keyword: 从文件首部向尾部进行搜索

n: 显示找到的下一个

N:显示找到的上一个

?keyword: 从文件尾部向首部进行搜索

n: 显示找到的下一个

N:显示找到的上

3.4 使用man查看及介绍bash命令

root@ubuntn:~# help hash

hash: hash [-lr] [-p pathname] [-dt] [name ...]  <-----使用格式

    Remember or display program locations.  记住或显示程序位置

   

    Determine and remember the full pathname of each command NAME.  If

    no arguments are given, information about remembered commands is displayed.

   

    Options:  <----选项

      -d                forget the remembered location of each NAME   删除一个指定命令的缓存记录

      -l                display in a format that may be reused as input

      -p pathname       use PATHNAME is the full pathname of NAME

      -r                forget all remembered locations       删除所有命令的缓存记录

      -t        print the remembered location of each NAME, preceding

                each location with the corresponding NAME if multiple

                NAMEs are given

    Arguments:

      NAME      Each NAME is searched for in $PATH and added to the list

                of remembered commands.

   

    Exit Status:

    Returns success unless NAME is not found or an invalid option is given.

root@ubuntn:~#

3.5 hash命令

查看内存中执行的外部命令,

选项使用示例,使用-r清空所有命令的缓存记录

4  history命令详解

         history命令用于显示历史记录和执行过的命令,history命令是被保存在内存中的,登录shell时,会读取命令历史文件中记录下的命令,登录进shell后新执行的命令只会记录在缓存中,这些命令会在用户退出时会追加至命令历史文件中,即记录在用户主目录下的".bash_history"中。

在内存中,历史命令仅能够存储1000条历史命令,该数量是由环境变量 HISTSIZE进行控制。

4.1  history的环境变量:

         HISTSIZE:命令历史记录的条数

         HISTFILE:~/.bash_history

         HISTFILESIZE:命令历史文件中记录历史的条数,默认1000个

输出命令历史缓存小:

4.2 history命令用法及常用选项介绍

root@ubuntn:~# help history

命令用法:

history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]

参数说明:

            N:显示最近的N条记录,包括当前命令自身,例如 history 5        

            -c:清空历史命令缓冲区,但不会清空历史文件,即.bash_history文件中的历史命令不会被清空

            -d offset:删除指定的偏移处的命令条目

            -a [/path/to/some_history_file]:将当前会话中的命令历史写入指定文件

            -r:将历史命令文件中的命令读入当前历史命令缓冲区        

            -w:将当前历史命令缓冲区命令写入历史命令文件中        

4.2.1 常用选项使用示例

   (1)、-d选项:删除指定的偏移处的命令条目

 使用history查看有7条命令,想删除第3条命令,就可以使用history -d 后面的第几个命令,如history -d 3就是删除第三条命令,如下:

root@ubuntn:~# history

    1  reboot

    2  adduser test

    3  cat /etc/passwd

    4  cat /etc/group

    5  cd /home/

    6  ll

    7  id test

root@ubuntn:~# history -d 3

root@ubuntn:~# history

    1  reboot

    2  adduser test

    3  cat /etc/group

    4  cd /home/

    5  ll

    6  id test

   7  history

   8  history -d 3

   9  history

root@ubuntn:~#

(2)-c:清空当前历史命令;对命令史文件没有影响

(3)、-r:将历史命令文件中的命令读入到当前历史命令缓冲区

将/root/.bash_history中的文件里的命令加到史命令缓冲区,执行history -r后,.bash_history中的文件的命令会加载到命令缓冲区,下面执行后的9至11就是我们前面4条已经提到文件的命令。

4.3  bash调用命令历史列表中的命令:

           !#: 执行命令历史中的第#条命令

           !!:执行上一条命令

           !string: 执行命令历史中最近一次以string开头的命令(从历史命令中最后向前匹配);

           !$ :调用上一条命令的最后一个参数

           ESC, . :功能同上(先按esc放开后,再按点号)

           Alt+.  :功能同上(同时按,不是所有终端都支持)

4.4 修改history命令环境变量

history命令历史记录的条数默为1000,如果需要修改历史记录条数,则在/etc/profile文件中修改环境变量,重新加载即可。

在/etc/profile文件最后新增export HISTSIZE=2000变量即可,配置方法如下:

root@ubuntn:~# echo "export HISTSIZE=2000" >>  /etc/profile  

root@ubuntn:~# source /etc/profile              ------->使配置生效

root@ubuntn:~# echo $HISTSIZE

2000

root@ubuntn:~#

4.5 配置history命令记录时间戳

默认查看历史命令是不显示时间的,如果需要显示时间,需要在/etc/profile文件中增加环境变量,在配置文件最后新增如下变量参数,新增后重新加载配置文件使配置生效:

 HISTTIMEFORMAT="%F %T "         #这里需要注意%T后面有个空格

配置方法如下:

root@ubuntn:~# echo 'HISTTIMEFORMAT="%F %T "' >>  /etc/profile

root@ubuntn:~# source /etc/profile             ------->加载配置文件使配置生效

配置后再次查看历史命令,就会有时间戳显示,如下:

4.6 修改历史命令存放的位置和操作用户

history命令显示的信息时默认保存最近的1000条命令,从历史信息中只能看到执行了某个命令,对于进一步的追踪命令执行的用户则无法查询,无法定位到是哪个用户在哪个时间在哪执行的命令,做以下配置,将以下脚本加入/etc/profile文件中。

###LOG HISTORY COMMAND / LOGNAME / Client IP###

USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`

HISTDIR=/LoginAudit/history

if [ -z $USER_IP ]

then

USER_IP=`hostname`

fi

if [ ! -d $HISTDIR ]

then

mkdir -p $HISTDIR

chmod 777 $HISTDIR

fi

if [ ! -d $HISTDIR/${LOGNAME} ]

then

mkdir -p $HISTDIR/${LOGNAME}

chmod 300 $HISTDIR/${LOGNAME}

fi

export HISTSIZE=4000

DT=`date +%Y%m%d_%H%:M:%S`

export HISTFILE="$HISTDIR/${LOGNAME}/${USER_IP}-history-$DT"

export HISTTIMEFORMAT="[%Y.%m.%d %H:%M:%S] [`who am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`] [$(whoami)]"

chmod 600 $HISTDIR/${LOGNAME}/*.history* 2>/dev/null

将这段脚本加入到/etc/profile的末尾,脚本的作用是把每个用户执行的命令记录在/LoginAudit/history/目录下,并在目录下以用户名生成目录,在用户名目录下历史记录文件名根据用户ip和时间命名保存记录历史命令。

配置后使配置生效:

root@ubuntn:~# source /etc/profile

使用history命令查看,如下:

进入保存历史命令的目录下,会有以用户名生成的目录保存历史命令。

Guess you like

Origin blog.csdn.net/yjun89/article/details/131747999