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

Curl命令行运行正常但在Expect脚本中失效问题求助

解决Expect脚本中curl输出乱码的问题

我来帮你排查下这个问题哈,你遇到的乱码大概率是Expect与curl的交互逻辑、重定向处理方式不对导致的,下面给你具体的解决思路和修正方案:

1. 先修正错误的重定向方式

你在spawn命令里直接写> $hname是错误的——Expect的spawn不会像shell那样解析重定向符号,这个>会被当成curl的参数传递过去,这直接导致curl输出异常。

正确的做法有两种:

  • 用shell包裹curl命令,让shell处理重定向:
    spawn sh -c "curl -u $myuserid $url > $hname"
    
  • 更推荐用curl自带的--output参数指定输出文件,逻辑更清晰可靠:
    spawn curl -u $myuserid --output $hname $url
    

2. 关闭curl的终端交互模式

Expect默认会模拟一个终端环境,curl在终端下会输出进度条、控制字符等非文本内容,这些内容混入输出就会导致乱码。你可以给curl加上-s(静默模式)参数,关闭进度条和冗余输出:

spawn curl -s -u $myuserid --output $hname $url

3. 修正密码交互的匹配逻辑

你的expect匹配规则太死板了,curl的密码提示可能是Enter host password for user '$myuserid':,也可能简化成Password:,建议用更灵活的匹配方式,避免因为匹配不到导致脚本卡住进而输出异常:

expect {
    "Password:" {send "$mypwd\r"}
    "'$myuserid':" {send "$mypwd\r"}
}

如果想适配更多场景,可以用正则表达式匹配:

expect -re {Password:|'[^\']+':} {
    send "$mypwd\r"
}

4. 确保输出编码一致

如果目标URL返回的内容是特定编码(比如GBK),可以让curl指定输出编码,比如强制转成UTF-8:

spawn curl -s --output-encoding utf-8 -u $myuserid --output $hname $url

完整的修正脚本示例

# 替换成你的实际参数
set myuserid "your_username"
set mypwd "your_password"
set url "https://your-target-url.com"
set hname "output.txt"

# 启动curl,静默模式+指定输出文件
spawn curl -s -u $myuserid --output $hname $url

# 处理密码交互,匹配所有可能的提示并等待命令执行完成
expect {
    -re {Password:|'[^\']+':} {
        send "$mypwd\r"
        exp_continue
    }
    eof
}

按这个脚本调整后,应该就能解决乱码问题了。核心就是让curl在非终端模式下运行,正确处理输出文件,同时灵活匹配密码提示避免脚本异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:42:07