python simulates logging in and keeps the cookie method detailed

  • 2020-05-27 06:23:26
  • OfStack

preface

Recently, after crawling the data of nosec.org, I have seen that you need to simulate login to get cookie before accessing the data you want to capture. The important thing is that the field authenticity_token in form of the login page of nosec.org will be automatically generated every time you visit the login page, and it will be sent to the server by POST like your user name and password.

After one study, it was found that when you directly visit the website login interface, the response header of the server will have an Set-Cookie field, as follows:


_nosec_session=ZTlHNmxuZXE4R0s1UXpsVUxGRTNPblNBWFd2TXU4TU9aNWVJM2lyLzNFY0pLeUdNMDY1cmZqanpkc0ppaGtjU
i9kTGdWenBrNXJKenNqbnN2YUxucE1DRW5UMHNTR1RxWDZPeGlLazllTmY1czVpYWplazJXdWkvZS9wUHJpc1Jya3ZzcmNVMytPR
it2T1dEcGx4bHNDTTVzSmVTb0xhSjRycE03QUl5RXE5Z2tZWG1mTHFBWGx1QW52QjBURi8rLS1acE8yeVRtMFRZR1JWdExneStwdmpRPT0
%3D--a6ccd9a12a8af5c8b5fb6625c24bb4db0398c503; path=/; HttpOnly

In addition, the form of page form has an input of authenticity_token, which reads as follows:


<input type="hidden" name="authenticity_token" value="cGdhqVxDMRndpKbpvIV66wfEQlGf4Rz6UtXqsf79brEvFveHw2rCc6uz3euFEyUlpuA0azt5uNhnmrUiCaAyUg==" />

Previously, the value of _nosec_session was analyzed according to the logic of the back end. After decryption and various xx methods, the value of authenticity_token was obtained. Then, the value of username and password post were taken along with it. Always think with the back end of the problem, have to walk recently are not walking well. So just grab the generated authenticity_token value in the page and go with POST.

Using the requests library Session() The method is really easy to use, much more convenient than taking cookielib directly in the early days.

code

The login method of class XXX is used to simulate login, so just post the code for that part of the login.


class XXX:
 def login(self):

  r = self.s.get('https://nosec.org/users/sign_in')
  html = r.text
  p1 = re.compile(r'city_token" value="(.*?)"')
  res = re.search(p1,html)
  authenticity_token = str(res.group(1))
  print 'authenticity_token:',authenticity_token
  # print 'cookies',self.s.cookies
  # print s.cookies
  data = {
   'authenticity_token':authenticity_token,
   'user[login]':'xxxxx',
   'user[password]':'xxxxx'
  }
  r = self.s.post('https://nosec.org/users/sign_in',data=data)
  # print r.headers
  # print r.request.headers
  # print self.s.cookies
  print '[*] OK!'
  return True

Call the login method and use it next time self.s.get() The request page will bring cookie with it.

I was once cheated by the train of thought and once by a slip of the pen (https was written as http), which made me crazy for a long time before I found this "BUG" = =, so I have to thank the code to improve the efficiency of Bug 2333!

conclusion


Related articles: