例1:监控磁盘使用率,高于80%的找出来,输出警告,发送邮件给管理员
$ df -h |grep -v Filesystem |awk '{print $1,$5}'|awk -F% '{print $1}'| awk '$2>80 {print $1"useage is over 80%,warning!!!"}' |mail -s "disk overuse problem" root
$ df -h | awk 'NR>1 {print $4"\t"$5}' | grep % | grep -v G | grep -v M | awk -F'%' '$1>80 {print $1"useage is over 80%,warning!!!"}' | mail -s "warring" root@localhost
$ df -k |grep -v Filesystem |awk '$3/$2>0.8 {print $1"useage is over 80%,warning!!!"}' |mail -s "disk overuse problem" root
例2:监控CPU 15分钟内的平均负载,如果超过5则发警告邮件给管理员
uptime |awk '$NF>5 {print "high load,warning"}' |mail -s 'xxxxx' root
例3:计算swap总量,使用量,剩余量,使用百分比,剩余百分比
格式要求为:
total used free used% free%
xxxxx xxxx xxxx xxx% xxx%
free |tail -1 |awk 'BEGIN {print "total\t\tused\tfree\tused%\tfree%"} {print $2"\t\t"$3"\t"$4"\t"$3/$2*100"%\t"$4/$2*100"%"}'
total used free used% free%
4096564 0 4096564 0% 100%
利用printf格式化输出
$ awk 'BEGIN {print "hello world"}'
hello world
$ awk 'BEGIN {printf "hello world"}'
hello world#
–从上面看到print和printf直接使用的主要区别就是printf不自动换行,需要使用\n来换行
$ awk 'BEGIN {printf "Hello world\n" }'
Hello world
格式:
printf {format_expression[,argument]}
两个主要的格式说明符是s和d,s代表字符串,d表示十进制整数
$ ls -l | grep -v total | awk '{printf ("%s的大小为%d\n",$NF,$5)}' |tail
Templates的大小为4096
test的大小为25
test1的大小为9
test.sh的大小为258
test*?[].sh的大小为0
user_passwd.txt的大小为60
Videos的大小为4096
while_useradd_shift.sh的大小为100
who.out的大小为320
内部变量的大小为76
$ awk -F: 'BEGIN {sum=0} $NF=="/sbin/nologin" {printf ("%s\t",$1); sum=sum+1} END {print "\n\n总共有:"sum"个"}' /etc/passwd
bin daemon adm lp mail uucp operator games gopher ftp nobody vcsa rpc mailnull smmsp nscd ntp oprofile pcap dbus avahi xfs named rpcusernfsnobody sshd haldaemon gdm avahi-autoipd sabayonapache squid ais mfs postfix distcache cacti
总共有:37个
1,利用awk把不允许登录的账号名打印出来(指第七列不是以/bin/bash结束的列),并统计个数
$ awk -F: 'BEGIN {sum=0} $NF!~"/bin/bash" {printf ("%s ",$1);sum=sum+1} END {print "\n\n总共的个数 为:"sum}' /etc/passwd
2,把系统上ssh的登录日志格式化打印成类似下面的
time hostname user ip port protocol
Jul-15 15:47:20 li root 2.2.2.35 6703 ssh2
time hostname user ip port protocol
Jul-15 15:47:27 li root 2.2.2.35 6704 ssh2
$ cat /var/log/secure |grep Accepted |awk '{print "***************************************************************************"}{print "time\t\thostname\tuser\tip\t\tport\tprotocol"}{print $1"-"$2,$3"\t"$4"\t\t"$9"\t"$11"\t"$13"\t"$14}{print "*************************************************************************"}'
$ cat /var/log/secure |grep Accepted |awk ' BEGIN{print "time\t\thostname\tuser\tip\t\tport\tprotocol"}{print $1"-"$2,$3"\t"$4"\t\t"$9"\t"$11"\t"$13"\t"$14}'