简体   繁体   中英

Cannot use expect in Bash script

In my bash script file, I try to use expect to provide password for ssh command but it doesn't work. Here is my script:

#!/bin/bash

/usr/bin/expect << EOD
spawn ssh root@192.168.1.201
expect "root@192.168.1.201's password:"
send "mypassword\r"
interact
expect eof
EOD

And the output after I execute the script:

[oracle@BTMVNSRV191 Desktop]$ ./login.sh
spawn ssh root@192.168.1.201
root@192.168.1.201's password: [oracle@BTMVNSRV191 Desktop]$ 

Could someone let me know, how to use expect in my script without changing #!/bin/bash to #!/usr/bin/expect ?

The following works as a single line of bash script in OS X Terminal. It was only intended for use on a firewall protected LAN. Further details at my original post .

expect -c 'spawn ssh -o StrictHostKeyChecking=no remote-user@remote-IP; 
expect assword; send remote-password\r; expect remote-user$; 
send "sudo shutdown -h +1\r"; expect assword; send remote-password\r; interact'

ssh (and any other password reading tool) reads its password not from its standard input. It uses some tricky ioctl()-s on its terminal device. This is because you can't give them your password in a pipe.

It is not really a big problem, because widely used cleartext passwords caused more harm as if sometimes we need to find some alternative, password-less solution.

In cases of the ssh, there is a very simple thing for that. Google for ssh-keygen . I suggest to use that, configure a passwordless ssh and everything will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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