在使用mod_python的脚本中使用pam_python
我想开发一个网页界面,让Linux系统的用户可以进行一些与他们账户相关的操作。我决定用Python和mod_python在Apache上写这个网站的后台。为了验证用户身份,我想用python_pam来查询PAM服务。我对这个模块自带的示例进行了修改,得到了以下代码:
# out is the output stream used to print debug
def auth(username, password, out):
def pam_conv(aut, query_list, user_data):
out.write("Query list: " + str(query_list) + "\n")
# List to store the responses to the different queries
resp = []
for item in query_list:
query, qtype = item
# If PAM asks for an input, give the password
if qtype == PAM.PAM_PROMPT_ECHO_ON or qtype == PAM.PAM_PROMPT_ECHO_OFF:
resp.append((str(password), 0))
elif qtype == PAM.PAM_PROMPT_ERROR_MSG or qtype == PAM.PAM_PROMPT_TEXT_INFO:
resp.append(('', 0))
out.write("Our response: " + str(resp) + "\n")
return resp
# If username of password is undefined, fail
if username is None or password is None:
return False
service = 'login'
pam_ = PAM.pam()
pam_.start(service)
# Set the username
pam_.set_item(PAM.PAM_USER, str(username))
# Set the conversation callback
pam_.set_item(PAM.PAM_CONV, pam_conv)
try:
pam_.authenticate()
pam_.acct_mgmt()
except PAM.error, resp:
out.write("Error: " + str(resp) + "\n")
return False
except:
return False
# If we get here, the authentication worked
return True
我的问题是,这个函数在简单脚本中和通过mod_python使用时表现不一样。为了说明这一点,我写了几个简单的例子:
my_username = "markys"
my_good_password = "lalala"
my_bad_password = "lololo"
def handler(req):
req.content_type = "text/plain"
req.write("1- " + str(auth(my_username,my_good_password,req) + "\n"))
req.write("2- " + str(auth(my_username,my_bad_password,req) + "\n"))
return apache.OK
if __name__ == "__main__":
print "1- " + str(auth(my_username,my_good_password,sys.__stdout__))
print "2- " + str(auth(my_username,my_bad_password,sys.__stdout__))
脚本的结果是:
Query list: [('Password: ', 1)]
Our response: [('lalala', 0)]
1- True
Query list: [('Password: ', 1)]
Our response: [('lololo', 0)]
Error: ('Authentication failure', 7)
2- False
但mod_python的结果是:
Query list: [('Password: ', 1)]
Our response: [('lalala', 0)]
Error: ('Authentication failure', 7)
1- False
Query list: [('Password: ', 1)]
Our response: [('lololo', 0)]
Error: ('Authentication failure', 7)
2- False
我不明白为什么auth
函数在输入相同的情况下返回的值却不一样。有没有人知道我哪里出错了?如果需要的话,这是原始脚本,希望能帮到你。
非常感谢!
编辑:好的,我找到了错误。我是以root用户运行脚本的,而mod_python是以网页服务器的用户运行脚本。只有root用户有权限读取shadow文件。我不太确定怎么解决这个问题,但至少现在我知道问题出在哪里了!
1 个回答
0
看起来你需要开启Apache才能使用PAM认证。你可以看看这个网站:http://www.debianhelp.co.uk/apachepam.htm
你也可以看看这个网站:http://inming.net/?p=86