Chinaunix首页 | 论坛 | 博客
  • 博客访问: 39593
  • 博文数量: 8
  • 博客积分: 81
  • 博客等级: 民兵
  • 技术积分: 80
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-10 16:38
文章分类

全部博文(8)

文章存档

2012年(2)

2011年(6)

我的朋友
最近访客

分类:

2011-05-07 22:19:42

看了下python的urllib2模块,这里做个总结。

  1. import urllib2
  2. import cookielib
  3. import urllib


  4. class Hi_login:
  5.     def __init__(self):
  6.         cookie = cookielib.CookieJar()
  7.         self.cookie = urllib2.HTTPCookieProcessor(cookie) ##### 生成cookie ###


  8.     def login(self,user,pwd):
  9.         url=''
  10.         postdata=urllib.urlencode({

  11.       'mem_pass':'on',
  12.     
  13.       'password':pwd
  14.        'Submit':'',
  15.       'tpl':'sp',
  16.       'tp_reg':'sp',
  17.       'u' :'',
  18.       'username':user})
  19.         ### proxy_support = urllib2.ProxyHandler({"http":""}) 然后加入opener方法里####
  20.         opener = urllib2.build_opener(self.cookie) ### 使用cookie ###
  21.         headers = { ####### dict结构,可以加入x-forward-for甚至refer等 #######
  22.        'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}

  23.         urllib2.install_opener(opener)
  24.         request = urllib2.Request(url,urllib.urlencode(postdata),headers = headers)
  25.         urllib2.urlopen(request)

  26. if __name__=='__main__':
  27.    pwd='123456'
  28.    user='xiaofu'
  29.    test=Hi_login()
  30.    test.login(user,pwd)

假如访问需要认证的页面比如nagios监控页面等,

 

  1. import urllib2
  2. password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

  3. url = ""

  4. password_mgr.add_password(None, url, user='abc',passwd='xxxxxx')

  5. handler = urllib2.HTTPBasicAuthHandler(password_mgr)

  6. opener = urllib2.build_opener(handler)

  7. urllib2.install_opener(opener)

  8. f=urllib2.urlopen(url)
  9. print f.code
返回结果200,否则就是401认证错误
阅读(918) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~