linux 系统管理 实战技巧

时间:2024-06-11 11:06:14

一、这篇文章讲了什么?

  这篇文章很有参考性哈。本来是想等一段时间有更多条技巧后在发布的,不过,突然发现,我是去年的今天在博客园落户了,祝我的博客一周岁快乐,希望以后多分享一些文章啦。所以就把草稿箱的其中一篇很实用性的linux小技巧分享给运维的基友们。后续该篇文章会一直更新新技巧哟。感谢童鞋们的关注哈。

  linux 系统管理 实战技巧

二、干货开始啦!

1.查看端口监听

[root@opm ~]# netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a,S[a]}'
CLOSE_WAIT
ESTABLISHED

2.查看端口监听状态统计

[root@Master ~]# netstat -aultn | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a,S[a]}'
TIME_WAIT
ESTABLISHED
LISTEN

可以看出当前系统有28253的端口在使用,

3.优化以上内核参数方式:

编辑/etc/sysctl.conf
net.ipv4.tcp_syncookies =
net.ipv4.tcp_tw_reuse =
net.ipv4.tcp_tw_recycle =
net.ipv4.tcp_fin_timeout =

修改完成后,sysctl -p 立即生效

4.修改流量大的web 服务器上,优化内核参数

net.ipv4.tcp_keepalive_time =
net.ipv4.ip_local_port_range =
net.ipv4.tcp_max_syn_backlog =
net.ipv4.tcp_max_tw_buckets =
#这几个参数,建议只在流量非常大的服务器上开启,会有显著的效果。一般的流量小的服务器上,没有必要去设置这几个参数。

5.查看linux 系统默认网关

ip route show | grep 'default' | awk '{print $3}'

6.过滤文件中的注释以及空格开头

egrep -v '^$|^#' /etc/rsyslog.conf

7.如何清空/删除 last记录

#清空最后登录
echo >/var/log/wtmp
#清空历史纪录
echo > ./.bash_history #在空格后输入命令,不记录到历史命令中,先输入到环境变量中
export HISTCONTROL=ignorespace

8.mysql密码忘记了,咋办?

vi /etc/my.cnf 添加下面一句话
[mysqld]
skip-grant-tables
重启mysqld。
之后登陆mysql系统,修改root 的密码
USE mysql;
UPDATE user SET Password = password ( 'new-password' ) WHERE User = 'root' ;
flush privileges
以上就可以了。

9.利用tcpdump 监控某个接口上的端口,如80 端口,-i 后跟网络接口,centos6上是eth0。-c 是抓的包数目

[root@web ~]# tcpdump -i eno16777984 'port 80' -c
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eno16777984, link-type EN10MB (Ethernet), capture size bytes
::42.142270 IP 192.168.30.65. > web.ichunqiu.com.http: Flags [S], seq , win , options [mss ,nop,wscale ,nop,nop,sackOK], length
::42.142360 IP web.ichunqiu.com.http > 192.168.30.65.: Flags [S.], seq , ack , win , options [mss ,nop,nop,sackOK,nop,wscale ], length
::42.142677 IP 192.168.30.65. > web.ichunqiu.com.http: Flags [.], ack , win , length
::42.142722 IP 192.168.30.65. > web.ichunqiu.com.http: Flags [S], seq , win , options [mss ,nop,wscale ,nop,nop,sackOK], length
::42.142759 IP web.ichunqiu.com.http > 192.168.30.65.: Flags [S.], seq , ack , win , options [mss ,nop,nop,sackOK,nop,wscale ], length
::42.143280 IP 192.168.30.65. > web.ichunqiu.com.http: Flags [S], seq , win , options [mss ,nop,wscale ,nop,nop,sackOK], length
::42.143317 IP web.ichunqiu.com.http > 192.168.30.65.: Flags [S.], seq , ack , win , options [mss ,nop,nop,sackOK,nop,wscale ], length
::42.143346 IP 192.168.30.65. > web.ichunqiu.com.http: Flags [.], ack , win , length
packets captured
packets received by filter
packets dropped by kernel

