1

How can bash securely call an expect script with a password?

I have two scripts: a bash script which is directly executed by a user, and an expect script which is invoked by the bash script and which logs in to the remote host with the password provided in the bash script.

bash script (main.sh)

#!/bin/bash

read -p "User: " user
read -s -p "Password: " password

./login.expect "$user" "$password"

expect script (login.expect)

#!/usr/bin/expect --

set user [lindex $argv 0]
set password [lindex $argv 1]
set host 192.168.1.15

spawn ssh $user@$host
expect -re ".*ssword.*" { send "$password\n" }    # Send password
expect -re ":~\\\$" { send "ls\n" }               # Do stuff
expect -re ":~\\\$" { send "exit\n" }             # exit

At least one problem with this setup is that someone could learn the password by watching the processes with "ps -ef", since the password is being provided on the command line.

These scripts are much simplified from my actual scripts as I am just trying to understand if this part can be done securely in some manner. My actual use case is very complex and requires the bash and expect scripts to be separate, so I can't just embed expect within bash, nor can I request the password from within the expect script. Also unfortunately ssh keys are not an option for passwordless login. I could restructure the expect script to take the password in some way other than a command line option, but I'm not sure what would be a good alternative.

My best option right now is to encrypt the password in bash, pass the encrypted password as an argument to the expect script, and have expect decrypt the password (I don't have the exact mechanics worked out for that).

Is there a better way?

Rusty Lemur
  • 1,697
  • 1
  • 21
  • 54
  • 1
    You may take a look at this question about how to prompt for a password from a expect script: https://stackoverflow.com/questions/681928/how-can-i-make-an-expect-script-prompt-for-a-password. Also this other question provides another approach using a key-based authentication, and avoiding that SSH asks for a password if the authentication fails: https://stackoverflow.com/questions/2991633/how-to-hide-ssh-expect-user-password – Néstor Lucas Martínez Aug 27 '18 at 22:11

2 Answers2

3

You can somewhat securely pass the password through the environment, as this is only readable by the same user and root. In the shell export password, and in the expect script

set password $env(password)
meuh
  • 11,500
  • 2
  • 29
  • 45
0

Read password from a file

set passfile [open "~/.sshpass" r]
gets $passfile userpass
close $passfile

And chmod 700 ~/.sshpass

Sridhar Sarnobat
  • 25,183
  • 12
  • 93
  • 106