Guest User

Untitled

a guest
Nov 21st, 2017
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.70 KB | None | 0 0
  1. >>> import requests
  2. >>> login_data = {'formPosted':'1', 'login_email':'me@example.com', 'password':'pw'}
  3. >>> r = requests.post('https://localhost/login.py', login_data)
  4. >>>
  5. >>> r.text
  6. u'You are being redirected <a href="profilePage?_ck=1349394964">here</a>'
  7. >>> r.cookies
  8. {'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
  9. >>>
  10. >>> r2 = requests.get('https://localhost/profile_data.json', ...)
  11.  
  12. s = requests.session()
  13.  
  14. s.post('https://localhost/login.py', login_data)
  15. #logged in! cookies saved for future requests.
  16. r2 = s.get('https://localhost/profile_data.json', ...)
  17. #cookies sent automatically!
  18. #do whatever, s will keep your cookies intact :)
  19.  
  20. import urllib2
  21. import urllib
  22. from cookielib import CookieJar
  23.  
  24. cj = CookieJar()
  25. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  26. # input-type values from the html form
  27. formdata = { "username" : username, "password": password, "form-id" : "1234" }
  28. data_encoded = urllib.urlencode(formdata)
  29. response = opener.open("https://page.com/login.php", data_encoded)
  30. content = response.read()
  31.  
  32. >>> url = 'http://httpbin.org/cookies'
  33. >>> cookies = dict(cookies_are='working')
  34.  
  35. >>> r = requests.get(url, cookies=cookies)
  36. >>> r.text
  37. '{"cookies": {"cookies_are": "working"}}'
  38.  
  39. import pickle
  40. import datetime
  41. import os
  42. from urllib.parse import urlparse
  43. import requests
  44.  
  45. class MyLoginSession:
  46. """
  47. a class which handles and saves login sessions. It also keeps track of proxy settings.
  48. It does also maintine a cache-file for restoring session data from earlier
  49. script executions.
  50. """
  51. def __init__(self,
  52. loginUrl,
  53. loginData,
  54. loginTestUrl,
  55. loginTestString,
  56. sessionFileAppendix = '_session.dat',
  57. maxSessionTimeSeconds = 30 * 60,
  58. proxies = None,
  59. userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
  60. debug = True):
  61. """
  62. save some information needed to login the session
  63.  
  64. you'll have to provide 'loginTestString' which will be looked for in the
  65. responses html to make sure, you've properly been logged in
  66.  
  67. 'proxies' is of format { 'https' : 'https://user:pass@server:port', 'http' : ...
  68. 'loginData' will be sent as post data (dictionary of id : value).
  69. 'maxSessionTimeSeconds' will be used to determine when to re-login.
  70. """
  71. urlData = urlparse(loginUrl)
  72.  
  73. self.proxies = proxies
  74. self.loginData = loginData
  75. self.loginUrl = loginUrl
  76. self.loginTestUrl = loginTestUrl
  77. self.maxSessionTime = maxSessionTimeSeconds
  78. self.sessionFile = urlData.netloc + sessionFileAppendix
  79. self.userAgent = userAgent
  80. self.loginTestString = loginTestString
  81. self.debug = debug
  82.  
  83. self.login()
  84.  
  85. def modification_date(self, filename):
  86. """
  87. return last file modification date as datetime object
  88. """
  89. t = os.path.getmtime(filename)
  90. return datetime.datetime.fromtimestamp(t)
  91.  
  92. def login(self, forceLogin = False):
  93. """
  94. login to a session. Try to read last saved session from cache file. If this fails
  95. do proper login. If the last cache access was too old, also perform a proper login.
  96. Always updates session cache file.
  97. """
  98. wasReadFromCache = False
  99. if self.debug:
  100. print('loading or generating session...')
  101. if os.path.exists(self.sessionFile) and not forceLogin:
  102. time = self.modification_date(self.sessionFile)
  103.  
  104. # only load if file less than 30 minutes old
  105. lastModification = (datetime.datetime.now() - time).seconds
  106. if lastModification < self.maxSessionTime:
  107. with open(self.sessionFile, "rb") as f:
  108. self.session = pickle.load(f)
  109. wasReadFromCache = True
  110. if self.debug:
  111. print("loaded session from cache (last access %ds ago) "
  112. % lastModification)
  113. if not wasReadFromCache:
  114. self.session = requests.Session()
  115. self.session.headers.update({'user-agent' : self.userAgent})
  116. res = self.session.post(self.loginUrl, data = self.loginData, proxies = self.proxies)
  117.  
  118. if self.debug:
  119. print('created new session with login' )
  120. self.saveSessionToCache()
  121.  
  122. # test login
  123. res = self.session.get(self.loginTestUrl)
  124. if res.text.lower().find(self.loginTestString.lower()) < 0:
  125. raise Exception("could not log into provided site '%s'"
  126. " (did not find successful login string)"
  127. % self.loginUrl)
  128.  
  129. def saveSessionToCache(self):
  130. """
  131. save session to a cache file
  132. """
  133. # always save (to update timeout)
  134. with open(self.sessionFile, "wb") as f:
  135. pickle.dump(self.session, f)
  136. if self.debug:
  137. print('updated session cache-file %s' % self.sessionFile)
  138.  
  139. def retrieveContent(self, url, method = "get", postData = None):
  140. """
  141. return the content of the url with respect to the session.
  142.  
  143. If 'method' is not 'get', the url will be called with 'postData'
  144. as a post request.
  145. """
  146. if method == 'get':
  147. res = self.session.get(url , proxies = self.proxies)
  148. else:
  149. res = self.session.post(url , data = postData, proxies = self.proxies)
  150.  
  151. # the session has been updated on the server, so also update in cache
  152. self.saveSessionToCache()
  153.  
  154. return res
  155.  
  156. if __name__ == "__main__":
  157. # proxies = {'https' : 'https://user:pass@server:port',
  158. # 'http' : 'http://user:pass@server:port'}
  159.  
  160. loginData = {'user' : 'usr',
  161. 'password' : 'pwd'}
  162.  
  163. loginUrl = 'https://...'
  164. loginTestUrl = 'https://...'
  165. successStr = 'Hello Tom'
  166. s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr,
  167. #proxies = proxies
  168. )
  169.  
  170. res = s.retrieveContent('https://....')
  171. print(res.text)
  172.  
  173. import requests
  174. import json
  175.  
  176. authUrl = 'https://whatever.com/login'
  177.  
  178. #The subsequent url
  179. testUrl = 'https://whatever.com/someEndpoint'
  180.  
  181. #Whatever you are posting
  182. login_data = {'formPosted':'1', 'login_email':'me@example.com', 'password':'pw'}
  183.  
  184. #The auth token or any other data that we will recieve from the authRequest.
  185. token = ''
  186.  
  187. # Post the loginRequest
  188. loginRequest = requests.post(authUrl,login_data)
  189. print loginRequest.text
  190.  
  191. # Save the request content to your variable. In this case I needed a field called token.
  192. token = str(json.loads(loginRequest.content)['token'])
  193. print token
  194.  
  195. # Verify successfull login
  196. print loginRequest.status_code
  197.  
  198. #Create your RequestsCookieJar for your subsequent requests and add the cookie
  199. jar = requests.cookies.RequestsCookieJar()
  200. jar.set('LWSSO_COOKIE_KEY', token)
  201.  
  202. #Execute your next request(s) with the RequestCookieJar set
  203. r = requests.get(testUrl, cookies=jar)
  204. print(r.text)
  205. print(r.status_code)
  206.  
  207. import requests
  208.  
  209. username = "my_user_name"
  210. password = "my_super_secret"
  211. url = "https://www.my_base_url.com"
  212. the_page_i_want = "/my_json_data_page"
  213.  
  214. session = requests.Session()
  215. # retrieve cookie value
  216. resp = session.get(url+'/login')
  217. csrf_token = resp.cookies['csrftoken']
  218. # login, add referer
  219. resp = session.post(url+"/login",
  220. data={
  221. 'username': username,
  222. 'password': password,
  223. 'csrfmiddlewaretoken': csrf_token,
  224. 'next': the_page_i_want,
  225. },
  226. headers=dict(Referer=url+"/login"))
  227. print(resp.json())
Add Comment
Please, Sign In to add comment