您的位置:首页 > 运维架构 > 网站架构

用Python访问有密码保护的网站----附代码样例

2010-09-23 23:58 495 查看
做这个东西的初衷是希望能够控制家里的TP-Link的Mercury路由器,这个路由器只提供了Web接口;

 

因为家里用的是长城宽带,长城宽带的业务员告诉我,他们115开头的IP是电信提供的IP,访问大多数应用时速度会快很多,比如PPS或一些游戏服务器,我试过一次,确实有效;

但是不是每次启动路由器时,都能够自动获取到115网段开始的IP,大多数时220开头的,刚开始时我是自己到路由器上手工刷,一般刷5到6次可能能刷到115的IP;

 

刷得久了也挺烦的,就想能不能弄个脚本自动完成这个工作,于是就有了下面这些代码;

 

import string
import urllib2
import sys
import re
import base64
from urlparse import urlparse

print("--------------------------start----------------------------")
theurl = 'http://192.168.1.1/userRpm/StatusRpm.htm'
# if you want to run this example you'll need to supply
# a protected page with your username and password

username = 'admin'
password = 'admin'            # a very bad password

req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
# here we *want* to fail
pass
else:
# If we don't fail then the page isn't protected
print "This page isn't protected by authentication."
sys.exit(1)

if not hasattr(e, 'code') or e.code != 401:
# we got an error - but not a 401 error
print "This page isn't protected by authentication."
print 'But we failed for another reason.'
sys.exit(1)

authline = e.headers['www-authenticate']
# this gets the www-authenticate line from the headers
# which has the authentication scheme and realm in it

authobj = re.compile(
r'''(?:/s*www-authenticate/s*:)?/s*(/w*)/s+realm=['"]([^'"]+)['"]''',
re.IGNORECASE)
# this regular expression is used to extract scheme and realm
matchobj = authobj.match(authline)

if not matchobj:
# if the authline isn't matched by the regular expression
# then something is wrong
print 'The authentication header is badly formed.'
print authline
sys.exit(1)

scheme = matchobj.group(1)
realm = matchobj.group(2)
print(scheme)
print(realm)
# here we've extracted the scheme
# and the realm from the header
if scheme.lower() != 'basic':
print 'This example only works with BASIC authentication.'
sys.exit(1)

base64string = base64.encodestring(
'%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
handle = urllib2.urlopen(req, None, 5)
except IOError, e:
# here we shouldn't fail if the username/password is right
print "It looks like the username or password is wrong."
sys.exit(1)
thepage = handle.read()

#Get wanpara line
# strList = string.split(thepage, '/n')

# wanParaStr = ''
# for everyStr in strList:
# if ('var wanPara' in everyStr):
# nextIndex = strList.index(everyStr) + 1
# wanParaStr = strList[nextIndex]
# break

# wanParaList = string.split(wanParaStr, ', ')
# print(wanParaList[14])
# print(len(wanParaList))

print("--------------------------end----------------------------")


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息