我是脚本编写新手,需要一些帮助。我正在从 Linux 服务器创建一个预期脚本,该脚本将自动ssh/log
进入我们的 HP StoreOnce Appliance
#!/usr/bin/expect -f
set password "password"
match_max 1000
spawn ssh -o StrictHostKeyChecking=no [email protected]
expect "*?assword:*"
send -- "$password\r"
send -- "\r"
interact
执行此脚本时,我能够自动登录,并可以从那里输入命令。
请参阅下面的输出:
=================================================================
[root@dpis tmp]# ./test.exp
spawn ssh -o StrictHostKeyChecking=no [email protected]
Password:
Last login: Thu Jan 26 08:37:24 2017 from 10.x.x.x
Welcome to the HP StoreOnce Backup System Command Line Interface.
Type 'help' at the prompt for context-sensitive help.
>
但我想要实现的是让脚本不仅自动登录,而且自动输入命令并显示其输出然后退出。
我尝试在交互后添加以下几行
expect ">"
send -- "serviceset show status"
寻求有关如何实现这一目标的帮助?谢谢!
答案1
你有一个好的开始。当您期望输入命令后,您必须按 Enter 键(发送字符\r
)。然后你必须等待另一个提示才能显示结果
expect ">"
send -- "serviceset show status\r"
expect ">"
在expect 中捕获输出有点像PITA。你可以这样做:
# at the top of the program
log_user 0
# ... log in ...
expect ">"
set cmd "serviceset show status\r"
send -- $cmd
expect -re "$cmd\n(.*)\r\n>"
set output $expect_out(1,string)
puts $output
# disconnect
send -- "exit\r"
expect eof