Home > Blockchain >  Loop through file and send commands over expect
Loop through file and send commands over expect

Time:11-14

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.

CodePudding user response:

If the file you send over contains shell commands, treat it as such and simply source it on the remote host

devicepath=rsync://root@localhost:$PORT_RSYNC/root/var/root/file.txt
/usr/bin/rsync -Pavr "$1" "$devicepath"

export PROMPT_ROOT PORT_SSH

expect << 'EXPECT_FEED'
    set send_slow {1  .001}
    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 ". /var/root/file.txt\r" ;# <<<<
    expect -re $env(PROMPT_ROOT)
    send "exit\r"
    expect eof
EXPECT_FEED

I prefer to use quoted heredocs: shell variables can be passed to expect via the environment.

I'm assuming root's shell is a POSIX-type shell where . is the "source" command.

CodePudding user response:

Thanks for the great suggestions. It is working like this

cmds=$(cat $1)
export cmds

    expect << 'EXPECT_FEED'
        set send_slow {1  .001}
        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"
        expect -re $env(PROMPT_'process')
        send -s "$env(cmds)\r"
        expect -re $env(PROMPT_ROOT)
        send "exit\r"
        expect eof
EXPECT_FEED
  • Related