1

I need to read the listing of a remote directory using ssh in a shell script. I'm using expect and the code that I tried is

#!/bin/expect

spawn ssh user@server 'ls -t path | head -1' > dir.txt
expect 'Password:*'
send "Password\n"

The result is that no file is created. But if I run the same command on the shell it works

ssh user@server 'ls -t path | head -1' > dir.txt
sthor69
  • 638
  • 1
  • 10
  • 25
  • Possible duplicate of [Use expect in bash script to provide password to SSH command](https://stackoverflow.com/questions/4780893/use-expect-in-bash-script-to-provide-password-to-ssh-command) – nullPointer Jan 21 '19 at 16:48
  • The problem is not to connect via ssh. It does work. The problem is sending the result of ll command to a file – sthor69 Jan 21 '19 at 16:49

1 Answers1

1
  1. expect (and Tcl behind it) do not use single quotes for anything, they are just plain characters. You are effectively doing this:

    spawn ssh user@server "'ls" "-t" "path" "|" "head" "-1'" ">" "dir.txt"
    
  2. I'm not certain, but pretty sure that spawn doesn't do any redirection for you

Try this: let a shell do the redirection: Here I'm using {braces}, which are Tcl's way of doing non-interpolating quoting.

spawn sh -c {ssh user@server 'ls -t path | head -1' > dir.txt}
expect 'Password:*'
send "Password\n"
expect eof

The expect eof will wait for the process to end before allowing your script to continue.


For further reference, here's the manual for Tcl syntax: https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm -- it's a very simple language, only 12 rules.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352