无法 运行 使用 expect 脚本远程执行 ssh 命令

unable to run remote ssh commands with expect script

我无法在远程主机上使用 expect 运行 命令 script.It 只是登录到远程主机,exits.Here 是代码

#!/usr/bin/expect
set timeout 15
puts "connecting to the storage\n"
set user [lindex $argv 0]
set host [lindex $argv 1]
set pass "root123"
spawn ssh "$user\@$host"
expect {
"Password: " {
send "$pass\r"
sleep 1
expect {
"$ " {
  send "isi quota quotas list|grep ramesh\r" }
"$ " {
  send "exit\r" }

}
}
"(yes/no)? " {
send "yes\r"
expect {
"$ " { send "ls\r" }
"$ " { send "exit\r" }

"> " {}
}
}
default {
send_user "login failed\n"
exit 1
}
}

它只进入远程主机并退出。 [deep@host1:~]$ ./sshexpect user1 host2 连接到存储

spawn ssh user1@host2
Password:
host2$
[deep@host1:~]$

语法错误吗? 我是 tcl 脚本的新手。

缩进会有很大帮助:

expect {
    "Password: " {
        send "$pass\r"
            sleep 1
            expect {
                "$ " { send "isi quota quotas list|grep ramesh\r" }
                "$ " { send "exit\r" }
            }
    }
    "(yes/no)? " {
        send "yes\r"
            expect {
                "$ " { send "ls\r" }
                "$ " { send "exit\r" }
                "> " {}
            }
    }
    default {
        send_user "login failed\n"
            exit 1
    }
}

问题出在这里:

            expect {
                "$ " { send "isi quota quotas list|grep ramesh\r" }
                "$ " { send "exit\r" }
            }

您匹配了相同的模式两次:我怀疑 expect 忽略了第一个操作块,而只使用了第二个; 因此你立即退出。

这就是你想要做的:

expect {
    "(yes/no)? " { send "yes\r"; exp_continue }
    "Password: " { send "$pass\r"; exp_continue }
    timeout      { send_user "login failed\n"; exit 1 }
    -re {$ $}
}
send "isi quota quotas list|grep ramesh\r"

expect -re {$ $}
send "ls\r"

expect -re {$ $}
send "exit\r"

expect eof