【问题标题】:unable to run remote ssh commands with expect script无法使用期望脚本运行远程 ssh 命令
【发布时间】:2016-03-28 21:42:39
【问题描述】:

我无法使用期望脚本在远程主机上运行命令。它只是登录到远程主机并退出。这是代码

#!/usr/bin/expect
set timeout 15
puts "connecting to the storage\n"
set user [lindex $argv 0]
set host [lindex $argv 1]
set pass "root123"
spawn ssh "$user\@$host"
expect {
"Password: " {
send "$pass\r"
sleep 1
expect {
"$ " {
  send "isi quota quotas list|grep ramesh\r" }
"$ " {
  send "exit\r" }

}
}
"(yes/no)? " {
send "yes\r"
expect {
"$ " { send "ls\r" }
"$ " { send "exit\r" }

"> " {}
}
}
default {
send_user "login failed\n"
exit 1
}
}

它只进入远程主机并退出。 [deep@host1:~]$ ./sshexpect user1 host2 连接到存储

spawn ssh user1@host2
Password:
host2$
[deep@host1:~]$

语法错了吗? 我是 tcl 脚本的新手。

【问题讨论】:

    标签: linux ssh tcl expect


    【解决方案1】:

    缩进会有很大帮助:

    expect {
        "Password: " {
            send "$pass\r"
                sleep 1
                expect {
                    "$ " { send "isi quota quotas list|grep ramesh\r" }
                    "$ " { send "exit\r" }
                }
        }
        "(yes/no)? " {
            send "yes\r"
                expect {
                    "$ " { send "ls\r" }
                    "$ " { send "exit\r" }
                    "> " {}
                }
        }
        default {
            send_user "login failed\n"
                exit 1
        }
    }
    

    问题出在这里:

                expect {
                    "$ " { send "isi quota quotas list|grep ramesh\r" }
                    "$ " { send "exit\r" }
                }
    

    您匹配相同的模式两次:我怀疑 expect 忽略了第一个动作块,而只使用了第二个; 因此你立即退出。

    这就是你想要做的:

    expect {
        "(yes/no)? " { send "yes\r"; exp_continue }
        "Password: " { send "$pass\r"; exp_continue }
        timeout      { send_user "login failed\n"; exit 1 }
        -re {\$ $}
    }
    send "isi quota quotas list|grep ramesh\r"
    
    expect -re {\$ $}
    send "ls\r"
    
    expect -re {\$ $}
    send "exit\r"
    
    expect eof
    

    【讨论】:

    • 我理解了这个错误,但我没有明白下面的行代表什么 -re {\$ $} 以及为什么我们需要在脚本末尾放置期望 eof
    • -re 选项使用正则表达式模式而不是默认的 glob 模式。我指定提示是一个美元符号和一个空格在行尾。如果 expect 看到一个美元符号和一个空格,然后是其他一些文本,那将不匹配作为提示。 expect eof 基本上意味着“等到生成的进程关闭”——这里不是绝对必要的,但通常是很好的做法。
    • 我试过了还是不行。它显示“登录失败”并退出。它只是登录到远程框,然后空白,一段时间后以“登录失败”退出
    • 使用expect -d filename 运行您的脚本以启用调试输出。 expect 会告诉你为什么没有一个模式匹配。
    • 我明白了!现在为我工作
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多