简体   繁体   English

如何在期望脚本中交互命令

[英]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.从这里开始,如果我有文件列表 a,b,c,d 我想发送“rm a”但是每次运行脚本时文件名都会改变。 I don't know how script make wait until I put command, also I don't want to type rm command every time.我不知道脚本如何等待直到我输入命令,而且我不想每次都输入 rm 命令。 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.我只想输入文件名。(这是一个例子,真正的命令很长,我不想每次都输入相同的长命令。)所以我想要的是脚本等到我只输入文件名之后我输入文件名,它发送“rm 文件名”并继续执行脚本的其余部分。

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 :使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM