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 来实现这一点。

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

相关推荐
上进小菜猪29 分钟前
从人工目检到 AI 质检-YOLOv8 驱动的 PCB 缺陷检测系统【完整源码】
后端
知远同学1 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
小徐Chao努力1 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
CoderCodingNo1 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
kylezhao20192 小时前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#
啃火龙果的兔子2 小时前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript
热爱专研AI的学妹2 小时前
数眼搜索API与博查技术特性深度对比:实时性与数据完整性的核心差异
大数据·开发语言·数据库·人工智能·python
Mr_Chenph2 小时前
Miniconda3在Windows11上和本地Python共生
开发语言·python·miniconda3
阿狸远翔2 小时前
Protobuf 和 protoc-gen-go 详解
开发语言·后端·golang
永远前进不waiting2 小时前
C复习——1
c语言·开发语言