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

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

相关推荐
掘金者阿豪4 分钟前
GitLab 服务器疑似遭入侵:从 502 故障到 Root 权限异常的完整排查复盘
后端
乌暮20 分钟前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
不绝19135 分钟前
Lua基础语法入门:注释、变量类型与字符串操作
开发语言·lua
云起SAAS38 分钟前
手机靓号选号商城H5源码 完整前后台可直接运行
前端·javascript·后端
the局外人1 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
苏三说技术1 小时前
分库分表要被淘汰了?
后端
__underline__1 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
Hhy_11071 小时前
《C++深度解构07》手撕 vector —— 从底层三指针架构到迭代器失效彻底吃透
c语言·开发语言·c++·学习·visual studio
nice_lcj5201 小时前
【从零理解计算机网络 · 05】TCP 四次挥手:为什么挥手要四次、TIME_WAIT 在等什么
后端·tcp/ip·计算机网络·面试·tcp·四次挥手·time_wait
Moment1 小时前
RSI 是怎样让 AI 改进自己的 ❓❓❓
前端·后端·面试