-1

我有一个来自 Pastebin 链接的 python 脚本,例如https://pastebin.com/raw/hz8p3B5Y

import requests
requests.get('https://api.telegram.org/******/sendMessage?chat_id=******&text=*****  # Send notification to my Telegram

我想运行一个可以加载原始 Pastebin 并执行它的本地 python 脚本。

4

2 回答 2

1

使用 bash 怎么样?您可以 curl 然后使用 Python 执行脚本

curl your_url | sudo python -
  • curl将 URL 的内容打印到标准输出

  • python -将表明源来自标准输入

curl相关并运行python脚本

于 2018-10-01T09:37:02.970 回答
1

与需要 Bash的其他答案相比,这是一个纯 Python 解决方案。

requests首先,您可以使用模块获取 Pastebin 链接的原始内容requests.content

import requests

pastebin_raw_link = 'https://pastebin.com/raw/xxxxxxxx'
response = requests.get(pastebin_raw_link)
source_code = response.content

print(source_code.decode('utf-8'))

那应该打印出与 Pastebin 的“原始”选项卡相同的内容
糊状原料

接下来,您可以source_code通过以下方式运行:

  • 选项1:调用exec

    exec(source_code)
    

    这通常是如何在 Python 中执行包含 Python 代码的字符串的公认答案?它通常也被认为是不安全的,如为什么应该避免 exec() 和 eval() 等帖子中所讨论的那样?确保您真的真正信任该 Pastebin 链接。

  • 选项 2:将其写入tempfile.NamedTemporaryFile()然后使用importlib直接从源文件导入 Python 模块

    import importlib.util
    import sys
    import tempfile
    
    with tempfile.NamedTemporaryFile(suffix='.py') as source_code_file:
        # Should print out something like '/var/folders/zb/x14l5gln1b762gjz1bn63b1sxgm4kc/T/tmp3jjzzpwf.py' depending on the OS
        print(source_code_file.name)
    
        source_code_file.write(source_code)
        source_code_file.flush()
    
        # From Python docs recipe on "Importing a source file directly"
        module_name = 'can_be_any_valid_python_module_name'
        spec = importlib.util.spec_from_file_location(module_name, source_code_file.name)
        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)
    

    这类似于手动复制 Pastebin 链接的内容,将其粘贴到同一目录中的某个文件(例如 'test.py'),然后将其导入为import test,执行文件的内容。

    也可以不使用tempfile.NamedTemporaryFile,但是您必须手动删除您创建的文件。该tempfile模块已经为您做到了:“文件一关闭就被删除”。

    此外,将其作为模块导入的好处在于它的行为与任何其他 Python 模块一样。意思是,例如,您的 Pastebin 链接声明了一些变量或方法,那么您可以执行以下操作:

    module.some_variable
    module.call_some_method()
    
于 2021-06-28T10:49:06.720 回答