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

Expect脚本遇--MORE--卡住失效,终端/Cron执行异常求助

解决Expect脚本在Cron/小终端下因--MORE--卡住的问题

问题原因

远程网络硬件会根据终端窗口尺寸决定是否将长输出分页显示(即出现--MORE--)。通过Cron执行时,脚本运行在非交互式无终端环境;或终端窗口尺寸较小时,远程设备会触发分页,而你的原脚本仅等待提示符OLT01>,未处理--MORE--的交互请求,导致脚本卡住。

解决方案

方案1:禁用远程设备的分页功能(推荐)

绝大多数网络设备支持通过命令关闭输出分页,无论终端尺寸如何,都会一次性输出全部内容。在登录后先执行对应命令即可:

修改后的Expect脚本:

#!/usr/bin/expect

set timeout 60

spawn ssh user@<remote IP>

expect "yes/no" { 
    send "yes\r"
    expect "*?assword" { send "password\r" }
    } "*?assword" { send "password\r" }

# 执行关闭分页的命令(根据设备型号调整)
# 常见命令示例:terminal length 0 / screen-length 0 temporary / no pagination
expect "OLT01>" { send "terminal length 0\r" }

# 后续正常执行命令
expect "OLT01>" { send "command 1\r" }
expect "OLT01>" { send "command 2\r" }
expect "OLT01>" { send "command 3\r" }

expect "OLT01>" { send "exit\r" }

注意:不同厂商的设备关闭分页的命令不同,比如中兴OLT可能用screen-length 0 temporary,华为设备常用terminal length 0,请根据你的设备型号调整。

方案2:让Expect脚本自动处理--MORE--

如果设备不支持关闭分页,可修改脚本,让它在等待提示符的同时匹配--MORE--,自动发送翻页按键(通常是空格或回车):

修改后的命令等待逻辑示例:

# 处理command 1的输出分页
expect {
    "--MORE--" {
        send " \r"  # 发送空格翻页,部分设备需用"\r"(回车)
        exp_continue  # 继续等待,直到出现提示符
    }
    "OLT01>" {
        send "command 1\r"
    }
}

# 同理处理其他命令
expect {
    "--MORE--" {
        send " \r"
        exp_continue
    }
    "OLT01>" {
        send "command 2\r"
    }
}

exp_continue会让当前的expect语句循环执行,直到匹配到目标提示符。

方案3:强制设置终端尺寸(适配Cron环境)

Cron运行时默认没有终端尺寸,可通过设置环境变量或强制分配伪终端,让远程设备认为终端足够大:

#!/usr/bin/expect

set timeout 60

# 设置终端的列数和行数,避免远程设备触发分页
set env(COLUMNS) 200
set env(LINES) 50

# 用-t -t强制分配伪终端(解决Cron无终端问题)
spawn ssh -t -t user@<remote IP>

# 后续登录和命令逻辑和原脚本一致
expect "yes/no" { 
    send "yes\r"
    expect "*?assword" { send "password\r" }
    } "*?assword" { send "password\r" }

expect "OLT01>" { send "command 1\r" }
expect "OLT01>" { send "command 2\r" }
expect "OLT01>" { send "command 3\r" }

expect "OLT01>" { send "exit\r" }

测试建议

  1. 先在小窗口终端手动运行修改后的脚本,验证是否不再卡住;
  2. 配置Cron任务测试,例如:
    * * * * * /path/to/your/expect_script >> /tmp/script_output.log 2>&1
    
    等待一分钟后查看/tmp/script_output.log,确认脚本执行正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 03:13:12