So here is my problem, I have this script I wrote where I'm exporting two variables however they're not making it into the subshell.
The point of this script is to change a users password and clear out their pam_tally for CentOS and Ubuntu hosts.
A little background is that this environment's users are managed by puppet but the passwords are all local, ssh keys are not allowed either (this is set in stone and can't be changed so I have to work with what I got) and the reason is that every log in has to be manual (even number of sessions are limited to two so you can't even user csshX effectively).
Here is my script
#!/bin/bash
echo "Please enter user whose password you want to change"
read NEWUSER
echo "Please enter new password for user"
read -s -p "Temp Password:" TEMPPASSWORD
PASSWORD=$TEMPPASSWORD
export PASSWORD
NEWUSER2=$NEWUSER
export NEWUSER2
for i in HOST{cluster1,cluster2,cluster3}0{1..9}
do
ping -c 2 $i && (echo $i ; ssh -t $i '
sudo pam_tally2 --user=$NEWUSER2 --reset
echo -e "$PASSWORD\n$PASSWORD" | sudo passwd $NEWUSER2
sudo chage -d 0 $NEWUSER2
')
done
You are using
ssh
to connect to a remote host and run a script on that host.ssh
does not export the local environment to the remote session but instead performs a login on the remote host which sets the environment according to the remote user's configuration on the remote host.I suggest you pass all needed values via the command you want to execute. This could be done like this:
Watch closely how this uses quotes. At each occasion where you used a variable, I terminate the single-quoted string (using
'
), then add a double-quoted use of the variable (e. g."$PASSWORD"
) and then start the single-quoted string again (using'
again). This way, the shell executing thessh
command will expand the variables already, so you have no need to pass them into the remote shell.But be aware that special characters in the password (like
"
or'
oror maybe a bunch of other characters) can mean trouble using this simple mechanism. To be safe against this as well, you would need to use the
%q
format specifier of theprintf
command to quote your values before passing them: