Aaron Q
Aaron Q

Reputation: 5

Using Expect to fill a password in a bash script

I am relatively new to working in bash and one of the biggest pains with this script I have to run is that I get prompted for passwords repeatedly when running this script. I am unable to pass ssh keys or use any options except expect due to security restrictions but I am struggling to understand how to use expect.

Does Expect require a separate file from this script to call itself, it seems that way looking at tutorials but they seem rather complex and confusing for a new user. Also how do I input into my script that I want it to auto fill in any prompt that says Password: ? Also this script runs with 3 separate unique variables every time the script is called. How do I make sure that those are gathered but the password is still automatically filled?

Any assistance is greatly appreciated.

#!/bin/bash
zero=`echo $2`
TMPIP=`python bin/dgip.py $zero`
IP=`echo $TMPIP`
folder1=`echo $zero | cut -c 1-6`
folder2=`echo $zero`
mkdir $folder1
cd $folder1
mkdir $folder2
cd $folder2
scp $1@`echo $IP`:$3 .

Upvotes: 0

Views: 605

Answers (1)

glenn jackman
glenn jackman

Reputation: 246774

Embedding expect code in an shell script is not too difficult. We have to be careful to get the quoting correct. You'll do something like this:

#!/usr/bin/env bash

user=$1
zero=$2
files=$3

IP=$(python bin/dgip.py "$zero")

mkdir -p "${zero:0:6}/$zero"
cd "${zero:0:6}/$zero"

export user IP files

expect <<<'END_EXPECT'        # note the single quotes here!

    set timeout -1
    spawn scp $env(user)@$env(IP):$env(files) .
    expect {assword:}
    send "$env(my_password)\r"
    expect eof

END_EXPECT

Before you run this, put your password into your shell's exported environment variables:

export my_password=abc123
bash script.sh joe zero bigfile1.tgz
bash script.sh joe zero bigfile2.tgz
...

Having said all that, public key authentication is much more secure. Use that, or get your sysadmins to enable it, if at all possible.

Upvotes: 1

Related Questions