使用 ssh 和 expect 编写远程列表

write remote listing using ssh with expect

我需要在 shell 脚本中使用 ssh 读取远程目录的列表。 我正在使用 expect,我尝试的代码是

#!/bin/expect

spawn ssh user@server 'ls -t path | head -1' > dir.txt
expect 'Password:*'
send "Password\n"

结果是没有创建文件。 但是,如果我 运行 在 shell 上执行相同的命令,它就可以工作

ssh user@server 'ls -t path | head -1' > dir.txt
  1. 期望(和它背后的 Tcl)不要对任何东西使用单引号,它们只是普通字符。您正在有效地执行此操作:

    spawn ssh user@server "'ls" "-t" "path" "|" "head" "-1'" ">" "dir.txt"
    
  2. 我不确定,但可以肯定 spawn 不会为您做任何重定向

试试这个:让 shell 进行重定向:这里我使用 {braces},这是 Tcl 进行非内插引用的方式。

spawn sh -c {ssh user@server 'ls -t path | head -1' > dir.txt}
expect 'Password:*'
send "Password\n"
expect eof

expect eof 将等待进程结束,然后再允许您的脚本继续。


为了进一步参考,这里是 Tcl 语法手册:https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm -- 这是一种非常简单的语言,只有 12 条规则。