1

我尝试使用期望脚本备份 Linkproof 设备,但遇到了一些麻烦。这是我的第一个脚本,我已经达到了我的极限;)

#!/usr/bin/expect
spawn ssh @IPADDRESS
expect "username:"
# Send the username, and then wait for a password prompt.
send "@username\r"
expect "password:"
# Send the password, and then wait for a shell prompt.
send "@password\r"
expect "#"
# Send the prebuilt command, and then wait for another shell prompt.
send "system config immediate\r"
#Send space to pass the pause
expect -re "^ *--More--\[^\n\r]*"
send ""
expect -re "^ *--More--\[^\n\r]*"
send ""
expect -re "^ *--More--\[^\n\r]*"
send ""
# Capture the results of the command into a variable. This can be displayed, or written to disk.
sleep 10
expect -re .*
set results $expect_out(buffer)
# Copy buffer in a file
set config [open linkproof.txt w]
puts $config $results
close $config
# Exit the session.
expect "#"
send "logout\r"
expect eof

输出文件的内容:

无法确定主机“@IP (XXX.XXX.XXX.XXX)”的真实性。

RSA 密钥指纹为 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。

您确定要继续连接(是/否)?@用户名

请输入“是”或“否”:@password

请输入“是”或“否”:系统配置立即

请输入“是”或“否”:


如您所见,命令的结果不在文件中。请你帮我理解为什么?谢谢你的帮助。

罗穆尔德

4

2 回答 2

3

您所有的“期望”语句都超时了,因为它们等待的文本与实际出现的文本不匹配。让我们检查前一两个,其他的都是一样的。

你说:

expect "username:"

但它实际上从 ssh 收到的是:

The authenticity of host '@IP (XXX.XXX.XXX.XXX)' can't be established.
RSA key fingerprint is XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.
Are you sure you want to continue connecting (yes/no)?

这不包含字符串“用户名:”,因此期望命令将超时,脚本将继续执行下一个命令:

send "@username\r"

我们可以看到它确实发送了:

Are you sure you want to continue connecting (yes/no)? @username

但这不是这个问题的有效答案。

其余的输出是一遍又一遍的相同想法。

于 2010-06-08T16:35:25.423 回答
1

正如@joefis 提到的,您确实需要从 ssh 中获取是/否。

我已经从我在serverexchange的回复中复制了这个, 因为它在这里高度相关

如果您在登录期间监视您的字符串,您将希望避免使用“密码:”,您会发现它并不总是大写。

将您的期望更改为 -re "(.*)assword:" 或 "assword:" 往往更有效地抓住这条线。

如果你发现时间仍然太快,你可以把 sleep 1;在您发送之前

这就是我期望的

expect {
    #When asked about authenticity, answer yes then restart expect block
    "(yes/no)?" { 
        send "yes\n"
        exp_continue 
    }
    "passphrase" { send "\r" }
    -re "(.*)assword:"  { sleep 1; send -- "password\r" }
    -re $prompt { return }
    timeout     { puts "un-able to login: timeout\n"; return }
    eof         { puts "Closed\n" ; return }
}

return所以有几件事,这将允许期望在一个期望上响应任何这些结果,如果找到一条语句,它只会继续更多的代码。我建议设置一个提示值,因为它有助于检测您的命令是否完整或您的登录确实成功。

于 2013-03-07T23:48:25.737 回答