Linux学习笔记¶
记录Linux服务器/操作系统的学习笔记。
学会使用命令帮助¶
概述¶
Linux命令行有非常多的命令,通过获取命令的帮忙信息,能够快速了解命令的具体含义和使用方法,通过使用命令行命令的帮助信息,可以减轻学习Linux的负担。获取帮助的途径有:
- 使用manual手册-man命令
- 使用info信息页-info命令
- 使用help帮助
- 程序自身的帮助文档
- 程序官方文档
- Google搜索
man命令¶
man命令的实用性非常高,基本上所有的类Unix系统都支持,所以man命令是学习的重点。man命令帮助文档存放在/usr/share/man目录下,man工具的功能非常强大,几乎每个命令都有man手册。
/usr/share/man目录结构如下:

man命令常用参数¶
查看man手册页
man [章节] keyword
列出所有帮助
man -a keyword
搜索man手册
man -k keyword
查找vim相关的手册
列出符合关键字的可用手册页
man -f keyword
查找man关键字可用的手册页
打印man帮助文件的路径
man -w [章节] keyword
打印man帮助文档存放的路径
man帮忙文档分类¶
帮忙文档分类如下:
分类(章节) | 说明 |
---|---|
1 | 可执行或Shell命令 |
2 | 系统调用(内核提供的函数) |
3 | 库调用(程序库中的函数) |
4 | 设备文件及特殊文件的说明 |
5 | 配置文件 |
6 | 游戏 |
7 | 杂项(包括宏包和规范) |
8 | 系统管理命令(通常只针对root用户) |
9 | 内核相关的文件 |
下面是引用man手册中关于小节的说明:
一个手册页面包含若干个小节。
小节名称通常包括NAME,概述(SYNOPSIS),配置(CONFIGURATION),描述(DESCRIPTION),选项(OPTIONS),退出状态(EXIT STATUS),返回值(RETURN VALUE),错误(ERRORS),环境(ENVIRONMENT),文件(FILES),版本(VERSIONS),符合标准(CONFORMING TO),注(NOTES),缺陷(BUGS),示例(EXAMPLE),作者(AUTHORS),和其他帮忙参考(SEE ALSO).
VIM编辑器的使用¶
VIM的模式¶
- 命令模式:vi默认启动进入此模式。
- 插入模式:在命令模式下,使用“i”或“o”或“a”可以进入插入模式(insert)。
- 修改模式:在命令模式下,使用“R”可以进入修改模式(Replace)。
- 扩展命令模式:在命令模式下,使用英文冒号“:”可以进入扩展命令模式(:)。
命令模式常用快捷键¶
- G 移动到文件的最后一行。
- nG : n为数字,移动到文件的第n行。
- gf : 打开以光标所在字符串为文件名的文件
- gg : 移动到文件的第一行。
- N[Enter] : 向下移动N行。
- h : 向左移动光标(←)
- j : 向下移动光标(↓)
- k : 向上移动光标(↑)
- l(小L) : 向右移动光标(→)
- 20j : 向下移动20行
- + 或 Enter : 把光标移至下一行第一个非空白字符
- - : 把光标移至上一行第一个非空白字符
- ^ : 把光标移至本行第一个非空白字符
- 0或Home :移动光标至行首
- $或End : 移动光标至行尾
- w : 向右移动一个单词,光标停在下一个单词开头
- W : 向右移动一个单词,光标移动时忽略一些标点
- b : 向左移动一个单词,光标停在下一个单词开头
- B : 向左移动一个单词,光标移动时忽略一些标点
- e : 向右移动一个单词,光标停在下一个单词末尾
- E : 向右移动一个单词,光标移动时忽略一些标点
- ge : 向左移动一个单词,光标停在下一个单词末尾
- gE : 向左移动一个单词,光标移动时忽略一些标点
- H : 移动光标至屏幕的最上方那一行行首
- M : 移动光标至屏幕的最中间那一行行首
- L : 移动光标至屏幕的最下方那一行行首
- ( : 移动光标至上一句
- ) : 移动光标至下一句
- { : 移动光标至上一段
- } : 移动光标至上一段
- ctrl+b : 屏幕向上移动一页
- ctrl+f : 屏幕向下移动一页
- ctrl+d : 屏幕向上移动半页
- ctrl+u : 屏幕向下移动半页
- ctrl+e : 屏幕向下移动一行
- n% : 到文件n%的位置,如1%,50%, 100%之类
- zz : 将当前行移动到屏幕中央
- zt : 将当前行移动到屏幕顶端
- zb : 将当前行移动到屏幕底端
- dd : 剪切当前行(不是删除,因为此时在缓存内保存了一份剪切的字符串)。
- d$ : 删除光标位置到该行最后一个字符(包括光标字元)。
- d0 : 删除光标字元至行首字符(不包括光标字元)。
- dG : 删除光标所在行至最后一行所有字符(包括光标所在行)。
- d1G : 删除光标所在行(包括光标所在行)与首行间所有字符。
- ndd : 删除光标所在行(包括)向下的n行。
- dw : 删除光标所在字符至下一个单词间所有字符(包括下一个单词前面的空格)。
- daw : 剪切光标所在位置的单词。
- das : 剪切光标所在位置的句子。
- x : 向后删除一个字符。
- nx : 向后删除n个字符。
- yy : 复制当前行。
- nyy : 复制n行(包含当前行)。
- y1G : 复制第一行至当前行所有字符。
- yG : 复制当前行到最后一行所有字符。
- y0 : 复制当前行行首字符至光标字符间所有字符。
- y$ : 复制当前行光标字符到行尾字符间所有字符。
- yaw : 复制光标所在位置的单词。
- yas : 复制光标所在位置的句子。
- ZZ : 保存更改并退出。
- p : 将已经复制的数据粘贴到光标的下一行(若是使用y0,y$复制的行的一部分,则粘贴时,会粘贴到光标所在行的光标字符后面)。
- P : 将已经复制的数据粘贴到光标的上一行(若是使用y0,y$复制的行的一部分,则粘贴时,会粘贴到光标所在行的光标字符前面)。
- u : 复原上一操作(撤消)。
- ctrl+R : 重做上一操作。
- . : 点号,重做上一操作。
- J : 将当前行与下一行合并为一行。
- gJ : 将当前行与下一行合并为一行,不过合并后不留空格。
- << : 段落向左缩进一个shiftwidth
- >> : 段落向右缩进一个shiftwidth
- gq : 对选中的长文字进行重排
- o : 当前行下插入空行,并进入插入模式。
- O : 当前行上插入空行,并进入插入模式。
- i : 进入插入模式,从当前光标所在处插入。
- I : 进入插入模式,从当前行第一个非空格处开始插入。
- a : 进入插入模式,从当前光标所在处下一个字符开始插入。
- A : 进入插入模式,从当前光标所在行最后一个字符开始插入。
- 8i=<ESC> 重复输入小技巧,先按数字8,再按i进入插入模式,再按=或其他字符,如=-,再按Esc退出键,再按一次键,就会出现8次=-组成的字符串。如:=-=-=-=-=-=-=-=-
- “ESC”健 : 返回命令模式。
编辑模式¶
在命令模式下按i、o、a等键可进入插入模式(编辑模式)。
- o: 当前行下插入空行,并进入插入模式。
- O: 当前行上插入空行,并进入插入模式。
- i: 进入插入模式,从当前光标所在处插入。
- I: 进入插入模式,从当前行第一个非空格处开始插入。
- a: 进入插入模式,从当前光标所在处下一个字符开始插入。
- A: 进入插入模式,从当前光标所在行最后一个字符开始插入。
另外按字母s也可以进入插入模式:
- s: 小s,删除光标字符,并进入编辑模式,并在光标所在位置开始编辑。
- S: 大S,删除光标所在行,并进入编辑模式,并在行首开始编辑。
- ns: 删除包含光标字符在内的n个字符,并进入编辑模式。
- nS: 大S,删除光标所在行在内及其后的n-1行,并进入编辑模式。
扩展命令模式常用操作键¶
- :r filename 在当前位置插入另一个文件的内容
- :[n]r filename 在当前文件第n行插入另一个文件的内容
- :r !date 在光标处插入当前日期与日期,同理,:r !command可以将其他shell命令的输出插入到当前文档
- :r !cat filename|head -n N 在当前文件光标的下一行插入文件filename的前N行
- :w : 保存。
- :q : 离开vim。
- :q! : 强制离开。
- :wq : 保存后离开。
- :w [filename] : 将当前文本另存为filename
- :n1,n2 w [filename] : 将n1至n2行内容另存为filename
- :r [filename] : 将新文本filename插入到当前光标所在行的下面
- :ce(nter) 本行文字居中
- :le(ft) 本行文字靠左
- :ri(ght) 本行文字靠右
- /word : 向下查找关键字word。
- ?word : 向上查找关键字word。
- :n1,n2s/word1/word2/g : 在第n1行与第n2行之间查找word1字符串,并直接替换为word2。
- :1,$s/word1/word2/g : 在第1行最后一行之间查找word1字符串,并直接替换为word2。
- :1,$s/word1/word2/gc : 在第1行最后一行之间查找word1字符串,并替换为word2(替换时询问用户是否替换)。
- :.,+5s/^/#/g : 将当前行及下面5行标记为注释(包括当前行,共6行)。
- :6,9 de : 删除第6至第9行。
- :2,8 co 10 : 复制第2行至第8行内容至第10行后面(从下一行开始)
- :set nu : 显示行号。
- :set nonu : 不显示行号。
- :set hlsearch : 高亮度搜索显示
- :set nohlsearch : 不高亮度搜索显示
- :set autoindent/noautoindent : 自动缩进
- :set ruler/noruler : 设置右下角状态栏说明
- :set showmode/noshowmode : 设置是否显示左下角(-INSERT-)状态列
- :set backspace=2 : =2时,退格键可删除任意字符,=0或=1时只能删除刚输入的字符。
- :set : 显示与系统预设值不同的设定参数。
- :set all : 显示所有的环境参数值
- :syntax on/off : 设置语法高亮
- :set bg=dark/light : 设置背景(background)为暗色/亮色
- :set tabstop=4 : 设置Tab宽度
- :set shiftwidth=4 : 设置每一级缩进的宽度
- :Sex : 水平分割一个窗口,浏览文件系统
- :Vex : 垂直分割一个窗口,浏览文件系统
~/.vimrc常用环境变量设置¶
- set hlsearch “设置高亮度反白
- set backspace=2 “可随时用退格键删除
- set autoindent “自动缩排
- set ruler “可显示最后一行的状态
- set showmode “显示状态
- set nu “显示行号
- set bg=dark “显示不同的底色色调
- set softtabstop=4 “统一缩进为4
- set tabstop=4 “设置Tab宽度
- set shiftwidth=4 “设置每一级缩进的宽度
- set fileencodings=utf-8,gbk,gb18030,gk2312
- syntax on “语法高亮
- set showcmd “输入的命令显示出来,看的清楚些
- set clipboard+=unnamed “共享剪贴板
- set cursorline “突出显示当前行
- set noeb “去掉输入错误的提示声音
- set confirm “在处理未保存或只读文件的时候,弹出确认
- set autoindent “设置自动缩进
- set cindent “设置自动缩进
- set expandtab “用空格代替制表符
- set smarttab “在行和段开始处使用制表符
- set laststatus=2 “总是显示状态栏
~/.vimrc配置文件内容如下:
set hlsearch
set backspace=2
set autoindent
set ruler
set showmode
set nu
set bg=dark
set softtabstop=4
set shiftwidth=4
set fileencodings=utf-8,gbk,gb18030,gk2312
syntax on
set showcmd
set clipboard+=unnamed
set cursorline
set confirm
set autoindent
set cindent
set expandtab
set laststatus=2
可视模式¶
- 可视模式(Visual Black),也即区块选择模式,此时可以对列字符进行操作。
- 在命令模式下,按v或V或ctrl+v可以进入到可视模式。
- v : 进入可视模式,并进行单字符(反白)选择。
- V : 进入可视模式,并进行行(反白)选择。
- ctrl+v : 进入可视模式,并进行区块选择,以长方形的方式(反白)选择字符。
- y : 将反白的地方复制下来。
- d : 删除反白区域。
- 进入可视模式后,可以按方向键或h/j/k/l(向左、向下、向上、向右)进行反白区域选择。
多视窗功能¶
- 输入:sp进入多视窗模式,此时,可以对文本进行前后对照或不同档案间进行对照。
- :sp 同一文件两个视窗,进行前后对照。
- :sp [filename] 两个文件进行对照。
在多视窗模式下:
- ctrl+w 可依次在多个视窗间进行上下循环切换。
- ctrl+w+k 可依次在多个视窗间进行从下到上切换(先按ctrl+w,松开后,再按k)。
- ctrl+w+j 可依次在多个视窗间进行从上到下切换(先按ctrl+w,松开后,再按j)。
- ctrl+w+q 关闭当前视窗下面的视窗(先按ctrl+w,松开后,再按q)。
增加编程语言模板的.vimrc配置文件¶
~/.vimrc配置文件内容如下:
execute pathogen#infect()
syntax on
filetype plugin indent on
set hlsearch
set backspace=2
set autoindent
set ruler
set showmode
set nu
set bg=dark
set ts=4
set softtabstop=4
set shiftwidth=4
set fileencodings=utf-8,gbk,gb18030,gk2312
syntax on
set showcmd
set clipboard+=unnamed
set cursorline
set confirm
set autoindent
set cindent
set expandtab
set laststatus=2
"SET Comment START
autocmd BufNewFile *.c,*.py,*.go,*.sh exec ":call SetComment()" |normal 10Go
func SetComment()
if expand("%:e") == 'c'
call setline(1, "/*")
call append(1, ' * Filename: '.expand("%"))
call append(2, ' * Author: Zhaohui Mei<mzh.whut@gmail.com>')
call append(3, ' * Description: ')
call append(4, ' * Create Time: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(5, ' * Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(6, ' */')
call append(7, '')
call append(8, '')
call append(9, '')
call append(10, '')
elseif expand("%:e") == 'go'
call setline(1, "/*")
call append(1, ' * Filename: '.expand("%"))
call append(2, ' * Author: Zhaohui Mei<mzh.whut@gmail.com>')
call append(3, ' * Description: ')
call append(4, ' * Create Time: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(5, ' * Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(6, ' */')
call append(7, 'package main')
call append(8, '')
call append(9, 'import "fmt"')
call append(10, '')
call append(11, 'func main() {')
call append(12, ' fmt.Println("vim-go")')
call append(13, '}')
elseif expand("%:e") == 'py'
call setline(1, '#!/usr/bin/python3')
call append(1, '"""')
call append(2, '# Filename: '.expand("%"))
call append(3, '# Author: Zhaohui Mei<mzh.whut@gmail.com>')
call append(4, '# Description: ')
call append(5, '# Create Time: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(6, '# Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(7, '"""')
call append(8, '')
call append(9, '')
call append(10, '')
elseif expand("%:e") == 'sh'
call setline(1, '#!/bin/bash')
call append(1, '##################################################')
call append(2, '# Filename: '.expand("%"))
call append(3, '# Author: Zhaohui Mei<mzh.whut@gmail.com>')
call append(4, '# Description: ')
call append(5, '# Create Time: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(6, '# Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
call append(7, '##################################################')
call append(8, '')
call append(9, '')
call append(10, '')
endif
endfunc
map <F2> :call SetComment()<CR>:10<CR>o
"SET Comment END
"SET Last Modified Time START
func DataInsert()
if expand("%:e") == 'c' || expand("%:e") == 'go'
call cursor(6, 1)
if search ('Last Modified') != 0
let line = line('.')
call setline(line, ' * Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
endif
elseif expand("%:e") == 'py' || expand("%:e") == 'sh'
call cursor(7, 1)
if search ('Last Modified') != 0
let line = line('.')
call setline(line, '# Last Modified: '.strftime("%Y-%m-%d %H:%M:%S"))
endif
endif
endfunc
autocmd FileWritePre,BufWritePre *.c,*.py,*.go,*.sh ks|call DataInsert() |'s
"SET Last Modified Time END
"" refer:https://blog.csdn.net/qq844352155/article/details/50513072
使用vim新建test.go后显示如下:
1 /*
2 * Filename: test.go
3 * Author: Zhaohui Mei<mzh.whut@gmail.com>
4 * Description:
5 * Create Time: 2019-11-24 23:52:56
6 * Last Modified: 2019-11-24 23:52:56
7 */
8 package main
9
10 import "fmt"
11
12
13 func main() {
14 fmt.Println("vim-go")
15 }
利用mailx发送邮件通知¶
修改mailx的配置文件¶
在/etc/mail.rc文件最后添加以下文本:
vi /etc/mail.rc
# 外部发送邮箱地址
set from=mzh_love_linux@163.com
# 外部smtp服务器的地址,不使用SSL协议加密,端口号25
set smtp=smtp.163.com
# 外部smtp服务器认证的用户名
set smtp-auth-user=mzh_love_linux
# 启用授权码,避免密码泄漏造成邮箱安全隐患,使用邮件客户端更安心
# 密码,此处使用网易邮箱授权密码
set smtp-auth-password=password
# 邮件认证的方式
set smtp-auth=login
保存后,重启sendmail:
service sendmail restart
测试sendmail发送邮件:
echo "sendmail测试"|mail -s "Linux外部邮箱发信测试" xxxxxxx@qq.com
如果配置成功,则xxxxxxx@qq.com这个邮箱会收到测试邮件。
配置SSL加密协议发送邮件¶
在/etc/mail.rc文件最后添加以下文本:
# 外部发送邮箱地址
set from=mzh_love_linux@163.com
# 外部smtp服务器的地址,使用SSL协议加密,端口号465
# 设置SMTP地址及端口,注意smtps说明启用了SSL加密
set smtp=smtps://smtp.163.com:465
# 外部smtp服务器认证的用户名
set smtp-auth-user=mzh_love_linux
# 启用授权码,避免密码泄漏造成邮箱安全隐患,使用邮件客户端更安心
# 密码,此处使用网易邮箱授权密码
set smtp-auth-password=password
# 邮件认证的方式
set smtp-auth=login
# 指定本地证书路径
set nss-config-dir=/etc/pki/nssdb/
# 忽略证书错误
set ssl-verify=ignore
发送测试邮件:
echo -e "正文"|mail -s "Linux使用mailx发送邮件通知" xxxxxxx@qq.com
监控磁盘空间并自动发送邮件通知¶
脚本内容如下:
#!/bin/bash
# Filename: disk_check.sh
# Author: Mei Zhaohui
# Date: 2019-08-15 22:17
# Function: Monitor hard disk space and send email to Admin
# You can add this shell to crontab
# 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
# 30 1 * * * /usr/bin/sh /root/disk_check.sh
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:$PATH
maxused=75
admin_emails="xxxxxxx@qq.com"
host_ip=$(ip addr show|grep 192|awk -F '[ /]+' '{print $3}')
disk_size=$(df -h|grep '/$'|awk -F '[ %]+' '{print $2}')
used=$(df -h|grep '/$'|awk -F '[ %]+' '{print $5}')
hard_free=$(df -h|grep '/$'|awk -F '[ %]+' '{print $4}')
if [[ "${used}" -gt "${maxused}" ]]; then
echo "Used greater then the maxused value"
avail_percentage=$[100-$used]
echo -e "Linux系统磁盘快满了,请尽快处理。详情如下:\n主机IP:${host_ip}\n磁盘总量:${disk_size}\n剩余空间:${hard_free}\n当前可用比例:${avail_percentage}%\n\n*********本邮件由系统自动发送,请勿直接回复*********"|mailx -s "[警告]Linux系统(${host_ip})磁盘要满了" "${admin_emails}" > /dev/null 2>&1
fi
将脚本加入到定时任务中,收到的邮件通知类似下图:

Bash script中的通配符与正则表达式¶
通配符符号与其意义¶
- 符号 意义
- * 代表任意个(包括0个)字符
- ? 代表一定有一个任意字符
- [] 代表至少有一个中括号内的字符。[abc]代表一定有一个字符,是a/b/c中任一个
- [-] 代表编码顺序内所有字符。[0-9]代表数字,[a-z]代表小写字母,[A-Z]代表大写字母
- [^] 非。[^abc]代表一定有一个字符,只要是非a/b/c的其他字符就行
正则表达式¶
正则表达式(regular expression)¶
- RE字符 意义
- * 重复0个或多个前面的RE字符
- . 点号 任意字符(一定有一个)
- ^word 待查找字符(word)在行首
- word$ 待查找字符(word)在行尾
- \ 转义字符,将特殊符号的特殊意义去除
- [list] 从字符集list中任意选取一个。如[abc]代表a或b或c
- [-] 代表编码顺序内所有字符。[0-9]代表数字,[a-z]代表小写字母,[A-Z]代表大写字母
- [^] 非。[^abc]代表一定有一个字符,只要是非a/b/c的其他字符就行。
- [^a-z]代表非小写字母,[^A-Z]代表非大写字母,[^0-9]代表非数字。
- {n,m} 连续n到m个前一个RE字符
- {n} 连续n个前一个RE字符
- {n,} 连续n个以上前一个RE字符
扩展正则表达式(extendedregular expression)¶
- 扩展符号 意义
- ? 匹配0个或一个在其之前的那个普通字符
- + 匹配一个或多个在其之前的那个普通字符
- ( ) 表示一个字符集合或用在expr中
- | 表示“或”,匹配一组可选的字符
linux下安装htop¶
下载源文件¶
htop-1.0.2.tar.gz下载地址:http://pan.baidu.com/s/1o6itGt8
安装htop¶
解压:
tar -zxvf htop-1.0.2
切换目录:
cd htop-1.0.2
安装:
./configure
make
make install
执行htop命令查看是否安装成功。
echo输出带颜色的字体¶
概述¶
在linux命令行终端或Bash Shell脚本中适当使用颜色,能够让第一时间感觉到您的命令或脚本执行过程中差异。本文主要介绍使用echo输出带颜色的字体。
- echo不带参数输出字符串
当echo命令不带参数时,可以直接输出字符串,如下所示:
[meizhaohui@hopewait ~]# echo "abc"
abc
[meizhaohui@hopewait ~]# echo def
def
- echo带参数输出字符串
当echo命令带-e参数时,可以使用反斜杠 \ 输出特殊的字符。echo输出带颜色的字体格式如下:
echo -e "\033[字背景颜色;字体颜色m字符串\033[0m"
其中: “\033” 引导非常规字符序列。”m”意味着设置属性然后结束非常规字符序列。
例如:
echo -e "\033[41;32m红色背景绿色文字\033[0m"
其中: 41的位置代表底色, 32的位置是代表字的颜色。
下面是代码输出绿色文字:
echo -e "\033[32m绿色文字\033[0m"
使用复杂的颜色输出¶
例1:
echo -e "\033[31m红字\033[32m绿字\033[0m" # 输出红字和绿字

例2:
echo -e "\033[31m红字\033[43;32m绿字带黄色背景\033[0m" # 输出红字和带黄色背景的绿字

例3:
echo -e "\033[4;47;31m带下划线的白色背景的红字\033[0m\033[1;41;32m高亮的红色背景的绿字\033[0m"

例4:
echo -e "\033[4m\033[47m\033[31m带下划线的白色背景的红字\033[0m \033[1m\033[41m\033[32m高亮的红色背景的绿字\033[0m"

例5:
echo -e "\033[4m\033[47m\033[31m带下划线的白色背景的红字\033[0m \033[1;4m\033[41m\033[32m高亮的红色背景的带下划线的绿字\033[0m"

通过以上示例可知:控制符可以进行组合在一起,如例3中的 \033[4;47;31m将三个属性组合在一起(属性数字中间使用分号;隔开);也可以像例4中 \033[4m\033[47m\033[31m每个属性单独写。
- 字背景颜色范围:40–47
- 40:黑
- 41:红
- 42:绿
- 43:黄色
- 44:蓝色
- 45:紫色
- 46:天蓝
- 47:白色
- 字颜色:30–37
- 30:黑
- 31:红
- 32:绿
- 33:黄
- 34:蓝色
- 35:紫色
- 36:天蓝
- 37:白色
- ANSI控制码的说明:
- \33[0m 关闭所有属性
- \33[1m 设置高亮度
- \33[4m 下划线
- \33[5m 闪烁
- \33[7m 反显
如果经常使用颜色控制的话,可以将颜色控制符进行定义好。 可以在~/.bashrc中设置个人偏好,使用vi ~/.bashrc打开.bashrc文件:并将下面的变量写入到文件中:
将下面的变量写入到~/.bashrc文件中:
[meizhaohui@hopewait ~]# vi ~/.bashrc
bg_black=”\033[40m”
bg_red=”\033[41m”
bg_green=”\033[42m”
bg_yellow=”\033[43m”
bg_blue=”\033[44m”
bg_purple=”\033[45m”
bg_cyan=”\033[46m”
bg_white=”\033[47m”
fg_black=”\033[30m”
fg_red=”\033[31m”
fg_green=”\033[32m”
fg_yellow=”\033[33m”
fg_blue=”\033[34m”
fg_purple=”\033[35m”
fg_cyan=”\033[36m”
fg_white=”\033[37m”
set_clear=”\033[0m”
set_bold=”\033[1m”
set_underline=”\033[4m”
set_flash=”\033[5m”
输入完成后,先按Esc键,再按:键,并输入wq保存退出。
使用以下命令使刚才的修改生效:
[meizhaohui@hopewait ~]# source ~/.bashrc
此时按如下命令输入相应的字体:
[meizhaohui@hopewait ~]# echo -e "${bg_red}${fg_green}${set_bold}红色背景粗体的绿色字${set_clear}"
红色背景粗体的绿色字
红色背景粗体的绿色字
[meizhaohui@hopewait ~]# echo -e "${bg_red}${fg_green}红色背景的绿色字${set_clear}"
红色背景的绿色字
红色背景的绿色字
如果要在脚本中使用使用~/.bashrc中定义的bg_red、fg_green等变量,可以在shell脚本中使用source ~/.bashrc 或者点操作符加载~/.bashrc文件到脚本中。
打印颜色脚本:
[meizhaohui@hopewait ~]# cat print_color.sh
#!/bin/bash
#Source personal definitions
source ~/.bashrc
# 或使用以下命令:
# . ~/.bashrc
echo -e "${bg_red}${fg_green}${set_bold}红色背景粗体的绿色字${set_clear}"
运行脚本:
[meizhaohui@hopewait ~]# sh print_color.sh
参考文献:
防止rm -rf /误删除的方法¶
概述¶
“rm -rf /”意味着擦除根路径/下挂载的所有内容而无需询问。 rm -rf / 命令在Linux下执行后,就是一场灾难。
为了防止这种误删除操作,找了很多办法,有建议回收站机制、也有说给重要目录设置权限等等方法、还有替换rm删除命令的方法;总结了一下,还是觉得禁用rm命令,并设置安全删除命令 safe-rm 和垃圾回收机制 trash-cli 。
safe-rm安全删除命令¶
safe-rm,它具有 rm 命令的所有功能,不过 safe-rm 命令可以设置路径黑名单,也就是说在黑名单中的目录或文件将不会被删除;我们把 rm 命令禁用,之后执行 safe-rm 命令,也就不会误删除黑名单中的目录或文件了。
safe-rm 的官网:https://repo.or.cz/w/safe-rm.git
README文档:
safe-rm - https://launchpad.net/safe-rm prevention of accidental deletions using a directory blacklist Copyright (C) 2008-2014 Francois Marier <francois@fmarier.org> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. How to use ----------- Once you have installed safe-rm on your system (see INSTALL), you will need to fill the system-wide or user-specific blacklists with the paths that you'd like to protect against accidental deletion. The system-wide blacklist lives in /etc/safe-rm.conf and you should probably add paths like these: / /etc /usr /usr/lib /var The user-specific blacklist lives in ~/.config/safe-rm and could include things like: /home/username/documents /home/username/documents/* /home/username/.mozilla Other approaches ----------------- If you want more protection than what safe-rm can offer, here are a few suggestions. You could of couse request confirmation everytime you delete a file by putting this in your /etc/bash.bashrc: alias rm='rm -i' But this won't protect you from getting used to always saying yes, or from accidently using 'rm -rf'. Or you could make use of the Linux filesystem "immutable" attribute by marking (as root) each file you want to protect: chattr +i file Of course this is only usable on filesystems which support this feature. Here are two projects which allow you to recover recently deleted files by trapping all unlink(), rename() and open() system calls through the LD_PRELOAD facility: delsafe http://homepage.esoterica.pt/~nx0yew/delsafe/ libtrashcan http://hpux.connect.org.uk/hppd/hpux/Development/Libraries/libtrash-0.2/readme.html There are also projects which implement the FreeDesktop.org trashcan spec. For example: trash-cli http://code.google.com/p/trash-cli/ Finally, this project is a fork of GNU coreutils and adds features similar to safe-rm to the rm command directly: http://wiki.github.com/d5h/rmfd/
下载:
[root@localhost ~]$ wget https://launchpad.net/safe-rm/trunk/0.12/+download/safe-rm-0.12.tar.gz
解压:
[root@localhost ~]$ tar -zxvf safe-rm-0.12.tar.gz
查看rm存放的路径:
[root@localhost ~]$ whereis rm /usr/bin/rm
查看PATH环境变量:
[root@localhost ~]$ echo $PATH /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
复制safe-rm到/usr/local/bin目录下(将 safe-rm放在 $PATH中比原rm程序靠前的位置):
[root@localhost ~]$ cp ~/safe-rm-0.12/safe-rm /usr/local/bin/safe-rm
创建/etc/safe-rm.conf,设置路径黑名单,将重要文件或者目录的完整路径输入进去保存就可以了,每条以回车分隔:
[root@localhost ~]$ touch /etc/safe-rm.conf [root@localhost ~]$ cat /etc/safe-rm.conf / /bin /boot /dev /etc /home /initrd /lib /proc /root /sbin /sys /usr /usr/bin /usr/include /usr/lib /usr/local /usr/local/bin /usr/local/include /usr/local/sbin /usr/local/share /usr/sbin /usr/share /usr/src /var /etc/safe-rm.conf [root@localhost ~]$
测试safe-rm命令,safe-rm会跳过/etc/safe-rm.conf中配置的目录或文件(最好先找个测试目录进行实验,别弄不好成灾难了….):
[root@localhost ~]$ echo "/a/b/c" >> /etc/safe-rm.conf [root@localhost ~]$ mkdir -p /a/b/c [root@localhost ~]$ safe-rm -rm /a/b/c safe-rm: skipping /a/b/c
trash-cli垃圾回收机制¶
trash-cli是一个使用python开发的软件包,包含trash-put、trash-rm、trash-list、trash-restore、trash、trash-empty等命令,我们可以通过这些命令,将文件移动到回收站,或者还原删除了的文件。
trash-cli提供以下命令:
- trash-put trash files and directories. 将文件或目录移入回收站
- trash-empty empty the trashcan(s). 清空回收站
- trash-list list trashed files. 列出回收站中的文件
- trash-restore restore a trashed file. 还原回收站中的文件
- trash-rm remove individual files from the trashcan. 删除回收站中的单个文件
参考:https://github.com/andreafrancia/trash-cli
源码安装¶
安装命令:
[root@localhost ~]$ git clone https://github.com/andreafrancia/trash-cli.git
[root@localhost ~]$ cd trash-cli
[root@localhost ~]$ python setup.py install
使用方法¶
删除文件:
[root@localhost ~]$ trash-put foo
列出回收站中的文件:
[root@localhost ~]$ trash-list
2008-06-01 10:30:48 /root/bar
2008-06-02 21:50:41 /root/bar
2008-06-23 21:50:49 /root/foo
搜索回收站:
[root@localhost ~]$ trash-list | grep foo
2007-08-30 12:36:00 /root/foo
2007-08-30 12:39:41 /root/foo
恢复回收站中的文件:
[root@localhost ~]$ trash-restore
0 2007-08-30 12:36:00 /root/foo
1 2007-08-30 12:39:41 /root/bar
2 2007-08-30 12:39:41 /root/bar2
3 2007-08-30 12:39:41 /root/foo2
4 2007-08-30 12:39:41 /root/foo
What file to restore [0..4]: 4
$ ls foo
foo
清空回收站:
[root@localhost ~]$ trash-empty
删除回收站中<days>天前的文件:
[root@localhost ~]$ trash-empty <days>
示例:
[root@localhost ~]$ date
Tue Feb 19 20:26:52 CET 2008
[root@localhost ~]$ trash-list
2008-02-19 20:11:34 /home/einar/today
2008-02-18 20:11:34 /home/einar/yesterday
2008-02-10 20:11:34 /home/einar/last_week
[root@localhost ~]$ trash-empty 7
[root@localhost ~]$ trash-list
2008-02-19 20:11:34 /home/einar/today
2008-02-18 20:11:34 /home/einar/yesterday
[root@localhost ~]$ trash-empty 1
[root@localhost ~]$ trash-list
2008-02-19 20:11:34 /home/einar/today
仅删除匹配的文件:
[root@localhost ~]$ trash-rm \*.o
Note: you need to use quotes in order to protect the pattern from shell expansion.(你需要使用引号来保护模式免受shell扩展。)
配置~/.bashrc禁用rm命令¶
在~/.bashrc中重命名rm:
[root@localhost ~]$ cat ~/.bashrc|grep 'trash-put'
alias rm='echo -e "Info:\033[31mrm can not be used, please use \033[32msafe-rm\033[0m or \033[32mtrash-put\033[0m\n"'
[root@localhost ~]$ source ~/.bashrc
[root@localhost ~]$rm
Info:rm can not be used, please use safe-rm or trash-put
参考文献:
终端快捷键的使用¶
概述¶
在linux 终端(Terminal)使用快捷键可以提升你的工作效率。
- Tab 自动补全
- Ctrl + A 移动光标到行首位置(按Home键作用相同)
- Ctrl + B 向左移动光标(与Ctrl + F作用相反)
- Ctrl + C 终止运行的程序或命令
- Ctrl + D 退出终端(类似于exit命令)
- Ctrl + E 移动光标到行尾位置(按End键作用相同)
- Ctrl + F 向右移动光标(与Ctrl + B作用相反)
- Ctrl + H 删除当前光标前一个字符(按Backspace作用相同)
- Ctrl + K 删除当前光标到行尾的全部内容(与Ctrl + U作用相反)
- Ctrl + N 查看下一条命令(按向下键作用相同,与Ctrl + P作用相反)
- Ctrl + L 清除终端屏幕,保留当前行(类似于clear命令)
- Ctrl + P 查看上一条命令(按向上键作用相同,与Ctrl + N作用相反)
- Ctrl + Q 恢复屏幕输出(与Ctrl + S作用相反)
- Ctrl + R 搜索历史命令
- Ctrl + S 暂停屏幕输出(与Ctrl + Q作用相反)
- Ctrl + T 将光标位置的字符和前一个字符进行位置交换,并将光标向后移动
- Ctrl + U 删除当前光标到行首的全部内容(与Ctrl + K作用相反)
- Ctrl + W 删除当前光标位置前的一个单词,如果光标处于一个单词上,则删除这个单词词首至光标前的字符
- Ctrl + Y 粘贴使用Ctrl + W,Ctrl + U和Ctrl + K快捷键擦除的文本
- Ctrl + Z 把当前任务放到后台运行(相当于运行命令时后面加&)
- Ctrl + & 恢复使用Ctrl + H,Ctrl + W,Ctrl + U和Ctrl + K快捷键擦除的文本
参考:
CentOS7增加系统安全性¶
为了给CentOS7系统增加系统的安全性,防止系统被黑,可以进行以下操作:
- 修改用户密码为高强度密码
- 创建
sudo
用户 - 修改SSH的默认
22
端口 - 禁用
root
账号远程登陆 - 安装
DenyHosts
防暴力破解软件 - 安装
ClamAV
反病毒软件
修改用户密码为高强度密码¶
- 所谓的高强度密码,就是包含了大小写、数字、符号的密码。
安装自动产生密码的软件pygen¶
[root@hellogitlab ~]# yum install pwgen -y
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
Loading mirror speeds from cached hostfile
WandiscoSVN | 2.9 kB 00:00:00
epel | 5.3 kB 00:00:00
extras | 2.9 kB 00:00:00
ius | 1.3 kB 00:00:00
os | 3.6 kB 00:00:00
updates | 2.9 kB 00:00:00
(1/3): epel/7/x86_64/updateinfo | 1.0 MB 00:00:00
(2/3): epel/7/x86_64/primary_db | 6.9 MB 00:00:01
(3/3): updates/7/x86_64/primary_db | 2.8 MB 00:00:03
Resolving Dependencies
--> Running transaction check
---> Package pwgen.x86_64 0:2.08-1.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
========================================================================================================================
Package Arch Version Repository Size
========================================================================================================================
Installing:
pwgen x86_64 2.08-1.el7 epel 26 k
Transaction Summary
========================================================================================================================
Install 1 Package
Total download size: 26 k
Installed size: 42 k
Downloading packages:
pwgen-2.08-1.el7.x86_64.rpm | 26 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : pwgen-2.08-1.el7.x86_64 1/1
Verifying : pwgen-2.08-1.el7.x86_64 1/1
Installed:
pwgen.x86_64 0:2.08-1.el7
Complete!
生成20个超级难记的密码¶
[root@hellogitlab ~]# pwgen -cnys 14 -n 20
T@N0PgKw)m4-ia %a3Oz\-+r170{x bPs9J84p%^nz/. mt9Ul_i'@kNOVW Yx'M7;xGZ)f.Id
T},u2]B1#s1Ob) iE6nkE_.()*$bQ 5:{8G,9OOaJ/!- /f0%Toh.ccqzq] <fjxUZQ}4wHvsa
>kx8!qvlkRf(TX W:0?cYKhOQO0{o dA_'nKikzD>7S6 ]^1S@;tBoUXurJ X/fjTy'[2,Sw2u
8=@S+>Wx1i9$yh |1Y^R4W5cgEb:E -OYSF0nS7zv/;q W=G;vt~Wzzr1F" tJD8OTl,2z13EL
我们使用passwd
命令可以修改自己的密码:
[root@hellogitlab ~]# passwd
Changing password for user root.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
或者使用下面这种方式修改密码:
[root@hellogitlab ~]# export HISTCONTROL=ignorespace
[root@hellogitlab ~]# echo "tJD8OTl,2z13EL" |passwd root --stdin
Changing password for user root.
passwd: all authentication tokens updated successfully.
[root@hellogitlab ~]# history |tail -n 2
689 2019-10-31 22:36:19 export HISTCONTROL=ignorespace
690 2019-10-31 22:36:43 history |tail -n 2
上面操作进行了以下事情:
- 通过
export HISTCONTROL=ignorespace
设置history不记录敏感命令,即命令以空格开头时不会被记录到history历史记录中。 - 通过
echo "tJD8OTl,2z13EL" |passwd root --stdin
设置root
用户密码,--stdin
表明从标准输入中读入密码信息。 history |tail -n 2
查看历史记录,可以看到echo "tJD8OTl,2z13EL" |passwd root --stdin
这条命令没有被记录。
创建sudo
用户¶
设置密码¶
输入两次密码:
[root@hellogitlab ~]# passwd meizhaohui
Changing password for user meizhaohui.
New password:
Retype new password:
Sorry, passwords do not match.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
修改授权文件¶
- 查看授权文件位置
[root@hellogitlab ~]# whereis sudoers
sudoers: /etc/sudoers.d /etc/sudoers /usr/share/man/man5/sudoers.5.gz
- 给授权文件
/etc/sudoers
增加写(w)权限
[root@hellogitlab .ssh]# ls -lah /etc/sudoers
-r--r-----. 1 root root 4.3K Oct 30 2018 /etc/sudoers
[root@hellogitlab ~]# chmod -v u+w /etc/sudoers
mode of ‘/etc/sudoers’ changed from 0440 (r--r-----) to 0640 (rw-r-----)
[root@hellogitlab ~]# ls -lah /etc/sudoers
-rw-r-----. 1 root root 4.3K Oct 30 2018 /etc/sudoers
- 在授权文件
/etc/sudoers
中增加sudo
用户”meizhaohui”
[root@hellogitlab ~]# sed -n '99,100p' /etc/sudoers
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
# 在第100行的下一行增加以下内容
meizhaohui ALL=(ALL) ALL
# 再次查看内容
[root@hellogitlab ~]# sed -n '99,101p' /etc/sudoers
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
meizhaohui ALL=(ALL) ALL
- 将授权文件的权限还原
[root@hellogitlab ~]# chmod -v u-w /etc/sudoers
mode of ‘/etc/sudoers’ changed from 0640 (rw-r-----) to 0440 (r--r-----)
[root@hellogitlab ~]# ls -lah /etc/sudoers
-r--r----- 1 root root 4.3K Oct 31 21:17 /etc/sudoers
测试sudo
用户是否具备sudo
权限¶
- 使用”meizhaohui”账号登陆系统,并尝试查看”/etc/sudoers”文件内容
[meizhaohui@hellogitlab ~]$ cat /etc/sudoers
cat: /etc/sudoers: Permission denied
[meizhaohui@hellogitlab ~]$ head /etc/sudoers
head: cannot open ‘/etc/sudoers’ for reading: Permission denied
[meizhaohui@hellogitlab ~]$ sudo head /etc/sudoers
[sudo] password for meizhaohui:
## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.
## Host Aliases
可以发现,不使用sudo
命令时,无法查看文件内容,显示”Permission denied”,表明没有权限;使用sudo
命令时,可以查看文件内容。说明sudo
用户配置正确。
修改ssh默认端口¶
- SSH 是建立在应用层和传输层基础上的一种安全协议。SSH传输数据是加密的,可以有效防止传输过程被截取数据保障安全。
- SSH默认端口值是
22
,最大可以是65535
。 - 为防止暴力破解,可以修改SSH端口号为非
22
,如10000
。
下面我们将SSH的端口号改成10000
:
- 查看配置文件
/etc/ssh/sshd_config
的默认端口
[root@hellogitlab ~]# grep -n 'Port 22' /etc/ssh/sshd_config
17:#Port 22
可以发现17行中显示端口号是22
。
修改端口号¶
[root@hellogitlab ~]# sed -i 's/#Port 22/Port 10000/g' /etc/ssh/sshd_config
[root@hellogitlab ~]# sed -n '17p' /etc/ssh/sshd_config
Port 10000
重启SSH服务¶
[root@hellogitlab ~]# systemctl restart sshd
[root@hellogitlab ~]# systemctl status sshd
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2019-10-31 21:40:38 CST; 7s ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 27570 (sshd)
CGroup: /system.slice/sshd.service
└─27570 /usr/sbin/sshd -D
Oct 31 21:40:38 hellogitlab.com systemd[1]: Stopped OpenSSH server daemon.
Oct 31 21:40:38 hellogitlab.com systemd[1]: Starting OpenSSH server daemon...
Oct 31 21:40:38 hellogitlab.com sshd[27570]: Server listening on 0.0.0.0 port 10000.
Oct 31 21:40:38 hellogitlab.com systemd[1]: Started OpenSSH server daemon.
Oct 31 21:40:39 hellogitlab.com sshd[27561]: Failed password for root from 106.54.19.58 port 54334 ssh2
Oct 31 21:40:39 hellogitlab.com sshd[27561]: Connection closed by 106.54.19.58 port 54334 [preauth]
[root@hellogitlab ~]# netstat -tunlp|grep ssh
tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN 27570/sshd
可以发现SSH服务在端口号已经变成10000
了。
防火墙放行10000
端口¶
- 查看当前防火墙放行规则信息
[root@hellogitlab ~]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2019-10-31 10:58:06 CST; 10h ago
Docs: man:firewalld(1)
Main PID: 25023 (firewalld)
CGroup: /system.slice/firewalld.service
└─25023 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
Oct 31 10:58:06 hellogitlab.com systemd[1]: Starting firewalld - dynamic firewall daemon...
Oct 31 10:58:06 hellogitlab.com systemd[1]: Started firewalld - dynamic firewall daemon.
[root@hellogitlab ~]# firewall-cmd --list-all
public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh dhcpv6-client
ports: 90/tcp
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
可以看到默认是放行ssh
服务的。
为防止不必要的麻烦,我们还是手动将10000
端口放行。
[root@hellogitlab ~]# firewall-cmd --zone=public --add-port=10000/tcp --permanent
success
[root@hellogitlab ~]# firewall-cmd --reload
success
[root@hellogitlab ~]# firewall-cmd --list-all
public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh dhcpv6-client
ports: 90/tcp 10000/tcp
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
退出SecureCRT远程连接。
验证SSH端口是否修改成功¶
- 尝试使用
22
端口和10000
端口连接服务器。 - 使用
22
端口连接时提示The remote system refused the connection.
异常。 - 使用
10000
端口连接时,可以正常连接到服务器,说明配置正确。
禁用root
账户远程登陆¶
- 查看用户手册
[root@hellogitlab ~]# man sshd_config
# 可以看到以下内容
PermitRootLogin
Specifies whether root can log in using ssh(1). The argument must be yes, prohibit-password,
without-password, forced-commands-only, or no. The default is yes.
If this option is set to prohibit-password or without-password, password and keyboard-interactive
authentication are disabled for root.
If this option is set to forced-commands-only, root login with public key authentication will be
allowed, but only if the command option has been specified (which may be useful for taking remote back‐
ups even if root login is normally not allowed). All other authentication methods are disabled for
root.
If this option is set to no, root is not allowed to log in.
“If this option is set to no, root is not allowed to log in.”意思是指如果将”PermitRootLogin”配置项设置为”no”的话,则不允许root
账号远程登陆。
下面我们来修改配置文件”/etc/ssh/sshd_config”中”PermitRootLogin”配置项的值
- 修改配置文件”/etc/ssh/sshd_config”
[root@hellogitlab ~]# grep 'PermitRootLogin' /etc/ssh/sshd_config
#PermitRootLogin yes
# the setting of "PermitRootLogin without-password".
[root@hellogitlab ~]# sed -i 's/#PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config
[root@hellogitlab ~]# grep 'PermitRootLogin' /etc/ssh/sshd_config
PermitRootLogin no
# the setting of "PermitRootLogin without-password".
可以发现配置文件修改成功。
重启SSH服务并退出root
账号远程连接¶
[root@hellogitlab ~]# systemctl restart sshd
[root@hellogitlab ~]# systemctl status sshd
● sshd.service - OpenSSH server daemon
Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2019-10-31 22:04:51 CST; 5s ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 32055 (sshd)
CGroup: /system.slice/sshd.service
└─32055 /usr/sbin/sshd -D
Oct 31 22:04:51 hellogitlab.com systemd[1]: Stopped OpenSSH server daemon.
Oct 31 22:04:51 hellogitlab.com systemd[1]: Starting OpenSSH server daemon...
Oct 31 22:04:51 hellogitlab.com sshd[32055]: Server listening on 0.0.0.0 port 10000.
Oct 31 22:04:51 hellogitlab.com systemd[1]: Started OpenSSH server daemon.
[root@hellogitlab ~]# exit
logout
测试使用root
账号远程连接¶
再次使用root
账号远程连接时,提示”password authentication failed”
登陆sudo
账号,并尝试切换到root
账号里:
[meizhaohui@hellogitlab ~]$ ssh root@106.54.98.83
ssh: connect to host 106.54.98.83 port 22: Connection refused
[meizhaohui@hellogitlab ~]$ ssh root@106.54.98.83 -D 10000
ssh: connect to host 106.54.98.83 port 22: Connection refused
[meizhaohui@hellogitlab ~]$ ssh root@106.54.98.83 -p 10000
The authenticity of host '[106.54.98.83]:10000 ([106.54.98.83]:10000)' can't be established.
ECDSA key fingerprint is SHA256:Ow0AsLnlUQJg/SzRNgYG7x8HmYQPZ9ubGUpJoYRRuKk.
ECDSA key fingerprint is MD5:ec:9f:dc:43:1c:02:15:91:21:ee:a0:cb:77:bc:dd:dd.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[106.54.98.83]:10000' (ECDSA) to the list of known hosts.
root@106.54.98.83's password:
Permission denied, please try again.
root@106.54.98.83's password:
Permission denied, please try again.
root@106.54.98.83's password:
[meizhaohui@hellogitlab ~]$ ^C
[meizhaohui@hellogitlab ~]$ su root
Password:
[root@hellogitlab meizhaohui]# whoami
root
[root@hellogitlab meizhaohui]# exit
exit
[meizhaohui@hellogitlab ~]$ sudo ls /root
[sudo] password for meizhaohui:
data
[meizhaohui@hellogitlab ~]$
- 可以看到
22
端口不能访问,并且不能使用ssh root@106.54.98.83 -p 10000
方式连接到服务器。 - 可以看到可以能
su root
命令切换到root
账号里,同时也可以使用sudo ls /root
来执行一些需要使用root
账号才能完成的事情。说明我们的配置正确。
安装DenyHosts
防暴力破解软件¶
待补。
安装ClamAV
反病毒软件¶
待补。
参考:
- Centos7创建用户并授予sudo权限 https://blog.csdn.net/markximo/article/details/81737692
- 常见网络端口及其服务 https://blog.csdn.net/qq_29277155/article/details/51685756
- SSH是什么?Linux如何修改SSH端口号? https://www.cnblogs.com/chen-lhx/p/3974605.html
- ClamAV https://wiki.ubuntu.org.cn/ClamAV