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

孤者浪人 提交于 2020-01-16 01:07:12

问题


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

回答1:


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!




回答2:


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.




回答3:


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>).



来源:https://stackoverflow.com/questions/21052944/save-the-result-of-ls-command-in-the-remote-sftp-server-on-local-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!