首页 > 解决方案 > ssh登录后期望脚本不执行

问题描述

我正在尝试编写一个期望脚本来:

  1. 连接到提供用户和密码的远程服务器
  2. 循环读取每一行的本地文件
  3. 在远程服务器上为这些行中的每一行执行特定命令

我可以成功实现第 1 步,并用一个简单的场景测试第 3 步,但还不能让它工作。不幸的是,在脚本的第 8 行,在发送密码后,我只是像手动登录的那样登录到服务器(我可以与控制台交互),其余的没有执行。

我该如何规避这个问题?

这是脚本:

#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t -t "$user\@$ip"
expect "Password:"
send "$password\r";
expect "NYXOOBPN402(config)$"
send "delete decoders:ASX-Trade24-FIX.mdp\r"
expect "Are you sure you want to delete 'decoders:ASX-Trade24-FIX.mdp' (y/n)?"
send "y\r";

这就是我执行它的方式:

./test_expect.sh 172.18.250.20 admin admin

标签: bashunixexpect

解决方案


问题是我的期望在第 17 行是不正确的。我应该只输入“*(config)*”而不是“NYXOOBPN402(config)*”,因为在这部分之前有很多文本不匹配。

这是我遇到同样问题的人的最终脚本:

#!/usr/bin/expect
set timeout 9
# Check if the parameters are correct
if {[llength $argv] == 0} {
      send_user "Usage: ./test_expect.sh ip username password\n"
        exit 1
    }

# Read the file with all the decoders names to be deleted
set f [open "decoders.txt"]
set decoders [split [read $f] "\n"]
close $f

# debug mode - very useful:
#exp_internal 1

# Connect to the server
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh -t "$user\@$ip"
expect "Password: "
send "$password\r";
sleep 3
# send ctrl+c since this terminal shows a lot of decoders
#send \x03

expect {
    default { send_user "\nCould not find the expected value.\n"; exit 1 }
    "*(config)*" {
        # Loop through all the decoders
        foreach decoder $decoders {
            #send_user "Removing $decoder\n"
            send "delete decoders:$decoder\r"
            expect {
                "Are you sure you want to delete*" { send "y\r" }
                "*decoder will still be active*" { send_user "\nRemoved $decoder successfully\n" }
                "*no such file or directory" { send_user "\nDecoder $decoder already deleted.\n" }
                default { send_user "\nNot expected value with $decoder, please debug.\n"; exit 1 }
            }
        }
    }
}

推荐阅读