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

Expect脚本执行keytool命令时无法自动响应二次确认问题

解决keytool证书导入时Expect脚本无法自动确认的问题

问题场景

手动执行keytool证书导入命令时,会触发密码输入和二次确认提示:

[user1@scds2000025np certificate_renew]$  keytool -import -alias rootca06062024 -file 25npBaseDomainRootCA06062024.cer -keystore OBG-ST-APIIdentity.jks -trustcacerts
Enter keystore password:
Certificate already exists in keystore under alias <rootca05062024>
Do you still want to add it? [no]:

编写的Expect脚本如下,但执行时卡在二次确认提示处,无法自动发送"yes":

#!/bin/bash

# Move to the specified directory
cd /data/user1/certificate_renew/
# Define variables
KEYTOOL_COMMAND="keytool -import -alias rootca06062024 -file 25npBaseDomainRootCA06062024.cer -keystore OBG-ST-APIIdentity.jks -trustcacerts"
KEYSTORE_PASSWORD="password"

# Create the expect script
expect <<EOF
  # Set timeout (in seconds)
  set timeout -1

  # Spawn the keytool command
  spawn $KEYTOOL_COMMAND

  # Expect the keystore password prompt
  expect "Enter keystore password:"
  send "$KEYSTORE_PASSWORD\r"

  # Handle subsequent prompts
  expect {
    # Match any string for the alias part
    -re {Certificate already exists in keystore under alias <.*>\r\nDo you still want to add it? \[no\]:} {
        send "yes\r"
      exp_continue
    }
    eof
  }
  # Interact with the spawned process
  interact
EOF

执行脚本后的输出,卡在确认提示:

spawn keytool -import -alias rootca06062024 -file 25npBaseDomainRootCA06062024.cer -keystore OBG-ST-APIIdentity.jks -trustcacerts
Enter keystore password:  password

Certificate already exists in keystore under alias <rootca05062024>
Do you still want to add it? [no]: 

问题原因

  1. 原正则尝试匹配连续两行带换行符的内容,但Expect处理输出时通常逐行解析,导致整行正则无法匹配实际输出。
  2. interact命令会将进程控制权交回用户,导致脚本无法自动处理后续确认提示。

修复方案

修改脚本,拆分匹配逻辑,去掉不必要的interact命令,直接匹配确认提示本身:

#!/bin/bash

cd /data/user1/certificate_renew/
KEYTOOL_COMMAND="keytool -import -alias rootca06062024 -file 25npBaseDomainRootCA06062024.cer -keystore OBG-ST-APIIdentity.jks -trustcacerts"
KEYSTORE_PASSWORD="password"

expect <<EOF
  set timeout -1
  spawn $KEYTOOL_COMMAND

  # 处理密码输入
  expect "Enter keystore password:"
  send "$KEYSTORE_PASSWORD\r"

  # 匹配证书已存在的提示(可选,仅用于确认流程节点)
  expect -re {Certificate already exists in keystore under alias <.*>}

  # 匹配二次确认提示并发送yes
  expect "Do you still want to add it? \[no\]:"
  send "yes\r"

  # 等待进程正常结束
  expect eof
EOF

修改说明

  • 移除interact:无需将控制权交回用户,让Expect自动处理到进程结束。
  • 拆分匹配逻辑:单独匹配确认提示符,避免多行正则匹配失败的问题;证书已存在的提示匹配为可选步骤,可根据需求省略。
  • 简化匹配规则:确认提示格式固定,直接匹配字符串比复杂正则更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:35:11