[Expect Script]Separate log files for each device

730 Views Asked by At

My code is generated for one log file output from multiple devices.

How could we separate each device for each log file output?

Here is my code:

#!/usr/bin/expect -f
#Slurp up the input file
set fp [open "ip.txt" r]
# To avoid empty lines, 'nonewline' flag is used
set file_data [read -nonewline $fp]
close $fp
set prompt ">"
log_file -noappend router_status.txt
foreach ip [split $file_data "\n"] {
    puts "Router $ip Interface Status"
    spawn telnet $ip
    expect "Username:"
    send "username\r"
    expect "assword:"
    send "password\r"
    expect $prompt
    # To avoid sending 'Enter' key on huge configurations
    send "show interface description\r"
    expect {
    -ex "---(more" { send -- " "; exp_continue }
    "*>" { send "exit\r" }
    }
    set timeout 3; # Reverting to default timeout
    # Sending 'exit' at global level prompt will close the connection
    expect eof
    }
2

There are 2 best solutions below

3
On

You can simply achieve it by changing the log_file

foreach ip [split $file_data "\n"] {
    puts "Router $ip Interface Status"
    spawn telnet $ip

    # Altering 'log_file' for each ip
    log_file -noappend router_${ip}_status.log

    # Your further code here...


}
1
On

In order to handle "cannot start logging without first stopping logging," use "log_file" with no arguments to stop logging, then "log_file path/to/file.log"