Shell實戰訓練營Day12
1.以日期格式(xxxx-xx-xx)每日生成一個檔案, 例如生成的檔名為2019-01-02.log, 並且把磁碟的使用情況寫到到這個檔案中, 不用考慮cron,僅僅寫指令碼即可
#! /bin/bash
d=date +%F
disklogfile=$d.log
df -h > $disklogfile
#!/bin/bash
d=date +%F
dir=/data/logs/disklog
if [ ! -d $dir ]
then
mkdir -p $dir
fi
df -h > $dir/$d.log
find $dir/ -mtime +365 |xargs rm
2.統計指定檔案每個IP訪問量有多少
(制定檔案如下:112.111.12.248 – [25/Sep/2013:16:08:31 +0800]formula-x.haotui.com “/seccode.php?update=0.5593110133088248″ 200″
61.147.76.51 – [25/Sep/2013:16:08:31 +0800]xyzdiy.5d6d.com “/attachment.php?aid=4554&k=9ce51e2c376bc861603c7689d97c04a1&t=1334564048&fid=9&sid=zgohwYoLZq2qPW233ZIRsJiUeu22XqE8f49jY9mouRSoE71″ 301″http://xyzdiy.×××thread-1435-1-23.html
#! /bin/bash
awk '{print $1}' logfiel|sort |uniq -c |sort -n -r //logfile 為制定檔名
3.統計系統所有程序佔用記憶體之和
#!/bin/bash
sum=0
for n in ps aux |grep -v 'TIME COMMAND'|awk '{print $6}'
do
sum=$[$sum+$n]
done
echo $sum
4.監控遠端的一臺機器(假設ip為180.163.26.39)的存活狀態,當發現宕機時傳送一封郵件
#!/bin/bash
n=ping -c5 180.163.26.39|grep 'packet' |awk -F '%' '{print $1}' |awk '{print $NF}'
if [ -z "$n" ]
then
echo "script error " //判斷返回值是否有誤
python mail.py $m "script error" "variable is null"
exit
else
n1=echo $n|sed 's/[0-9]//g'
if [ -n "$n" ] //判斷返回值是否有誤
then
echo "script error "
python mail.py $m "script error" "variable is null"
exit
fi
fi
python 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.qq.com'
gport = 25
try:
# msg = MIMEText(unicode(content).encode('utf-8')) //如果傳送的郵件有亂碼,可以嘗試把這行改成如下:
msg = MIMEText(content,'plan','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]
##定義QQ郵箱的賬號和密碼,你需要修改成你自己的賬號和密碼(請不要把真實的使用者名稱和密碼放到網上公開,否則你會死的很慘)
sendqqmail('[email protected]','aaaaaaaaaa','[email protected]',to,subject,content)
if name == "main":
main()
#####指令碼使用說明######
#1. 首先定義好指令碼中的郵箱賬號和密碼
#2. 指令碼執行命令為:python mail.py 目標郵箱 "郵件主題" "郵件內容"
5.找到/123目錄下所有後綴名為.txt的檔案 ——批量修改.txt為.txt.bak——把所有.bak檔案打包壓縮為123.tar.gz——批量還原檔案的名字,即把增加的.bak再刪除
#!/bin/bash
find /123/ -type f -name "*.txt" > /tmp/txt.list
for f in cat /tmp/txt.list
do
mv $f $f.bak
done
#find /123/ -type f -name .txt |xargs -i mv {} {}.bak //同上 批量新增.bak字尾
#find /123/ -type f -name .txt -exec mv {} {}.bak \; //同上 批量新增.bak字尾
for f in cat /tmp/txt.list
do
echo -n $f.bak
done > /tmp/txt.bak.list
tar -czvf 123.tar.gz cat /tmp/txt.bak.list |xargs
for f in cat /tmp/txt.list
do
mv $f.bak $f
done