How to pass a value from bash into expect?
I've got a really simple bash script which requires expect. I need to pass a value from bash into expect and I'm not trying to ssh into another server or anything (cause I only seem to find questions regarding logging into another server via ssh).
The idea is simply something like this:
#!/usr/bin/env bash echo "Please enter your password: " read PASSWD x=$(expect -c ' spawn su -c 'whoami' expect "Password:" send "$PASSWD\r" interact ')
So this doesn't work. The expect shell doesn't recognize the $PASSWD variable. How may this be accomplished?
Another option would be to store the PASSWD in the environment and let expect pick it up there:
read -p "Your password: " passwd export passwd expect -c '... ; send "$env(passwd)\r"; ...'
Probably the best choice security-wise is have expect prompt for the password: then, the password will not show up on the command line nor in the environment.
expect -c <<'END' stty -echo send_user "Your password: " expect_user -re "(.*)\n" send_user "\n" set passwd $expect_out(1,string) stty echo # your script starts here ... send "$passwd\r" ... END
Variables within single quotes are not expanded by the shell, that's why in this case $PASSWD remains the literal string $PASSWD.
Try changing the quotes:
#!/usr/bin/env bash echo "Please enter your password: " read PASSWD x=$(expect -c " spawn su -c 'whoami' expect 'Password:' send '$PASSWD\r' interact ")
One more note: you should be aware that this could pose a security risk, as the password will be visible in plaintext in the process list while the command is running.