简体   繁体   中英

save the result of ls command in the remote sftp server on local machine

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

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.

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!

You can use echo 'ls -1' | sftp <hostname> > files.txt 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>) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM