我想开发一个 Web 界面,允许 Linux 系统的用户执行与其帐户相关的某些任务。我决定在 Apache 上使用 Python 和 mod_python 编写站点的后端。为了对用户进行身份验证,我想我可以使用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 有权读取影子。我不确定我将如何规避这一点,但至少现在我知道问题出在哪里!