简体   繁体   中英

How to interactive command in expect script

I have a small expect script, and I want to send command based on output. this is example

#! /usr/bin/expect
spawn ssh root@hostname
expect "Password:"
send "12345\r"
expect "root@host:#"
send "ls -lrt"  # depend on this output I need delete file

from here, if i have file list a,b,c,d I want to send "rm a" but file name will change each time when I run script. I don't know how script make wait until I put command, also I don't want to type rm command every time. I only want to type file name.(this is example, the real command is long, I don't want to type same long command every time.) So what I want is that the script wait until I put only file name and after I type file name, it send "rm filename" and keep going rest of script.

please help..

this does not need to be interactive at all. I assume your requirement is to delete the oldest file. so do this:

ssh root@hostname 'stat -c "%Y:%n" * | sort -t: -k1,1n | head -1 | cut -d: -f2- | xargs echo rm'
# .. remove the "echo" if you're satisfied it finds the right file .................... ^^^^

Use expect_user :

#!/usr/bin/expect
spawn ssh root@hostname
expect "Password:"
send "12345\r"
expect "root@host:#"
send "ls -lrt"  # depend on this output I need delete file

expect_user -re "(.*)\n" {
    set filename $expect_out(1,string)
    send "ls -al $filename\r"    ;#// Substitute with desired command
}

expect eof

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