一个Python脚本,让OpenVPN使用postfix邮箱帐号进行身份认证

这几天配置OpenVPN,使用了用户名密码的身份认证方式,借助已有的postfix邮箱帐号,省去了再为每个人设置用户名密码的麻烦。

原理很简单,OpenVPN服务器配置里有这样一句:

auth-user-pass-verify /etc/openvpn/auth-postfix-mailbox.py via-env

就是说要用/etc/openvpn/auth-postfix-mailbox.py这个脚本来验证用户名和密码。用户名和密码如何传递给它呢?via-env,环境变量。

脚本如下:

#!/usr/bin/env python

import os
import sys
from MySQLdb import *
import md5crypt

def auth(username, password):
conn = connect (host = 'localhost',
user = 'dbuser',
passwd = 'dbpasswd',
db = 'postfix')
cursor = conn.cursor()
cursor.execute("""
select password from mailbox
where username=%s
and active=1
""", (username))
row = cursor.fetchone()
if row == None:
return 1
crypt = md5crypt.md5crypt(password, row[0])
cursor.execute("""
select * from mailbox
where username=%s
and password=%s
and active=1
""", (username,crypt))
row = cursor.fetchone()
cursor.close()
conn.close()
if row == None:
return 1
return 0

def main():
status = 0
try:
username = os.environ['username']
password = os.environ['password']
status = auth(username, password)
except:
sys.exit(1)

sys.exit(status)

if __name__ == "__main__":
main()

由于postfix使用md5认证,所以需要用md5crypt这个模块,从这里可以下载到。

2 Replies to “一个Python脚本,让OpenVPN使用postfix邮箱帐号进行身份认证”

  1. Hi, wolfg,

    我也再用T43 ,安装了ubuntu,你的博客很有意思,可以交个朋友么?我的email地址如上,如果要加msn也可以shewenhao@hotmail.com

Comments are closed.