改进 expect 脚本以登录到列入白名单的 postgres 实例

Improving an expect script to log onto whitelisted postgres instance

我正在使用 expect 简化登录脚本到仅列入白名单(因此漏洞较少)postgres 实例。这是编辑后的脚本

#!/usr/bin/expect
set RDSI [lindex $argv 0]
spawn /usr/local/bin/psql -U postgres -h $RDSI -d clips
expect "Password" 
send "myPassword\r" 
interact 
expect eof  # I have tried with and without this line

让我们运行它:

19:00:38/ciderapp $./exp.sh
spawn /usr/local/bin/psql -U postgres -h  -d clips
SET
psql (12.4)
Type "help" for help.

clips=#       # We get into the db v quickly          
              # Delays here for about 20+ seconds
myPassword    # we don't necessarily want this printed!
clips-# 

三个问题:

您看到的是 expect 的预期行为。您等待它收到密码提示或超时(默认 10 秒),然后一旦它做了其中一件事情,您就无条件发送密码。如果您想在提示可能不会出现的情况下使用它,则需要以收到密码提示为条件发送密码。

但无论如何,将 expectpsql 一起使用确实没有意义,因为 PostgreSQL 提供了比这更好的方法来完成任务。

您可以使 expect 命令有条件地执行操作。在这里,您期望密码提示,但它没有出现。

假设交互提示是"clips-#",你可以这样做:

#!/usr/bin/expect
set RDSI [lindex $argv 0]
spawn /usr/local/bin/psql -U postgres -h $RDSI -d clips
set prompt "clips-#"
expect {
    "Password" 
        send "myPassword\r" 
        exp_continue
    }
    $prompt
}
interact 

该 expect 语句中有 2 种模式。如果看到“password”,它将发送密码,然后在相同的 expect 语句中继续。当看到提示时,由于没有任何操作,expect 命令 returns.

对于期望脚本的最后一行,使用

  • interact 如果您作为人类需要与生成的进程进行交互,或者
  • expect eof如果不需要交互,您只需等待流程结束即可。