【问题标题】:save the result of ls command in the remote sftp server on local machine将 ls 命令的结果保存在本地机器上的远程 sftp 服务器中
【发布时间】:2014-01-10 19:36:17
【问题描述】:

我见过This question,但我对答案不满意。我连接到远程 sftp 服务器,我会在那里做 ls 我想在我的本地机器上得到 ls 的结果。我不想保存任何额外的东西,只需要 ls 命令的结果。我可以将结果保存到本地机器上可访问的变量吗?

#!/usr/bin/expect

spawn sftp myuser@myftp.mydomain.com
expect "password:"
send "mypassword\n";
expect "sftp>"
send  "ls\n"  //save here
interact

【问题讨论】:

    标签: linux bash sftp expect ls


    【解决方案1】:

    尝试将ls 输出发送到日志文件:

    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 触发记录程序输出,稍后log_file 不带参数将其关闭。需要期待另一个 sftp 提示,否则它不会记录输出。

    日志中会多出两行——第一行是ls 命令本身,最后一行是sftp> 提示。您可以使用sed -n '$d;2,$p' log.out 之类的内容将它们过滤掉。然后你可以将文件内容slurp到shell变量中,删除临时文件等等。

    【讨论】:

      【解决方案2】:

      这是我的做法,采用更“传统”的方法,包括打开文件以写入所需的输出(不过我喜欢 @kastelian 的 log_file 想法):

      #!/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
      

      生成的文件将包含与 log_file 建议的解决方案中相同的两行额外行:顶部的 ls 命令和底部的 sftp> 提示符,但您应该能够根据需要处理这些。

      我已经测试过了,它可以工作。

      如果有帮助请告诉我!

      【讨论】:

      • 谢谢詹姆斯。这个文件在本地机器上正确吗?我不想在远程机器上创建文件
      • 没错,文件在本地机器上(期望脚本运行的地方),not 在远程机器上。您可以将路径及其名称从我放置的(/tmp/ls-output)编辑到您喜欢的任何位置(/home 等)。
      【解决方案3】:

      您可以使用echo 'ls -1' | sftp <hostname> > files.txt。或者,如果你真的想要一个 shell 变量(如果你的文件列表很长,不推荐),试试varname=$(echo 'ls -1' | sftp <hostname>)

      【讨论】:

      • 谢谢我正在使用期望脚本。你知道怎么做吗?我会在问题中更新它
      猜你喜欢
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多