简体   繁体   English

通过python eval执行代码

[英]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: 我的课程分配是在服务器上读取一个名为key.txt的文件,该文件与端口2323上运行的python脚本位于同一目录中。脚本中运行的代码如下:

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. 我正在连接PuTTY,每次我运行任何代码时,如果传递的代码无效,连接都会立即断开。 It gives no explanation, but I assume the eval function couldnt parse my code. 它没有给出任何解释,但我假设eval函数无法解析我的代码。

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 输入open('key.txt', 'r').read() (或任何明确的代码)会终止连接
  • Using chr(#) to pass in commands, ex. 使用chr(#)传递命令,例如。 hello = chr(104)+chr(101)+chr(108)+chr(108)+chr(111) . 你好= 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> 通过输入compile('print "Hello!"', 'buttfile', 'exec')使用compile ,输出<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. 我编写了一个小型cpp程序,将我键入的任何内容转换为char组合,包括换行符,以便可以使用chr()方法输入多行代码。

So my question is how would I execute code to read a file through python's eval function? 所以我的问题是我将如何执行代码以通过python的eval函数读取文件?

If you are connecting to a linux system you can do it in two commands: 如果要连接到linux系统,则可以使用两个命令来完成:

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

This assumes that the locate db is up to date. 这假定locate数据库是最新的。

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. 这会将键输出到屏幕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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