10.统计web服务器站点的日志,如apache 的access.log日志

  • 统计访问者的ip数目
[root@elk ~]# awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -n 25
124.126.211.201
123.125.2.108
139.59.253.208
  • 利用系统自带geoiplookup查看访问者的ip归属地(注:需要在本机先安装GeoIP软件)如下:
安装geoip软件
[root@elk nginx]# yum install GeoIP -y 查询ip归属地
[root@elk nginx]# cat access.log- | awk '{ print $1 }' | sort | uniq -c | sort -rn | head -n | \
awk '{ printf("%5d\t%-15s\t", $1, $2); system("geoiplookup " $2 " | cut -d \\: -f2 ") }'
124.126.211.201 CN, China
123.125.2.108 CN, China
139.59.253.208 AU, Australia
223.223.181.131 CN, China
93.174.93.99 NL, Netherlands
121.43.61.205 CN, China
36.110.44.114 CN, China
183.6.143.154 CN, China
116.226.39.94 CN, China
111.207.81.199 CN, China
106.81.231.217 CN, China
36.44.56.82 CN, China
112.80.61.114 CN, China
220.181.132.219 CN, China
61.141.94.68 CN, China
171.8.167.69 CN, China
101.226.33.240 CN, China
180.153.212.13 CN, China
180.153.206.20 CN, China
171.8.167.68 CN, China
101.226.89.119 CN, China
101.226.33.226 CN, China
101.226.102.97 CN, China
27.221.19.18 CN, China
  • 查看访问者404 错误页面的请求次数以及请求页面,并按降序排列
[root@elk nginx]# cat /var/log/nginx/access.log | awk '($9 ~ /404/)' | awk '{ print $7 }' | sort | uniq -c | sort -rn | head -n 
  • 查看访问者使用的User-Agent,并统计排序
[root@elk nginx]# cat /var/log/nginx/access.log | awk -F\" '{ print $6 }' | sort | uniq -c |sort -frn | head -n 25
  • 统计web服务器的 UV 量
[root@elk nginx]# cat /var/log/nginx/access.log | awk '{ print $1 }' | sort | uniq -c | wc -l
  • 统计当天的uv访问量
[root@elk nginx]# cat /var/log/nginx/access.log | grep `date '+%d/%b/%G'` | awk '{ print $1 }' | sort | uniq -c | wc -l
  • 统计当月的uv访问量
[root@elk nginx]# cat access.log | grep `date '+%b/%G'` | awk '{ print $1 }' | sort | uniq -c | wc -l
  • 根据返回的响应码进行排序
[root@elk nginx]# cat /var/log/nginx/access.log | awk '{ print $9 }' | sort | uniq -c | sort -rn

      "-"
  • 快速列出点击量最多的请求页面
[root@elk nginx]# cat /var/log/nginx/access.log | awk '{ print $7 }' | sort | uniq -c | sort -rn | head -n
/elasticsearch/packetbeat-*/_field_stats?level=indices
/favicon.ico
/bundles/src/ui/public/images/elk.ico
/
/elasticsearch/logstash-*/_field_stats?level=indices
/elasticsearch/.kibana/_refresh
/app/kibana
/elasticsearch/_msearch?timeout=&ignore_unavailable=true&preference=
/elasticsearch/_msearch?timeout=&ignore_unavailable=true&preference=
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
/elasticsearch/.kibana/index-pattern/_search?fields=
/bundles/src/ui/public/images/kibana.svg
/bundles/kibana.bundle.js?v=
/bundles/node_modules/font-awesome/fonts/fontawesome-webfont.woff2
/bundles/commons.style.css?v=
/bundles/commons.bundle.js?v=
/bundles/kibana.style.css?v=
/elasticsearch/topbeat-*/_field_stats?level=indices
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
/elasticsearch/.kibana/visualization/_search?size=
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
/elasticsearch/.kibana/dashboard/_search?size=
/elasticsearch/_mget?timeout=&ignore_unavailable=true&preference=
  • 实时的查看请求者ip、http方法、响应码、请求的页面
[root@elk nginx]# tailf /var/log/nginx/access.log | awk '{ printf("%-15s\t%s\t%s\t%s\n", $1, $6, $9,$7) }'
60.191.52.254 "HEAD 401 http://115.236.176.134:3434/
141.212.122.160 "GET 401 /
101.200.215.149 "GET 401 /manager/html
114.44.57.4 "CONNECT 400 126mx01.mxmail.netease.com:25
187.160.7.218 "GET 401 /cgi/common.cgi
187.160.7.218 "GET 401 /stssys.htm
187.160.7.218 "GET 401 /
187.160.7.218 "POST 401 /command.php
218.75.70.3 "GET 401 /
163.172.173.181 "GET 401 http://www.baidu.com/cache/global/img/gs.gif
123.125.2.108 "GET 200 /
123.125.2.108 "GET 200 /app/kibana
123.125.2.108 "GET 304 /bundles/commons.style.css?v=10000
  • 跟上面的类似,只是在第四个字段加了个GeoIP解析归属地,如下:
[root@elk nginx]# tailf /var/log/nginx/access.log | awk '{
"geoiplookup " $ " | cut -d \\: -f2 " | getline geo
printf("%-15s\t%s\t%s\t%-20s\t%s\n", $, $, $, geo, $);}'
123.125.2.108 "GET 304 CN, China /bundles/src/ui/public/images/kibana.svg
123.125.2.108 "POST 200 CN, China /elasticsearch/_mget?timeout=0&ignore_unavailable=true&preference=1472922034187
123.125.2.108 "POST 200 CN, China /elasticsearch/.kibana/index-pattern/_search?fields=
123.125.2.108 "GET 200 CN, China /elasticsearch/.kibana/_mapping/*/field/_source?_=1472922034556
123.125.2.108 "POST 200 CN, China /elasticsearch/_mget?timeout=0&ignore_unavailable=true&preference=1472922034187
123.125.2.108 "GET 304 CN, China /bundles/node_modules/font-awesome/fonts/fontawesome-webfont.woff2
  • 显示非法代理的访问者
[root@elk nginx]# awk -F\" '($6 ~ /^-?$/)' /var/log/nginx/access.log | awk '{ print $1 }' | sort | uniq
114.44.57.4
183.129.160.229
218.75.70.3
61.231.3.98

11.linux中利用python开启临时的web下载服务,访问端口是88,http://ip:88/,端口可以自定义其它的,避免与系统其它的冲突

[root@web ~]# python -m SimpleHTTPServer 
Serving HTTP on 0.0.0.0 port  ...

12.vim 复制多行内容

:, co
意思是复制第1行到10行之间的内容到第10行后面。 :,- co
意思是复制第1行到文件最后一行之间的内容到第10行后面。

13.快速删除文件内每行中的的空格
  删除行首的空格

[root@hcloud webtest]# sed -i 's/^[ \t]*//g' filename

  删除行尾的空格

[root@hcloud webtest]# sed -i 's/[ \t]*$//g' filename

14.windows 编写的脚本到linux 上运行,编码错误解决方法:

:set ff=unix
:wq

15.yum 安装软件时,出现以下提示:

Resolving Dependencies
There are unfinished transactions remaining. You might consider running yum-complete-transaction first to finish them.

  解决方法:

[root@test ]# yum-complete-transaction

16.用grep 过滤文件中的空行已经#注释,并将显示出来的内容标上行号

grep -Ev  '^$|^#' hosts >test.txt && cat -n test.txt && rm -f test.txt

17.假如server的某个进程的日志由于访问量或者其它错误bug导致日志大小暴增,且该日志分区空间即将不足,需要在线清空该日志(清理前先备份)

  解决方法,有以下几种:

  1)

cat /dev/null > logfile

  2)

dd if=/dev/null of=logfile

  3)

rm logfile

18.利用linux 自带工具实时检测网卡流量

  1)ifconfig

[root@zabbix- ~]# watch -d ifconfig eth0

  2)/proc/net/dev

[root@zabbix- ~]# watch -d cat /proc/net/dev

19.模拟cpu升高(可后台运行n次,每个进程的使用率*n 就是总的cpu利用率)

  1)

dd if=/dev/zero of=/dev/null

  2)

fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd

  3)

yes > /dev/null &

  4) 哈哈,这个慎用。。。。。!!!!

:(){ :|:& };:

20. 查看浏览器内部的缓存,谷歌为例,浏览器内输入以下内容:

chrome://net-internals/#dns

21. 使用awk 做百分比计算(用-v 连接外部变量)

如下图:

linux 系统管理 实战技巧

[root@docker ~]# awk -v a=$a -v b=$b -v c=$c 'BEGIN{printf "%2.f%\n",((a - b) / c) * c}'

22. 将查看man手册时的终端设置为有颜色高亮的,添加如下:

修改/root/.bashrc 文件,添加到文末

# Set have color's terminal
export LESS_TERMCAP_mb=$'\E[01;31m' # begin blinking
export LESS_TERMCAP_md=$'\E[01;38;5;74m' # begin bold
export LESS_TERMCAP_me=$'\E[0m' # end mode
export LESS_TERMCAP_se=$'\E[0m' # end standout-mode
export LESS_TERMCAP_so=$'\E[38;5;246m' # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\E[0m' # end underline
export LESS_TERMCAP_us=$'\E[04;38;5;146m' # begin underline

23.断点续传下载文件

使用wget 下载文件,-c 断点续传

wget -c http://www.niu.com/filename

使用rsync 走ssh 协议拷贝文件, -e 参数,是指定远程ssh 的服务端口为8080

rsync -azP -e "ssh -p 8080" root@10.10.0.88:/root/-/* ./

24.修改ulimit 文件大小,并且加入/etc/profile最后一行中,已经看到生效了,但是scp 传输给服务器时,文件依旧会中断

ulimit -f unlimited

后来觉得是ssh的问题,因为scp 依靠的是ssh 协议,所以重启了服务器上的ssh 服务。从客户端上继续上传文件成功。所以应该在不重启主机的情况下,只要重启相关使用的程序即可

service sshd restart

25.批量修改数据库中的ip记录成统一格式,如下所示

在库里,有一批服务器需要修改ip子网网段地址,如原来都是192.168.10.x, 现在要统一修改成10.10.0.0,那么可以使用该sql 语句

MariaDB [cloud]> update d_host set HostIP=concat('10.10.0',substring(hostip,));

26.xargs 的一般使用技巧

处理每行显示的单词数量,如下:没有使用xargs处理的方式:

[root@docker test]# ls *.html
baaiqzryca_oldboy.html fhqvkawqgv_oldboy.html mdxppexnhr_oldboy.html ozkqzhpcof_oldboy.html xkkclfmfsx_oldboy.html
eqxvzmbthe_oldboy.html hckcitirol_oldboy.html okpolqsrlz_oldboy.html vhktzmneui_oldboy.html yytrltjhjy_oldboy.html

使用xargs 加 -n number 处理的方式,如下:

[root@docker test]# ls *.html | xargs -n
baaiqzryca_oldboy.html eqxvzmbthe_oldboy.html
fhqvkawqgv_oldboy.html hckcitirol_oldboy.html
mdxppexnhr_oldboy.html okpolqsrlz_oldboy.html
ozkqzhpcof_oldboy.html vhktzmneui_oldboy.html
xkkclfmfsx_oldboy.html yytrltjhjy_oldboy.html
[root@docker test]# ls *.html | xargs -n
baaiqzryca_oldboy.html
eqxvzmbthe_oldboy.html
fhqvkawqgv_oldboy.html
hckcitirol_oldboy.html
mdxppexnhr_oldboy.html
okpolqsrlz_oldboy.html
ozkqzhpcof_oldboy.html
vhktzmneui_oldboy.html
xkkclfmfsx_oldboy.html
yytrltjhjy_oldboy.html

还有一个功能,是xargs 的 -I {} 参数 将管道前的标准输出,传递给xargs参数,后面可以把 {}当作参数传递给它其它命令,如下:

[root@docker test]# ls *.html | xargs -I {} cp {} /tmp/test2/.

上面的意思就是将当前目录 所有以.html 结尾的文件,cp到 /tmp/test2目录下。(备注:这个目的用xargs 有点多此一举啦,直接cp *.html dest 也是可以的)

27.curl 构造参数,传参,提交请求

curl -d 'Key=xxx&phone=xxx&sms=xxx' -X POST -v api接口地址

28.如何杀死僵尸进程 Z

找出该Z进程的父进程,进而杀死

kill $(ps -A -ostat,ppid | awk '/[zZ]/{print $2}')

孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。

僵尸进程:一个进程使用fork创建子进程,如果子进程退出,而父进程并没有调用wait或waitpid获取子进程的状态信息,那么子进程的进程描述符仍然保存在系统中。这种进程称之为僵死进程。详细参考内容

29.永远的擦除硬盘数据,比rm更危险,谨慎操作

[root@node- ~]# shred --help
Usage: shred [OPTION]... FILE...
Overwrite the specified FILE(s) repeatedly, in order to make it harder
for even very expensive hardware probing to recover the data. Mandatory arguments to long options are mandatory for short options too.
-f, --force change permissions to allow writing if necessary
-n, --iterations=N overwrite N times instead of the default ()
--random-source=FILE get random bytes from FILE
-s, --size=N shred this many bytes (suffixes like K, M, G accepted)
-u, --remove truncate and remove file after overwriting
-v, --verbose show progress
-x, --exact do not round file sizes up to the next full block;
this is the default for non-regular files
-z, --zero add a final overwrite with zeros to hide shredding
--help display this help and exit
--version output version information and exit If FILE is -, shred standard output. Delete FILE(s) if --remove (-u) is specified. The default is not to remove
the files because it is common to operate on device files like /dev/hda,
and those files usually should not be removed. When operating on regular
files, most people use the --remove option. CAUTION: Note that shred relies on a very important assumption:
that the file system overwrites data in place. This is the traditional
way to do things, but many modern file system designs do not satisfy this
assumption. The following are examples of file systems on which shred is
not effective, or is not guaranteed to be effective in all file system modes: * log-structured or journaled file systems, such as those supplied with
AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.) * file systems that write redundant data and carry on even if some writes
fail, such as RAID-based file systems * file systems that make snapshots, such as Network Appliance's NFS server * file systems that cache in temporary locations, such as NFS
version clients * compressed file systems In the case of ext3 file systems, the above disclaimer applies
(and shred is thus of limited effectiveness) only in data=journal mode,
which journals file data in addition to just metadata. In both the
data=ordered (default) and data=writeback modes, shred works as usual.
Ext3 journaling modes can be changed by adding the data=something option
to the mount options for a particular file system in the /etc/fstab file,
as documented in the mount man page (man mount). In addition, file system backups and remote mirrors may contain copies
of the file that cannot be removed, and that will allow a shredded file
to be recovered later. Report shred bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'shred invocation'

30.过滤ip 地址的通用方法

echo My ip address is 192.168.8.88 | grep -E -o "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"

或

echo My ip address is 192.168.8.88 | egrep -o "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"

40.在mysql 中,为用户修改远程授权

MariaDB [(none)]> update mysql.user set Host='%' where Host='::1'

更新历史:

2017/06/01: 更新curl构造参数、如何杀死僵尸进程;

注意:该文章属于作者原创,如有转载或者分享,请注明出处以及该文章链接:http://www.cnblogs.com/hanyifeng/p/5440274.html