Bash,预期:SSH 后命令的执行不起作用

Bash, Expect : Execution of command after SSH is not working

我需要登录到虚拟机并在那里执行一些命令。我已经完成了与同一主题相关的所有问题,但没有找到 EXPECT 的任何解决方案。我正在使用 EXPECT,因为我在使用 SSH 时需要传递密码。

我在执行我的脚本时收到 "command not found error",但手动运行,它工作正常。

#!/usr/bin/expect -f

set user [lindex $argv 0]
set to [lindex $argv 1]
set pass [lindex $argv 2]
set command [lindex $argv 3]
puts "$user, $to , $command and $pass ."
# connect via scp
spawn sudo ssh -t -t -v $user@$to << EOF
    ls
EOF

#######################
expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send $pass\n
}
}
interact

收到错误:

spawn sudo ssh -t -t -v username@server_ip << EOF Invalid command name "ls" while executing "ls" (file "./establishSSHConnection.sh" line 10)

您似乎正试图在 'here' 文档中向远程系统发送命令:

spawn sudo ssh -t -t -v $user@$to << EOF
    ls
EOF

相反,您应该使用 'exp_send' 在 'interact' 之前发送 ls 命令,即删除 'here' 文档:

spawn sudo ssh -t -t -v $user@$to

并将 ls 命令放在最后:

expect {
    -re ".*es.*o.*" {
        exp_send "yes\r"
        exp_continue
    }
    -re ".*sword.*" {
        exp_send "$pass\r"
    }
}
exp_send "ls\r"
interact

编辑:

啊,我误会了。如果您只想 运行 命令,那么您需要告诉另一端关闭连接:

expect {
    -re ".*es.*o.*" {
        exp_send "yes\r"
        exp_continue
    }
    -re ".*sword.*" {
        exp_send "$pass\r"
    }
}
exp_send "ls\r"
exp_send "exit\r"
expect {
    eof {puts "Connection closed"}
    timeout {puts "Connection timed out"}
}

Expect(构建于 Tcl 之上)没有此处文档。

如果你想远程执行命令然后结束ssh会话,做

set command "ls -lrt"  ; # for example
spawn sudo ssh -t -t -v $user@$to $command
# ... log in logic
expect eof