问题描述
我有以下小脚本:
#!/usr/bin/expect
set timeout 90
set ip [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set commands "sudo du -sh /var/tmp"
set regexp ".*"
set failonmatch "false"
if {[string trim $regexp] == ""} {
set regexp ".*"
}
if {[string trim $failonmatch] == ""} {
set failonmatch "false"
}
log_user 0
spawn ssh -o StrictHostKeyChecking=no $username@$ip $commands
...
我想在另一台设备上运行命令(比如 IP 111.23.44.33)。
如何使用特定的 IP、用户名和密码运行命令?我的意思是,我应该使用什么命令来指定参数
我是 Unix 和 Expect 的新手,感谢您的帮助!!
编辑,这是我拥有的期望代码(以防万一):
expect {
timeout {
send_user "Timeout connecting to device.\n"
close
wait
exit 1
}
eof {
send_user "Could not connect to device.\n"
wait
exit 1
}
-re "(.*refused)" {
send_user "Connection to device refused.\n"
wait
exit 1
}
"*assword*:" {send "$password\r"}
}
expect {
timeout {
send_user "Timeout executing command on device.\n"
close
wait
exit 1
}
full_buffer {
append outcome $expect_out(buffer)
exp_continue
}
eof {
append outcome $expect_out(buffer)
puts $outcome
if {"$failonmatch" == "false"} {
if {[regexp $regexp $outcome]} {
wait
exit 0
} else {
wait
exit 1
}
} else {
if {[regexp $regexp $outcome]} {
wait
exit 1
} else {
wait
exit 0
}
}
}
-re "(^.*assword*:)" {
send_user "Unable to login to device.\n"
puts $expect_out(buffer)
close
wait
exit 1
}
}
谢谢!!
解决方法
从代码中可以看出,参数是从$argv
列表中读取的:
set ip [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
expect 是 tcl 语言的扩展。 argv
变量是 documented here。
使用参数调用 expect 程序:
/path/to/expect/program 1.2.3.4 username 's3cretpa$$word'