shell - 将文件读入 String 并在 Expect Script 中执行循环

标签 shell unix loops tcl expect

我想要做的是:

  • 创建一个 .exp文件,将从 *.txt 中读取文件,并将文本文件中的所有内容解析为expect脚本中的字符串变量。
  • 循环包含一系列主机名的字符串,并执行一系列命令,直到字符串被枚举。

  • 所以脚本的作用是从 txt 中读取一系列主机名。同目录下的文件,然后将它们读入字符串,.exp文件将自动登录到每个文件并执行一系列命令。

    我编写了以下代码,但它不起作用:
    #!/usr/bin/expect
    
    set timeout 20
    set user test
    set password test
    
    set fp [open ./*.txt r]
    set scp [read -nonewline $fp]
    close $fp
    
    spawn ssh $user@$host
    
    expect "password"
    send "$password\r"
    
    expect "host1"
    send "$scp\r"
    
    expect "host1"
    send "exit\r"
    

    任何帮助是极大的赞赏....

    最佳答案

    代码应该将两个文件的内容读入行列表,然后遍历它们。它最终是这样的:

    # Set up various other variables here ($user, $password)
    
    # Get the list of hosts, one per line #####
    set f [open "host.txt"]
    set hosts [split [read $f] "\n"]
    close $f
    
    # Get the commands to run, one per line
    set f [open "commands.txt"]
    set commands [split [read $f] "\n"]
    close $f
    
    # Iterate over the hosts
    foreach host $hosts {
        spawn ssh $user@host
        expect "password:"
        send "$password\r"
    
        # Iterate over the commands
        foreach cmd $commands {
            expect "% "
            send "$cmd\r"
        }
    
        # Tidy up
        expect "% "
        send "exit\r"
        expect eof
        close
    }
    

    您可以使用一两个工作程序对其进行重构,但这是基本思想。

    关于shell - 将文件读入 String 并在 Expect Script 中执行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662391/

    相关文章:

    loops - Dart:从foreach循环中的if退出函数

    php - 在 Hostgator jailed shell 上使用 PHP 创建 SYMLINK - Get Perm Denied 错误

    Java Runtime.getRuntime.exec() 返回 null 但在 shell 中返回有效字符串

    c++ - 在一行中读取 SMTP 邮件

    loops - 将与模式匹配的行打印到文件 A,如果不匹配则打印到文件 B

    Java - 循环问题

    bash - 从控制台输出中获取最后 n 行

    shell - 使用 Jenkins 运行 ios-sim

    regex - AWK 匹配以数字开头的字符串

    linux - 查找文件linux的修改时间和修改用户名