HTTP基本认证,使用python [英] HTTP basic authentication, using python

查看:100
本文介绍了HTTP基本认证,使用python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的用户转到我域上的受保护目录。
.htaccess和.htpasswd都被创建并驻留在受保护的库中。

I want my users to go to a protected directory on my domain. Both .htaccess and .htpasswd are created and reside in the protected library.

要求用户名/密码组合的html是:

The html that asks for a username/password combination is:

<form method="post" enctype="multipart/form-data" action="bin/logintest.cgi">
Username: <input type="text" name="username" size="20" value="please enter.."><br>
Password: <input type="password" name="password" size="20"><BR>
<input name="submit" type="submit" value="login">

python cgi脚本为:

The python cgi script is:

#!/usr/bin/python

import urllib2
import base64
import cgi

form = cgi.FieldStorage()
username = form.getfirst("username")
password = form.getfirst("password")

request = urllib2.Request("http://www.mydomain.com/protecteddir/index.html")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)

print "Content-type: text/html\n\n"
print result

当我输入正确的用户名/密码组合时,生成的网页为:

When I enter a correct username/password combination, the resulting 'webpage' is:

>

我怀疑我的python代码打印结果不正确。我该如何解决?

I suspect that my python code "print result" is not correct. How can I fix this?

推荐答案

urlopen 返回的对象调用很像打开文件流,您需要读取以获取输出。

The returned object from a urlopen call is much like an open file stream, you need to read it to get the output.

更改打印结果打印结果.read()

result = urllib2.urlopen(request)

print "Content-type: text/html\n\n"
print result.read()






或者更改结果= urllib2.urlopen(request) result = urllib2.urlopen(request).read()

result = urllib2.urlopen(request).read()

print "Content-type: text/html\n\n"
print result






查看这些示例: http://docs.python.org/library/urllib2.html#examples

午餐盒

这篇关于HTTP基本认证,使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