expect

Expect script reads from file and puts everything on the same line


Expect script should read commands from file and send them line by line through telnet, but it puts everything on the same line

I have file with commands and my task is to connect to telnet, read command from file and send it. I have to do it for all commands in file. I prepared script, but it puts all commands on the same line and send them as one.

Here is content of file with commands (those are just test commands)

add chain=forward src-address=1.1.1.1 action=log;
add chain=forward src-address=1.1.1.1 action=log;
add chain=forward src-address=1.1.1.1 action=log;
add chain=forward src-address=2.2.2.2 action=log;
add chain=forward src-address=2.2.2.2 action=log;
add chain=forward src-address=2.2.2.2 action=log;
add chain=forward src-address=2.2.2.2 action=log;
add chain=forward src-address=2.2.2.2 action=log;
add chain=forward src-address=3.3.3.3 action=log;
add chain=forward src-address=3.3.3.3 action=log;
add chain=forward src-address=3.3.3.3 action=log;

and here is script I am using

set timeout 1
set fid [open /home/toor/file.txt]
set content [read $fid]
close $fid

###
start telnet and login
###

set records [split $content "\r"]

foreach record $records {
   lassign $records \
         commands
   expect "> "
   send  "$commands\r"
}
sleep 1
expect "> "
send "quit\r"

Any advice, which help me to send every command separately would really help me and I will be very grateful to you


Solution

  • Your commands file probably has \n line endings not \r

    set fid [open /home/toor/file.txt]
    set records [split [read -nonewline $fid] "\n"]
    # ..........................................^
    close $fid
    

    Your lassign command has no purpose. You can just send "$record\r"