Rust Command无法执行*拓展解决办法

rust 复制代码
async fn run_cmd_async_out<I, S>(cmd: &str, args: I, timeout_s: u64, with_http_proxy: bool) -> Result<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut cmd = tokio::process::Command::new(cmd);
    
    // 让 sh 来运行命令,使得通配符能够被 shell 解析
    let cmd = cmd.arg("-c").arg(cmd).args(args);

    if with_http_proxy {
        // 设置 HTTP 代理
        if let Ok(c) = fs_read_line(CONF_HTTP_PROXY) {
            cmd.env("http_proxy", c);
        }

        if let Ok(c) = fs_read_line(CONF_HTTPS_PROXY) {
            cmd.env("https_proxy", c);
        }
    }
    
    let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().context("wait stdout/stderr failed")?;

    match timeout(Duration::from_secs(timeout_s), child.wait()).await {
        Ok(Ok(_)) => {
            let output = child.wait_with_output().await?;
            if !output.status.success() {
                Err(anyhow!("run cmd failed, {}", String::from_utf8_lossy(output.stderr.as_slice())))
            } else {
                let status = String::from_utf8_lossy(output.stdout.as_slice()).to_string();
                Ok(status)
            }
        }
        Ok(Err(e)) => Err(anyhow!("running cmd error, {e}")),
        Err(e) => {
            let _ = child.start_kill();
            let _ = child.wait().await;
            Err(anyhow!("running cmd timeout, {e}"))
        }
    }
}

调用的示例 。

rust 复制代码
system_async_run("sh", &vec!["-c", "rm -f /var/backups/*.pcap"]).await?;

解释:

在 Linux 中,当你使用命令如 rm -rf /var/volatile/*.pcap 时,* 是由 shell 进行扩展的,它将通配符替换为实际的文件名列表。在使用 tokio::process::Command 时,这种通配符扩展不会自动发生,因为 Command 直接调用的是操作系统的命令,而没有通过 shell 来进行扩展。

要解决这个问题,你可以让 tokio::process::Command 在运行时通过 shell 来执行该命令,从而使得 * 符号能够得到正确的扩展。你可以通过设置 sh 来实现这一点。

注: 妈的。好坑。折腾我半天。以为删除不了文件。

相关推荐
愚农搬码3 小时前
自研表单引擎、开源组件二开和商业产品,企业应该如何选择?
后端
用户298698530143 小时前
Python 自动化处理 Word 页眉页脚的几种典型场景
后端·python·api
小小晓.3 小时前
Qt 对话框、QLineEdit 与布局管理实战详解
开发语言·qt
愚农搬码4 小时前
一款企业级电子表单系统应该具备哪些功能?
后端
炸薯条!4 小时前
博客系统测试报告
开发语言·lua
Evand J4 小时前
【MATLAB例程12】永磁同步电机基于增广无迹卡尔曼滤波的未知负载转矩在线观测
开发语言·matlab
Rain的Java大神之路4 小时前
国家数据集团校招、社招都开了:总部雄安,这些技术岗值得认真看看
java·后端·面试
XW4 小时前
Agent 上下文管理实现详解:从窗口工程到长期记忆
后端
Moment4 小时前
为什么这么多 Agent Harness 都选择 TypeScript
前端·后端·面试
软件技术NINI4 小时前
基于SpringBoot和Vue的项目评审系统
javascript·vue.js·spring boot·后端·spring·毕业设计·毕设