Skip to main content

Sending request using request library

Using request library for Pirates

 Few years ago using urllib2 was a simplest way for sending and receiving  HTTP Request. But now I'm using  Request library . This  is more simple and powerful. Unfortunately Request is not include in default install and Pip  should be used . 

Installation

 Procedure is really simple  and near to standard :

MacBook-Pro-Hohlov:pirates skhohlov$ virtualenv ./env
New python executable in ./env/bin/python2.7
Also creating executable in ./env/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-Hohlov:pirates skhohlov$ source ./env/bin/activate
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ 
(env)MacBook-Pro-Hohlov:pirates skhohlov$ pip install requests
Collecting requests
  Using cached requests-2.13.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.13.0
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.


Few lines of code. 

 Request has a good documentation at : http://docs.python-requests.org/en/master/   It will be nice to check it if you have any misunderstanding.   Lets back to pirates game.  One of the first request is three  requests for selecting  correct segment for playing. List   is a powerful and very important  feature of the python  language.  If you  have worked  with C or C++  you should  know  how  much time requires understanding of pointers and correct using. Python  is doing this in  light and easy to understand way. Good tutorial  is here : https://www.tutorialspoint.com/python/python_lists.htm    
I've created a function  hot to send requests and select proper segment for  future requests: 



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def detectdefaultsegment(gamesession, config):
    """ function for detecting default user segment"""
    BaseSegmentURLList = [
    'https://kpppen3s00.plrm.zone/PiratesPpEng3/Segment00/segment.ashx',
    'https://kpppen2s00.plrm.zone/PiratesPpEng2/Segment00/segment.ashx',
    'https://kpppen1s01.plrm.zone/PiratesPPeng/Segment00/segment.ashx']
        
    gamesession.headers.update({'sign-code':config['sign-code'], 'server-method':'GetTouch','client-ver':config['client-ver']})
    for  BUrl in BaseSegmentURLList:        
        answer=gamesession.post(BUrl,data="[\""+config['userid']+"\"]")
        if answer.text[0] is not '!':
            segmenturl = BUrl
    return segmenturl

How its works ?
 Lines  3-6 are  our python list  of the  url.
 Line 8 is adding some header to the request  such as client version , sever method etc.
 Lines 9-12 are python loop:  request is send to each url .  Correct answer is started from  digits (timestamp),  incorrect is started from symbol "!".  Correct URL is returned.
All script code are placed at : https://pastebin.com/ZB4LiXuw 

Looks like I will write only SignIn function. Other part is not interested for me.

Generating Signature and Sign in function. 

Article about  swf working with swf shows how to application "crypting" request  again bad guys. 


def generateSignature(jsonstring, servercommand,config ):
    """Generate checksum for sign-code header.
    Each POST request has this one."""
    matrix_string = "The Matrix has you..."    
    return hashlib.md5((matrix_string+jsonstring+servercommand+config['userid']+config['authkey']).encode('ascii')).hexdigest()

and our first  Sign in function  is look like :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def SignIn(gamesession, config, mainurl):
   """ function for SignIn. This not auth function,
   this function is used for marking for setting up flag
   for first signing in per day. """        
   JSON_STRING = """{"s":{"x":null,"gr":null,"l":"en-US","I'm":false,"s":null,"tg":0,"m":"myemail","ar":null,"de":null,"t":0,"a":false,"n":"nickname","vk":{"b":false},"u":"//cdn01.x-plarium.com/browser/content/portal/common/avatars/default_avatar.jpg","i":"pp24685509","fl":false,"np":false,"p":null,"d":"nickname;null;null;en_US;0;;","tip":null},"mr":"","l":"","i":"0","f":[""],"c":{"ht":"Portal","put":null,"i":1,"v":"1.0"},"t":-180,"rr":"https://plarium.com/en/strategy-games/pirates-tides-of-fortune/"}"""
   parsed_string = json.loads(JSON_STRING)
   print("email:{c[m]}, username:{c[n]}, userid:{c[i]}".format(c=parsed_string["s"]))
   print json.dumps(parsed_string)
   sign =  generateSignature(JSON_STRING, 'SignIn', config)
   gamesession.headers.update({'sign-code':sign, 'server-method':'SignIn','client-ver':config['client-ver'], 'signin-authSeed':config['authSeed'], 'signin-authKey':config['authkey'], 'signin-userId':config['userid']})
   answer = gamesession.post(mainurl,data=JSON_STRING)
   return answer


Main problem is understanding a string "JSON_STRING".  I've sorted out that this string contains nickname , email, link to photo etc.   Everyone  can get this string from  checking headers procedure, I've informed about this one or two weeks ago. Strings #6-8 print  this information.  Those string have debuging purpose only.  Strings #10-12 are preparing request  and sending it to server.
Other server command requires a similar job to our SignIn  function.
I have no interest for this and  I would like to do something  funny and smart  (Ex: Arduino or AI )

Comments

Post a Comment

Popular posts from this blog

Update grub using dracut

Fixing grub using dracut Last kernel update was not successful to me. Centos can not boot with next messages:  [ 180.098802] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 180.610167] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 181.121619] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 181.633093] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 182.144831] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 182.656146] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 183.167306] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts [ 183.678755] dracut-initqueue[376]: Warning: dracut-initqueue timeout - starting timeout scripts  Of course simples way  is creating  linux  usb stick  and fix it. But dracut
  debian,  amavis,  virus inside archive   One my client asked informed me, that amavis skips some files types. mail server configuration is really simple: Postfix as SMTP server and  amavis working as context filter. Also amavis runs spamassasin and clamd antivirus. Amavis gets files from attachment and unpack it. lha file is not detected. short investigation First I deceided to run amavis  in debug mode and verify how virus passed postix+amavis.  root@newserver:/var/lib/amavis# /etc/init.d/amavis stop [ ok ] Stopping amavis (via systemctl): amavis.service. root@newserver:/var/lib/amavis# /etc/init.d/amavis debug Trying to run amavisd-new in debug mode. Debug mode inform about loaded plugins: ' Nov 13 22:07:23.335 newserver. /usr/sbin/amavisd-new[40334]: Found decoder for .cpio at /bin/pax Nov 13 22:07:23.336 newserver. /usr/sbin/amavisd-new[40334]: Found decoder for .tar at /bin/pax Nov 13 22:07:23.336 newserver. /usr/sbin/amavisd-new[40334]

Postfix can not start via systemd (simple fix)

Solving problem related to systemd process I like postfix.   This is really smart and secure mail server. I'm helping above  dozen clients around the world and  tunning  postfix is really fun task. This morning I was downgrading postfix  to the stable version for one of the my friends and come across interesting issue.  root@newserver:/etc/init.d# systemctl status postfix ● postfix.service Loaded: masked (/dev/null; bad) Active: inactive (dead) since вт 2017-06-13 14:35:41 EEST; 1h 48min ago Main PID: 25145 (code=exited, status=0/SUCCESS) чер 13 14:47:09 newserver systemd[1]: Stopped postfix.service. чер 13 14:47:29 newserver systemd[1]: Stopped postfix.service. чер 13 14:58:22 newserver systemd[1]: Stopped postfix.service. чер 13 14:58:23 newserver systemd[1]: Stopped postfix.service. чер 13 15:05:20 newserver systemd[1]: Stopped postfix.service. чер 13 15:29:06 newserver systemd[1]: Stopped postfix.service. чер 13 15:29:06 newserver systemd[1]: Stopp