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

Shell脚本用变量传用户名密码时sshpass失效,报错-p: command not found

Shell脚本错误排查与修复

错误原因

你在给output变量赋值时,没有使用命令替换语法捕获sshpass命令的输出。直接写output=sshpass -p ${rmtpasswrd} ssh ${Rem_user}@${server} -T 'df -h;'会被Shell解析为:

  • 将output变量赋值为字符串sshpass
  • 随后尝试执行独立命令-p ${rmtpasswrd} ssh ...,这就触发了-p: command not found的错误

要捕获命令输出并赋值给变量,必须用$()或反引号`包裹整个命令。

修复后的脚本

echo "Enter the server name (输入无回显)"
read -s server
echo -e "\nEnter the Remote Username (输入无回显)"
read -s Rem_user
echo -e "\nEnter the Remote Password (输入无回显)"
read -s rmtpasswrd

# 使用$()捕获命令输出
output=$(sshpass -p "${rmtpasswrd}" ssh "${Rem_user}@${server}" -T 'df -h')
echo "$output"

额外优化点

  • 给read -s补充提示说明,避免用户因输入无回显产生困惑
  • 给变量添加双引号"${rmtpasswrd}",防止密码包含特殊字符时出现解析错误
  • 移除df -h末尾的多余分号
  • 用$()替代反引号,可读性更强且支持嵌套语法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:05:18