简体   繁体   中英

How to list a directory with expect via sftp connection

I have this expect script but the list of files does not present me correctly.

expect.dat

set timeout 10000
spawn sftp -o ConnectTimeout=3 user@192.1.6.6
expect "*?assword*"
send   "tech\r"
expect "sftp>"
send   "cd /global/scripts/log\r"
expect "sftp>"
send   "ls 20220703*\r"
expect "sftp>"
send   "bye\r"

Expect command

expect expect.dat

Result

spawn sftp -o ConnectTimeout=3 user@192.1.6.6
Password:
Connected to user@192.1.6.6.
sftp> cd /global/scripts/log
sftp> ls 20220703*
20220703_A.log        20220703_A.xls
20220703_E.log        20220703_E_r.log
sftp> You have new mail in /var/spool/mail/dm

how to get this result?

20220703_A.log
20220703_A.xls
20220703_E.log
20220703_E_r.log

First, use the sftp command ls -1 20220703* to produce output in a single column.

Next, use log_user 0 and spawn -noecho sftp ... to hide all the excess output.

Last, and the trickiest part, capture the ls output so that can be printed out cleanly: we have to handle the fact that the command we just "typed" will be given back to us.

set ls_cmd "ls -1 20220703*"
send   "$ls_cmd\r"

# capture the command's output
expect -re "$ls_cmd\r\n(.*)\r\nsftp>"
puts $expect_out(1,string)

send   "bye\r"
expect eof     # wait for sftp to exit cleanly

expect gives you the process's output using \r\n line endings.

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