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

时间:2016-03-28 12:34:48

标签: linux ssh tcl expect

我无法使用expect script在远程主机上运行命令。它只是登录到远程主机并退出。这是代码

#!/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脚本的新手。

1 个答案:

答案 0 :(得分:1)

缩进会有很大帮助:

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 {
    "(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