save the result of ls command in the remote sftp server on local machine
Question
I have seen This question but I am not satisfied with answer. I connect to remote sftp server and I will do ls there I want to have the result of ls on my local machine. I don't want any thing extra to be saved, only the result of ls command. Can I save the result to a variable accessible on the local machine?
#!/usr/bin/expect
spawn sftp myuser@myftp.mydomain.com
expect "password:"
send "mypassword\n";
expect "sftp>"
send "ls\n" //save here
interact
Solution
Here's how I would do it, with a more "traditional" approach that involves opening a file for writing the desired output (I like @kastelian 's log_file idea, though):
#!/usr/bin/expect
spawn sftp myuser@myftp.mydomain.com
expect "password:"
send "mypassword\n";
expect "sftp>"
set file [open /tmp/ls-output w] ;# open for writing and set file identifier
expect ".*" ;# match anything in buffer so as to clear it
send "ls\r"
expect {
"sftp>" {
puts $file $expect_out(buffer) ;# save to file buffer contents since last match (clear) until this match (sftp> prompt)
}
timeout { ;# somewhat elegant way to die if something goes wrong
puts $file "Error: expect block timed out"
}
}
close $file
interact
The resulting file will hold the same two extra lines as in the log_file proposed solution: the ls command at the top, and the sftp> prompt at the bottom, but you should be able to deal with those as you like.
I have tested this and it works.
Let me know if it helped!
OTHER TIPS
Try sending ls
output to the log file:
spawn sftp myuser@myftp.mydomain.com
expect "password:"
send "mypassword\n";
expect "sftp>"
log_file -noappend ls.out
send "ls\n" //save here
expect "sftp>"
log_file
interact
log_file -noappend ls.out
triggers logging program output, and later log_file
without arguments turns it off. Need to expect another sftp prompt otherwise it won't log the output.
There will be two extra lines in log - first line is ls
command itself, last line is sftp>
prompt. You can filter them out with something like sed -n '$d;2,$p' log.out
. Then you can slurp the contents of the file into shell variable, remove temp file, etc. etc.
You can use echo 'ls -1' | sftp <hostname> > files.txt
. Or, if you really want a shell variable (not recommended if you have a long file list), try varname=$(echo 'ls -1' | sftp <hostname>)
.