Expect script not sending commands after successful ssh login

好久不见. 提交于 2019-12-25 09:16:14

问题


When launching the following script, the ssh login succeeds, and I'm able to interact, but it doesn't send the cd folder command. Is my expect "$" command useful at all if I know for sure that this is the first command I want to send, and how can the cd folder command be sent?

Here's the short expect script:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no host@exemple.com
expect "password"
send "mypassword\r"
expect "$"
send "cd folder\r"
interact

Thank you!


回答1:


You need to expect a more specific shell prompt.

According to expect's manual:

Note that in many editors, the ^ and $ match the beginning and end of lines respectively. However, because expect is not line oriented, these characters match the beginning and end of the data (as opposed to lines) currently in the expect matching buffer.




回答2:


You should create your SSH keys using ssh-keygen (or like this), and ask the server administrator to add your public key to ~/.ssh/authorized_keys on the server. Then you will be able to log in to the remote machine without specifying the password. Otherwise, anyone who has read access to the script would be able to access the remote server on your behalf! There is a good discussion regarding this problem.

With the configured keys, you can simply

ssh user@exemple.com -- 'cd folder; # whatever'

or, using the here document syntax:

#!/bin/bash -
ssh -tt user@host <<'EOC'
cd folder
# do something else
exit
EOC

Note, the first -t option forces pseudo-terminal allocation. Multiple -t options force tty allocation, even if ssh has no local tty.



来源:https://stackoverflow.com/questions/40498940/expect-script-not-sending-commands-after-successful-ssh-login

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!