简体   繁体   中英

Executing code through python eval

My class assignment is to read a file called key.txt on a server which is in the same directory of a python script it is running on port 2323. The code running in the script is as follows:

while 1: print  eval(raw_input("Enter   Math:"))

I'm connecting with PuTTY and every time I run any code, the connection instantly drops if the code I pass is invalid. It gives no explanation, but I assume the eval function couldnt parse my code.

Here are some of the things I've tried and their outputs:

  • Entering open('key.txt', 'r').read() (or any explicit code) killed the connection
  • Using chr(#) to pass in commands, ex. hello = chr(104)+chr(101)+chr(108)+chr(108)+chr(111) . The server just spits back whatever I type
  • Using compile by entering compile('print "Hello!"', 'buttfile', 'exec') , with the output <code object <module> at 0x7f6270ac0db0, file "buttfile", line 1>

Those are the only two ways I can think of that allows me to pass in code. I wrote a small cpp program to convert whatever I type into the char combinations, as well as including newlines so I can enter multiline code with the chr() method.

So my question is how would I execute code to read a file through python's eval function?

If you are connecting to a linux system you can do it in two commands:

__import__("os").system("locate key.txt")

This assumes that the locate db is up to date.

Then when you know the location just use:

__import__("os").system("cat /location/of/file/key.txt")

Which will output the key to the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM