腳本內容以下:python
vim ~/shell/clean_cache.pygit
1 #!/usr/bin/python 2 #conding=utf-8 3 #該腳本用於清理服務器當中佔用內存20G以上,運行時間超過3小時以上(或1天以上的)進程。 4 import os 5 #import psutil 6 7 pslist = os.popen('ps -auxf','r').readlines() 8 for list in pslist: 9 p = list.split() #以空格分割 10 user = p[0] #用戶 11 pid = p[1] #進程PID 12 mem = p[4] #內存 13 day = p[8] #日期 14 t = p[9] #運行時間 15 if mem.isdigit() and int(mem) > 20000000: #剔除第一行vsz而且保證佔用內存大於20G 16 if day.isalnum(): #判斷日期是否爲今天 17 print day.isalnum() 18 print "progess running over a day,kill it now!" 19 cmd = "kill -9 "+pid 20 os.popen(cmd) 21 if int(t.split(':')[0]) > 180: #判斷運行時間超過3小時 22 print t.split(':')[0] 23 print "this progesss have run over 2 hour,kill it now!" 24 cmd = "kill -9 "+pid 25 os.popen(cmd) 26 else: 27 continue
以上是單臺的服務器的腳本內容,其實能夠結合crontab或者能夠與ansible的script模塊來批量執行,會達到更好的效果!shell
舉例: ansible all -m script -s -a "/home/xxx/shell/clean_cache.sh"vim