# vim maildir-delete.py
# -*- coding:UTF-8 -*-
#author: leikang
#createtime: 2019 10 10
#适用Python 2.6.6
#此脚本用于删除一个月以前的已读留言和三个月前的未读留言
import os,socket,fcntl,struct
import MySQLdb
import subprocess
import sys
import time
DAYS_C = 30
DAYS_N = 90
#获取本机ip
def get_local_ip(ifname):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',ifname[:15]))
ret = socket.inet_ntoa(inet[20:24])
finally:
s.close()
return ret
ip = get_local_ip("bond0")
print(ip)
#连接database
def getConn():
try:
conn = MySQLdb.connect(
host="x.x.x.x", #数据库地址
user="用户名", passwd="密码",
db="extmail",
charset="utf8")
return conn
except:
print("获取数据库连接出错...")
#查询用户目录
def getMailbox():
try:
sql = "select maildir from mailbox where mailhost = '%s';" %(ip)
conn = getConn()
cursor = conn.cursor()
maildir = cursor.execute(sql)
nRet= cursor.fetchall()
for i in nRet:
dir_1=i[0]
dir_2="/home/domains/"
c_dir=dir_2+dir_1+"/cur/"
n_dir=dir_2+dir_1+"/new/"
deletefile_cur(c_dir)
deletefile_new(n_dir)
except:
print("查询数据库出错")
#删除一个月前已读留言
def deletefile_cur(c_dir):
try:
for c_eachfile in os.listdir(c_dir):
c_filename = os.path.join(c_dir, c_eachfile)
if os.path.isfile(c_filename):
c_lastmodifytime = os.stat(c_filename).st_mtime
c_endfiletime = time.time() - 3600 * 24 * DAYS_C
if c_endfiletime > c_lastmodifytime:
os.remove(c_filename)
print "del %s success!!!" % c_filename
except:
print("删除已读留言出错")
#删除三个月前未读留言
def deletefile_new(n_dir):
try:
for n_eachfile in os.listdir(n_dir):
n_filename = os.path.join(n_dir, n_eachfile)
if os.path.isfile(n_filename):
n_lastmodifytime = os.stat(n_filename).st_mtime
n_endfiletime = time.time() - 3600 * 24 * DAYS_N
if n_endfiletime > n_lastmodifytime:
os.remove(n_filename)
print "del %s success!!!" % n_filename
except:
print("删除未读留言出错")
if __name__=="__main__":
getMailbox()
time.sleep(1)
print ('Deleting completed,success')