2013-12-17 99 views
0

我想写一个Python脚本,将自动登录到Web客户端。这是使用提供的用户名和密码自动登录到Web客户端。下面是我的Python代码:登录自动化

import httplib 
import urllib 
import urllib2 
header = { 
    'Host' : 'localhost.localdomain', 
    'Connection' : 'keep-alive', 
    'Origin' : 'localhost.localdomain', #check what origin does 
    'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20131029 Firefox/17.0', 
    'Content-Type' : 'application/x-www-form-urlencoded', 
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
    'Referer' : 'http://localhost.localdomain/mail/index.php/mail/auth/processlogin', 
    'Accept-Encoding' : 'gzip, deflate', 
    'Accept-Language' : 'en-US,en;q=0.5', 
    'Cookie' : 'atmail6=tdl3ckcf4oo88fsgvt5cetoc92' 
} 
content = { 
    'emailName' : 'pen.test.clin', 
    'emailDomain' : '', 
    'emailDomainDefault' : '', 
    'cssStyle' : 'original', 
    'email' : 'pen.test.clin', 
    'password' : 'aasdjk34', 
    'requestedServer' : '', 
    'MailType' : 'IMAP', 
    'Language' : '' 
} 

def runBruteForceTesting(): 
    url="http://localhost.localdomain/mail/index.php/mail/auth/processlogin" 
    for i in range (0,100): 
     data = urllib.urlencode(content) 
     request = urllib2.Request(url, data, header) 
     response = urllib2.urlopen(url, request) 
     print 'hi' 
     print request, response 
runBruteForceTesting() 

不过:我收到以下错误:

Traceback (most recent call last): 
    File "C:/Users/dheerajg/Desktop/python/log.py", line 39, in <module> 
    runBruteForceTesting() 
    File "C:/Users/dheerajg/Desktop/python/log.py", line 35, in runBruteForceTesting 
    response = urllib2.urlopen(url, request) 
    File "C:\Python27\lib\urllib2.py", line 127, in urlopen 
    return _opener.open(url, data, timeout) 
    File "C:\Python27\lib\urllib2.py", line 402, in open 
    req = meth(req) 
    File "C:\Python27\lib\urllib2.py", line 1123, in do_request_ 
    'Content-length', '%d' % len(data)) 
    File "C:\Python27\lib\urllib2.py", line 229, in __getattr__ 
    raise AttributeError, attr 
AttributeError: __len__ 

回答

1

您从urllib2.Request收到的request对象不具有 __len__方法;在你的情况下,这意味着你打电话urllib2.urlopen 错误的第二个参数。

看文档,写它需要一个字符串:

data may be a string specifying additional data to send to the server, or None if no such data is needed.

那么,关于调用urlopen这样的:

response = urllib2.urlopen(url, request.get_data())