Read file into String and do a loop in Expect Script

前端 未结 3 1522
萌比男神i
萌比男神i 2020-12-05 12:30

What I am trying to do is to:

  1. Create a .exp file, which will read from the *.txt file from the same directory and parse all the conte
相关标签:
3条回答
  • 2020-12-05 13:10

    I'd refactor a bit:

    #!/usr/bin/expect
    
    set timeout 20
    set user test
    set password test
    
    proc check_host {hostname} {
        global user passwordt
    
        spawn ssh $user@$hostname
        expect "password"
        send "$password\r"
        expect "% "                ;# adjust to suit the prompt accordingly
        send "some command\r"
        expect "% "                ;# adjust to suit the prompt accordingly
        send "exit\r"
        expect eof
    }
    
    set fp [open commands.txt r]
    while {[gets $fp line] != -1} {
        check_host $line
    }
    close $fp
    
    0 讨论(0)
  • 2020-12-05 13:11

    The code should read the contents of the two files into lists of lines, then iterate over them. It ends up like this:

    # 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
    }
    

    You could refactor this a bit with a worker procedure or two, but that's the basic idea.

    0 讨论(0)
  • 2020-12-05 13:12

    Using any of the two solutions here, I would also create a logfile that you can view at a later time. Makes it easy to troubleshoot any problems after the script is run, especially if you're configuring several hundred hosts.

    Add:

    log_file -a [log file name]

    Before your loop.

    Cheers,

    K

    0 讨论(0)
提交回复
热议问题