Search code examples
linuxbashsftpexpectls

Save the result of ls command in the remote SFTP server on local machine


I have seen How do I pipe the output of an LS on remote server to the local filesystem via SFTP?, 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!