习题1:统计内存使用

要求:写一个脚本计算一下linux系统所有进程占用内存大小的和。(提示:使用ps或者top命令)

参考答案:

#!/bin/bash
# date:2018年2月6日
# 使用top计算
echo -n "top统计结果:";top -bn1|sed '1,7'd|awk '{(sum=sum+$6)}; END {print sum}'
# 使用ps计算
echo -n " ps统计结果:";ps aux|grep -v 'RSS'|awk '{(sum=sum+$6)}; END {print sum}'
# 使用for循环
sum=0
for men in `ps aux|grep -v 'RSS'|awk '{print $6}'`
do
   sum=$[$sum+$men]
done
echo "(ps)The total memory is $sum""k"


习题2:设计监控脚本

要求:设计一个脚本,监控远程的一台机器(假设ip为123.23.11.21)的存活状态,当发现宕机时发一封邮件给你自己

提示: 1. 你可以使用ping命令   ping -c10 192.168.139.128
            2. 发邮件脚本可以参考 mail.py
            3. 脚本可以搞成死循环,每隔30s检测一次

参考答案:

#!/bin/bash
# date:2018年2月6日
ip="192.168.139.128"
email="your_email@163.com"
while :
do 
   ping -c10 $ip >/dev/null 2>/dev/null
   if [ $? -ne "0" ];then
	python /root/shell/mail.py "$email" "$ip down" "$ip is down..."
   else
	echo "ping must be sth wrong ..."
   fi
sleep 30
done

邮件脚本mail.py

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import os,sys
reload(sys)
sys.setdefaultencoding('utf8')
import getopt
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from  subprocess import *
def sendqqmail(username,password,mailfrom,mailto,subject,content):
    gserver = 'smtp.163.com'
    gport = 25
    try:
        msg = MIMEText(unicode(content).encode('utf-8'))
        msg['from'] = mailfrom
        msg['to'] = mailto
        msg['Reply-To'] = mailfrom
        msg['Subject'] = subject
        smtp = smtplib.SMTP(gserver, gport)
        smtp.set_debuglevel(0)
        smtp.ehlo()
        smtp.login(username,password)
        smtp.sendmail(mailfrom, mailto, msg.as_string())
        smtp.close()
    except Exception,err:
        print "Send mail failed. Error: %s" % err
def main():
    to=sys.argv[1]
    subject=sys.argv[2]
    content=sys.argv[3]
    sendqqmail('your_email@163.com','邮箱的授权码','your_email@163.com',to,subject,content)
if __name__ == "__main__":
    main()