说明:
很久没弄邮箱了,老早就有想法写个脚本自动生成全局地址本,每次添加一个用户还要SSH连到服务器加个地址本,麻烦死了,想必大家都有这样的情况;这周有点空就研究了下python语言,写了这么个脚本出来,共享出来一起学习。
1、安装
一般情况下系统已默认安装,我的操作系统centos6.5装的是python2.4.3
yum install -y MySQL-python
2、脚本
cd /var/www/excuite/extmail vi globabook.py
#!/usr/bin/python #coding=utf-8 #save in /var/www/excuite/extmail #yum install -y MySQL-python #apt-get install python-MySQLdb import MySQLdb def SqlResult(sqlcmd): try: conn = MySQLdb.connect(host='localhost',user='root',passwd='password',db='extmail',port=3306) # 定义连接,修改登陆账号成你自己的 cur = conn.cursor() cur.execute(sqlcmd) result = cur.fetchall() cur.close() conn.close() return result except MySQLdb.Error,e: print 'mysql error msg:',e def Books(): d = {} domains = 'select domain from domain;' for domain in SqlResult(domains): root = domain[0].split('.')[0] if root == 'defaultdomain': #defaltdomain改成你的默认域名 f = 'globabook.cf' else: f = 'globabook-'+root+'.cf' d[domain[0]] = f return d def Users(domain): us = ["Name,Mail,Company,Phone"] usernames = "select name,username from mailbox where active='1' and domain='%s';" % domain for user in SqlResult(usernames): u='\n"'+user[0].decode("utf-8")+'","'+user[1]+'"' us.append(u) return us def Main(): bs = Books() for dm in bs: f = bs.get(dm) book = open(f,"w") us = Users(dm) for user in us: book.write(user.encode("utf-8")) book.close() print "Congratulations, the %s is update!" % f print "ALL Globabook Files Are Updated !" Main()
3、执行脚本
chmod +x globabook.py python globabook.py
4、添加任务,每日刷新
crontab -e 0 0 * * * cd /var/www/extsuite/extmail && /usr/bin/python globabook.py
5、脚本讲解
SqlResult函数用来获取数据库数据;Books函数返回一个字典,键是域名,值是域名对应的地址本文件名称;Users函数用来获取数据库中用户数据,只取"名字"和"邮箱地址";主函数Main调用以上函数,将用户数据按域名存入相应的地址本文件;每天执行时会清空地址本重新写入数据。