'Loop through file and send commands over expect

I am trying to send commands from a file to a device over expect. I tried sending them one at a time from my local machine but all of my file paths were relative to local, not relative to the remote device. My solution was to try to upload the file to the device and load the commands from there. When I try to load the file I keep getting a permissions issue even though if I cat the file from the device I don't have a problem reading it. The file has 1 command per line.

devicepath=rsync://root@localhost:$PORT_RSYNC/root/var/root/file.txt
/usr/bin/rsync -Pavr $1 $devicepath
    
expect <<- expect_feed
set  send_slow  {1  .001}
spawn ssh -o NoHostAuthenticationForLocalhost=yes -p $PORT_SSH root@localhost
expect -re "password:"
send -s "password\r"
expect -re $PROMPT_ROOT
send -s "chmod 777 /var/root/file.txt\r"
expect -re $PROMPT_ROOT
set f [cat /var/root/file.txt]
set cmds [split [read $f] "\n"]
close $f
foreach line $cmds {
    send -s "$line\r"
    expect -re $PROMPT_ROOT
expect_feed

This yields:

root# cat: /var/root/file.txt: Permission denied

I also tried

set f [open /var/root/file.txt]

...but it gave the same error.



Solution 1:[1]

Thanks for the great suggestions. It is working like this.

It would probably work just as well without send slow now that it is sending one line at a time and waiting for a response.

The last command in the file is 'quit' in order to return to the root prompt, I suppose that could have been hard coded

cmdpath=$1
export cmdpath

    expect << 'EXPECT_FEED'
        set send_slow {1  .001}
        set commandfile [open $env(cmdpath)]
        spawn ssh -o NoHostAuthenticationForLocalhost=yes -p $env(PORT_SSH) root@localhost
        expect -re "password:"
        send -s "password\r"
        expect -re $env(PROMPT_ROOT)
        send -s ">the name of the process accepting commands<\r"
        while { [gets $commandfile line] != -1 } {
            expect -re $env(PROMPT)
            send -s "$line\r" }
        expect -re $env(PROMPT_ROOT)
        send "exit\r"
        expect eof
EXPECT_FEED

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1