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

如何将Bash主脚本变量传递给其启动的expect子进程使用

问题原因分析

你遇到的运行失败问题是三个错误共同导致的:

  • export语法错误:export $usr这种带$的写法是把变量的值当成要导出的变量名,完全没有导出usr这个变量本身,正确写法是直接传变量名export usr。
  • 单引号阻断变量解析:shell环境中单引号包裹的内容不会解析任何$开头的变量,你传给expect的代码里的$usr、$ip等全部被当成了普通字符串,没有被替换成你输入的实际值。
  • 密码发送逻辑缺失回车:你原来的send "$pw"后面没有加回车符\r,就算变量传对了也不会自动提交密码完成登录。
解决方案

推荐使用更稳妥的环境变量读取方案,不需要处理复杂的引号转义,也能兼容包含特殊字符的密码:

修正后的完整代码

#!/bin/bash

red="\x1b[0;31m"
nc="\x1b[0m"


####### commented out till scipt is finished
# if [ $EUID -ne 0 ]; then
# echo -e "${red}[!]${nc} | script must be run as root"
# exit
# fi

read -p '[?] | ip address of device: ' ip
read -p '[?] | nickname to set for this config: ' name
read -p '[?] | username to generate keys for: ' usr
read -p '[?] | password for that user: ' pw


# 修正export写法,导出变量名而非变量值
export usr pw ip name

# 用expect内置的$env()语法读取shell导出的环境变量
/usr/bin/expect -c 'spawn ssh $env(usr)@$env(ip); expect "(yes/no)? "; send "yes\r"; expect "Password:"; send "$env(pw)\r"; interact'

可选的简单替换方案

如果你的输入内容(尤其是密码)不包含双引号、空格等特殊字符,也可以直接把expect代码包裹在双引号中让shell提前替换变量:

/usr/bin/expect -c "spawn ssh $usr@$ip; expect \"(yes/no)? \"; send \"yes\r\"; expect \"Password:\"; send \"$pw\r\"; interact"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:48:03