tauri项目绕开plugin-shell直接调用可执行文件并携带任意参数

110 阅读1分钟

tauri项目的plugin-shell插件的要求太多了,用起来实在是不顺手,要求参数要求位置等,不行不行,客户要求可以在前端输入任意命令行参数并执行,哪怕是rm -rf都要无条件执行,好好好,满足你。

我们直接绕开 plugin-shell 插件,不使用它了,直接使用系统内置的功能,还能减小包体积呢,真是一举两得

use std::process::Command;

然后写一个command提供给前端调用,传入一个字符串参数即可:

#[tauri::command]
pub fn run_command(command: String) -> Result<String, String> {
    let output = if cfg!(target_os = "windows") {
        Command::new("cmd").args(&["/C", &command]).output().unwrap()
    } else {
        Command::new("sh").arg("-c").arg(&command).output().unwrap()
    };

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).to_string())
    }
}

这里唯一要做的就是要在前端找到可执行文件的绝对路径位置,然后把参数拼好,再执行就可以了,这里我先写了一个绝对路径,测试也是没问题的,所以你要先自己通过程序拿到可执行文件的绝对路径,然后就可以了

// run help
const runHelp = async () => {
    const command = await invoke('run_command', {
        command: '/Users/song/Project/my/TauriMan/src-tauri/bin/fnm --version',
    })
    console.log('run_command------', command)
}

执行结果: