Skip to content
Advertisement

Why do i get a Syntax error using exec()?

This function grabs a python script from a paste on pastebin with the title py_0001, when the execution reaches the try: except: it throws an error SyntaxError: unexpected character after line continuation character

If you copy value of script_ and declare it as a string variable it executes without any errors

The function works fine until it reaches the error handling part

def get_script():
    ''' grabs python script from pastebin '''
    reg_ = r'[a-zA-Z0-9]*">py_0001'
    resp = requests.get(url='https://pastebin.com/u/'+usr_name)
    path = re.findall(reg_ , str(resp.content) , re.MULTILINE)  
    url2 = "https://pastebin.com/raw/"+ str(path[0]).replace('">py_0001' , '')
    resp2 = requests.get(url2)
    script_ = str(resp2.content)[2:-1]
    print (script_)


  
    try:
      exec(script_)
    except:
      print ("3rr0r")

This is the output of the paste on pastebin

import osrnimport time rnimport random rn rndef fun_9991():rn    ## a simple code example to test rn    for i in range (0 , 10 ):rn        print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))rn    print ("loop reached the end")rn    rn rnif __name__ == "__main__":rn    fun_9991()rnrnrn

Advertisement

Answer

Your problem is calling str() on a bytes object. NEVER call str() on a bytes object to convert it to a string, since it behaves like repr(). Simply using [2:-1] will only remove the quotes but not undo escaping other special characters.

You can do this:

script_ = resp2.content.decode('utf-8')

Or this:

script_ = resp2.text

Also, executing random code from the internet is an incredibly bad idea.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement