Python implementation of login Discuz! Forum common code sharing

  • 2020-04-02 13:50:37
  • OfStack

The code is as follows:


#coding:gbk
import urllib2,urllib,cookielib,re

'''
  Universal landing DZ BBS 
  Parameters that parms:
   username: The user name ( mandatory ),
   password : password ( mandatory ),
   domain: Domain name of the website, note the format must be: http://www.xxx.xx/( mandatory ),
   answer: Answers to questions ,
   questionid: The problem ID,
   referer: Jump address 
   
  Variable keyword parameters are used here ( Relevant information can refer to the manual )
'''
def login_dz(**parms):

  # Initialize the 
  parms_key = ['domain','answer','password','questionid','referer','username']
  arg = {}
  for key in parms_key:
    if key in parms:
      arg[key] = parms[key]
    else:
      arg[key] = ''
      
  #cookie Set up the 
  cookieFile = './kan_cookies.dat'
  cookie = cookielib.LWPCookieJar()
  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

  # To obtain formhash
  pre_login = arg['domain']+'member.php?mod=logging&action=login&infloat=yes&handlekey=login&inajax=1&ajaxtarget=fwin_content_login'
  c = opener.open(pre_login).read()
  cookie.save(cookieFile)
  patt = re.compile(r'.*?name="formhash".*?value="(.*?)".*?')
  formhash = patt.search(c)
  if not formhash:
    raise Exception('GET formhash Fail!')
  formhash = formhash.group(1)

  # landing 
  postdata = {
   'answer':arg['answer'],
   'formhash':formhash,
   'password':arg['password'],
   'questionid':0 if arg['questionid']=='' else arg['questionid'],
   'referer':arg['domain'] if arg['referer']=='' else arg['referer'],
   'username':arg['username'],
    }

  postdata = urllib.urlencode(postdata)
  req = urllib2.Request(
    url= arg['domain']+'member.php?mod=logging&action=login&loginsubmit=yes&handlekey=login&loginhash=LCaB3&inajax=1',
    data=postdata
    )
  c = opener.open(req).read(300)
  flag = ' Logon failure  %s'%arg['username']
  if 'succeedhandle_login' in c:
    flag = True
  return flag


# Use example: basic parameters login 
user='xxx'
pwd='xxx'
dom='http://www.discuz.net/' # Another test site: http://bbs.jb51.net/
try:
  flag = login_dz(username=user,password=pwd,domain=dom)
  print(flag)
except Exception,e:
  print('Error:',e)


Related articles: