我正在尝试通过期望脚本循环站点列表。该循环将获取我的列表并逐行读取它,将目录更改为站点名称的文件夹,然后将站点名称传递给期望脚本。
重击脚本:
#!/bin/bash
sites="/home/user/sites.cfg"
while read site; do
cd /home/user/$site
pwd
echo $site
./base.sh
done < $sites
期待脚本:
#!/usr/bin/expect
set site [lindex $argv 0]
set timeout 3
logfile services
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
expect "password" { send mypassword\r }
expect "#"
send environment\ no\ more\n
expect "#"
send show\ service\ service-using\n
expect "#"
send logout\n
结果:
user@myserver:~$ sh show-database.sh
/home/user/site-01
site-01
show-database.sh: 11: show-database.sh: ./base.sh: not found
/home/user/site-02
site-02
show-database.sh: 11: show-database.sh: ./base.sh: not found
我希望在每个站点的每个文件夹中看到一个名为 services 的文件。我可以运行以下命令,它可以从 CLI 运行,但它不会切换目录。这只是一个更大脚本的开始,该脚本在循环中还有更多事情要做。现在,这就是我要测试的内容。
./base.sh site-01
谢谢!
答案1
您根本不需要 bash 包装脚本,expect 可以处理所有这些:
#!/usr/bin/expect
set timeout 3
set rootdir /home/user
set sites [file join $rootdir sites.cfg]
set fh [open $sites r]
while {[gets $fh site] != -1} {
set dir [file join $rootdir $site]
if { ! [file isdirectory $dir]} {
puts "*** error: $dir does not exist"
continue
}
cd $dir
puts [pwd]
puts $site
log_file services
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
expect "password"
send "mypassword\r
expect "#"
send "environment no more\r"
expect "#"
send "show service service-using\r"
expect "#"
send "logout\r"
expect eof
log_file
}