如何从文件传递多个参数到foreach

时间:2015-09-18 00:16:36

标签: expect

我有一个文件,其中包含一个服务器列表(空间)用户,现在我想将此文件作为参数传递给我的expect脚本,以便我的脚本将一个ssh会话生成到user @ server并执行一堆命令并退出。

cat HostsUserFile.txt 

Server1 User1
Server2 User2
Server3 User3

cat CollectStats.exp

### Get the list of hosts, one per line, whereas hosts.txt should be a file    containing the list of servers and user #####
set password ****
set f [open "HostsUserFile.txt"]
set hosts [split [read -nonewline $f] "\n"]
close $f

### Loop through the hosts listed in host.txt ###
foreach { host user } $hosts {
### spawn ssh process ###
spawn -noecho ssh -q $user@$host -o StrictHostKeyChecking=no
expect "*?assword*"
send "$password\r"
expect "*$*"
send "exit\r"
}

我希望在第一次迭代期间将Server1替换为host并将User1替换为用户变量,依此类推。

请帮助我实现这一目标。感谢。

1 个答案:

答案 0 :(得分:0)

由于变量hosts是列表列表(即{Server1 User1} {Server2 User2} {Server3 User3}),您应该使用单个变量用于foreach循环,并且在其中您可以将项目提取为

foreach hostinfo $hosts {
    # If your 'Tcl' version is 8.5 or above, use lassign as, 
    #           lassign $hostinfo server user
    # Else, use 'lindex' to get this done
    set server [lindex $hostinfo 0]
    set user [lindex $hostinfo 1]
    puts "Server : $server , User : $user"

    # Your further code on ssh
}