1. 故障案例
1.1. vim编辑10G文件导致内存不足
- 背景
-
- 开发人员想通过查看日志方式、看代码/程序是否有问题
- 通过vim编辑日志
- 突然发现系统崩溃了
- 步骤
-
- 重启linux
- echo 1 > /proc/sys/vm/drop_caches
- 原因:vim编辑时会加载文件内容到内存中,文件过大,内存占满
- 避免:
-
- 查看日志,不使用cat和vim
- 查看日志使用,tail/head,less/more
2. 查看文件
2.1. tail/head
- tail查看文件末尾内容,默认查看10行
- head 查看文件开头内容,默认查看10行
# 查看/etc/passwd末尾5行
[root@kylin210 ~]# tail -5 /etc/passwd
# 查看文件末尾实时更新
[root@kylin210 ~]# tail -f /var/log/messages
# 查看文件开头5行
[root@kylin210 ~]# head -5 /etc/passwd
2.2. grep 过滤
grep命令 | 说明 |
-i | 过滤不区分大小写 |
-n | 过滤加上行号 |
-v | 过滤取反 |
# 找出/etc/passwd中包含root的行
[root@kylin210 ~]# grep 'root' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
# 在/etc/ssh/sshd_config中过滤出Prot的行
[root@kylin210 ~]# grep 'Port' /etc/ssh/sshd_config
Port 52113
# 在/etc/ssh/sshd_config中过滤出PermitRootLogin的行,不区分大小写
[root@kylin210 ~]# grep -i 'permitroot' /etc/ssh/sshd_config
PermitRootLogin yes
# 过滤出内容并显示行号,过滤/etc/ssh/sshd_config中Port行号
[root@kylin210 ~]# grep -n 'Port' /etc/ssh/sshd_config
[root@kylin210 ~]# grep -n 'PermitRoot' /etc/ssh/sshd_config
# 过滤/etc/passwd中包含/bin/bash的行
[root@kylin210 ~]# grep '/bin/bash' /etc/passwd
root:x:0:0:root:/root:/bin/bash
zbl:x:2001:2001::/home/zbl:/bin/bash
# 过滤/etc/passwd中不包含/bin/bash的行
[root@kylin210 ~]# grep -v '/bin/bash' /etc/passwd
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
2.3. less/more
- 按页查看文件内容,类似于vim
# less快捷键
q 退出
G 最后一行
g 第一行
100g 第100行
空格或ctrl + f按页查看 下一页
ctrl + b 上一页
# more
空格或ctrl + f按页查看 下一页
3. 日志分析
3.1. wc
- 统计行数
[root@kylin210 ~]# wc -l /etc/services
11473 /etc/services
3.2. | 管道
- 管道左边的命令输出,然后传递给管道右边命令
# 统计/etc/passwd中/bin/bash的数量
[root@kylin210 ~]# grep '/bin/bash' /etc/passwd | wc -l
1