我可以通过eventlet.backdoor在Python中调用函数或更改变量吗?

0 投票
3 回答
805 浏览
提问于 2025-04-17 11:12

我写了这段简单的代码来说明我的情况:

import threading
import time
import eventlet
from eventlet import backdoor

eventlet.monkey_patch()

global should_printing
should_printing = True

def turn_off_printing():
    global should_printing
    should_printing = not should_printing

def printing_function():
    global should_printing
    while should_printing == True:
        print "printing"
        time.sleep(1)

def console():
    while True:
        print "inside console"
        time.sleep(1)

if __name__ == '__main__':
    eventlet.spawn(backdoor.backdoor_server, eventlet.listen(('localhost', 3000)))

    thread = threading.Thread(target=printing_function)
    thread.start()

    thread = threading.Thread(target=console)
    thread.start()

执行完这段代码后,我通过telnet连接,导入我的模块,然后调用turn_off_printing()。但是它没有起作用。我是犯了什么错误,还是说这根本不可能?

3 个回答

0

你无法访问 should_printing,因为 __main__ 模块和你导入的模块是不同的,尽管它们看起来是同一个模块。想了解更多细节,可以查看 这里

the executing script runs in a module named __main__, importing the
script under its own name will create a new module unrelated to
__main__.
1

确保在调用后门时,传递你想要访问的所有变量和函数。

if __name__ == '__main__':
    s=eventlet.spawn(backdoor.backdoor_server, eventlet.listen(('localhost', 3000)), globals())

    thread1 = threading.Thread(target=printing_function)
    thread1.start()

    s.wait()

现在,should_printing 这个变量应该可以在运行在3000端口的 Python 解释器中看到,如果把它设置为 false,就会停止打印信息。

-1

正如fthinker在上面的评论中提到的:

看起来这个后门服务器并没有使用相同的命名空间。输入函数名时,它们显示未定义,而你的变量 'should_printing' 也未定义。我在通过telnet连接到后门服务器设置的解释器时进行了测试。

(如果fthinker把这个作为回答发出来,我会删除这个帖子)

撰写回答