You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ps命令中隐藏bash脚本内的命令执行痕迹?

隐藏脚本中命令执行痕迹的可行方案

我来给你几个实用的办法,解决ps命令能看到脚本里netstat、grep等子进程的问题:

方法1:用纯Bash内置逻辑替代外部工具(最彻底)

你的脚本里的管道命令(netstat/grep/tr/cut)都会生成独立子进程,所以ps能抓得到。如果用Bash内置的字符串处理和系统文件读取来实现相同功能,就能完全避免产生这些子进程,ps只会显示你的主脚本进程。

比如直接读取/proc/net/tcp和/proc/net/tcp6(系统内核提供的网络状态文件),提取监听端口:

#!/bin/bash
while true; do
  # 将结果统一写入/tmp/log
  {
    # 处理IPv4监听端口
    while read -r _ local_addr _ state _; do
      # 状态字段为0A表示LISTEN(十六进制)
      if [[ "$state" == "0A" ]]; then
        # 提取端口(十六进制转十进制)
        port_hex=${local_addr#*:}
        port_dec=$((16#$port_hex))
        # 输出格式与原脚本一致:ip:port
        echo "${local_addr%:*}:$port_dec"
      fi
    done < /proc/net/tcp

    # 处理IPv6监听端口
    while read -r _ local_addr _ state _; do
      if [[ "$state" == "0A" ]]; then
        port_hex=${local_addr##*:}
        port_dec=$((16#$port_hex))
        echo "[${local_addr%:*}]:$port_dec"
      fi
    done < /proc/net/tcp6
  } > /tmp/log

  sleep 100
done

这个版本完全没有调用任何外部命令,ps只能看到你的主Bash进程,彻底隐藏了执行痕迹。

方法2:隐藏子进程的命令行参数

如果不想修改核心逻辑,也可以让子进程的命令行不被ps捕获。比如用bash -s从here-doc读取命令,这样ps看到的子进程只是bash -s,不会显示具体的netstat等命令:

#!/bin/bash
while true; do
  # 用here-doc传递命令,子进程命令行仅显示bash -s
  bash -s > /tmp/log << 'EOF'
netstat -antp | grep LISTEN | tr -s ' ' | cut -d ' ' -f 4
EOF
  sleep 100
done

这里的'EOF'加单引号是为了避免主shell解析here-doc里的变量,保证命令原封不动传给子shell。

额外建议

  • 推荐用ss命令替代netstat,ss是netstat的现代替代工具,效率更高,且默认输出格式更易处理(比如可以用ss -tuln直接显示监听端口,不需要grep)。
  • 作为开机服务,建议用systemd管理,在服务文件里设置PrivateTmp=true,避免日志文件被其他进程篡改,同时提升安全性。
  • 如果你的脚本不需要交互式输入,可以在shebang行加上-f参数(#!/bin/bash -f),关闭文件名扩展,减少潜在风险。

内容的提问来源于stack exchange,提问作者user8819420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:49:11