Description
Long time did not get the mailbox, the old have the idea to write a script automatically generated global address book, each time you add a user also SSH to the server add an address this, the trouble died, presumably everyone has such a situation; this week, a little empty research the next Python language, write a script out, share together to learn.
1. Installation
in general, the system is installed by default, my operating system centos6.5 is python2.4.3
Yum Install-y Mysql-python
2. Scripts
Cd/var/www/excuite/extmailvi globabook.py
#!/usr/bin/python#coding=utf-8#save in /var/www/excuite/extmail#yum install -y Mysql-python#apt-get install python-mysqldbimport mysqldbdef sqlresult (sqlcmd): try: conn = mysqldb.connect (host= ' localhost ', user= ' root ', passwd= ' password ', db= ' Extmail ', port=3306) # Define the connection, modify the login account to your own cur = conn.cursor () cur.execute (sqlcmd) result = cur.fetchall () cur.close () conn.close () return result except mysqldb.error,e: print ' mysql error msg: ', Edef 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 DD ef 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: &Nbsp; book.write (User.encode ("Utf-8")) book.close () print "congratulations, the % s is update! " % f print "all globabook files are updated !" main ()
3. Execute script
chmod +x Globabook.pypython globabook.py
4, add tasks, daily refresh
CRONTAB-E0 0 * * * python/var/www/extsuite/extmail/globabook.py
5. Script explanation
The Sqlresult function is used to get the database data; the books function returns a dictionary, the key is the domain name, the value is the name of the address of the domain name, the users function is used to obtain the user data in the database, only "first name" and "Mailbox address"; main function main calls the above function, The user data is deposited into the corresponding address file by domain name, and the address book is re-written to the data when executed daily.
This article is from the "Moon Ching Xing Fei" blog, please be sure to keep this source http://ywzhou.blog.51cto.com/2785388/1725667
Postfix mailbox (15): Global address this automatically generated script