首页 > 解决方案 > 使用 pyinstaller 导入外部 .exe 文件

问题描述

我正在尝试使用 pyinstaller 将我的 Python 代码库捆绑到一个 .exe 文件中。

我的代码使用 nmap 执行 shell 命令。这在开发中运行良好,因为我在我的开发环境中单独安装了 nmap。

但是,如果我想在另一台机器上将其作为 exe 运行(无需在该机器上单独安装 nmap),我似乎无法做到这一点。

我查看了 pyinstaller 的 --add-binary 选项,这就是我使用它的方式:

pyinstaller --onefile --add-binary "C:\Program Files (x86)\Nmap\nmap.exe";. --paths=path_to_my_python_file python_file_to_run -n name_of_my_exe_file

生成的 exe 文件能够毫无困难地导入 Python 特定的依赖项并执行所有其他 Python 代码,但它不能运行 nmap shell 命令。

这就是我通过 Python 运行 nmap 的方式(为简洁起见,省略了完整的命令):

subprocess.Popen(["powershell.exe", "nmap" )],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
  1. 甚至可以将 nmap 与我的 exe 文件捆绑在一起吗?
  2. 如果是,我做得对吗?
  3. 如果没有,我有什么选择?(我不能使用任何基于 python 的 nmap 库,如 python-nmap 等)

[更新] 工作解决方案:最终的 pyinstaller 声明:

pyinstaller --paths=path_to_my_python_file --noconfirm python_file_to_run --noconfirm -n name_of_exe_file 

使用 robocopy 复制我需要的所有 nmap 文件:

robocopy  path_to_nmap_source_directory path_to_installation_destination_directory /COPYALL /E /NFL /NDL /NJH /NJS /nc /ns /np

Python代码(Bundling data files with PyInstaller (--onefile))获取nmap的执行路径:

def get_base_path():
    base_path = ""
    if getattr(sys, 'frozen', False):
            base_path = sys._MEIPASS
    return base_path

def get_exe_path(file):
    #file is the name of your exe file e.g nmap.exe
    base_path = get_base_path()
    exe_path = os.path.join(base_path, file)
    return exe_path

标签: pythonwindowsshellpyinstallernmap

解决方案


你最好的选择是使用nmap的python实现,pip上有很多,比如python-nmap,我建议下载一个纯python实现并使用它而不是exe。


推荐阅读