Score:0

Passing a user input to an ssh command

kz flag

I'm currently trying to create a shell script that will execute a mysqldump on a remote mysql database and then copy the output file back to my local machine. The problem I'm running into is that I don't want to hard code the password into the script. I tried using 'read' to prompt for user input, but that variable doesn't seem to be getting passed to the remote command.

For reference, my script looks something like this:

#!/bin/bash
PASSWORD=""
TABLE=""
while getopts t: flag
do
   case "${flag}" in
      t) TABLE=${OPTARG};;
      *) echo 'invalid argument.'
   esac
done
read -sp "input the mysql password:" PASSWORD
#this is just to verify what the local and remote command is seeing
echo "$TABLE, $PASSWORD"
ssh myserver -p 9999 "echo $TABLE, $PASSWORD"
#this is the ssh command 
ssh myserver -p 9999 "mysqldump --xml -h somesql.us-east-1.rds.amazonaws.com -u admin -p ${PASSWORD} mydb ${TABLE} > ${TABLE}.xml"
scp -p 9999 myserver:/${TABLE}.xml ${TABLE.xml}

If I run that script with

./data_input.sh -t mytable

it will prompt for a password, but not see the PASSWORD variable when the ssh command runs, and mysqldump will fail to authenticate. What is the correct way to pass along the user input variable to the ssh command?

Romeo Ninov avatar
in flag
Why you do not use `mysqldump` directly from your host?
kz flag
@RomeoNinov With the way the server is setup, I can't connect directly to mysql from the local. I need to ssh into the remote and run mysql from there. It is possible mysql could be configured to allow remote connections, but it probably isn't worth it for what we are doing.
Score:3
it flag

You have a space between -p and the password variable, but according to the mysqldump man page:

If given, there must be no space between --password= or -p and the password following it.

kz flag
Nice catch! I'm so used to getting prompted to fill in a password I never even considered that.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.