如何将多个参数从一个文件传递给foreach

How to pass multiple arguments to foreach from a file

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

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 替换为主机,将 User1 替换为用户变量,依此类推。

请帮我实现这个。谢谢

由于变量 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
}