I'm new to bash scripting. I want to call a function from my script which will ssh into a remote computer (on my LAN) and run a command.
So far I have:
function run_ssh_command {
target_ip=$1
username=$2
password=$3
cmd=$4
ssh -l ${username} ${target_ip} ${password}
}
I invoke the function from the terminal as follows:
(Note: I give script_name, username and password "real" values when executing the function on my machine. 'ifconfig' is the command I want to run on the remote machine.)
source script_name.sh; run_ssh_command 192.168.X.Y username password ifconfig
Result: Running the above command will get me to the password prompt part of the login process (e.g. same as ssh username@192.168.X.Y)
Question: I want to handle the password entry automatically using the script. What is the "best" way to go about this, in general?
sshpass
is an option for you. Usage issshpass -p <PASSWORD> ssh user@host
; in your casesshpass -p <PASSWORD> ssh user@host ifconfig
. – mnille Apr 17 '18 at 11:59${variable_name}
doesn’t mean what you think it does … – G-Man Says 'Reinstate Monica' Apr 17 '18 at 21:00$user
is just as good as${user}
. And the other point is you should always quote your shell variable references (e.g.,"$username"
and"$target_ip"
) unless you have a good reason not to, and you’re sure you know what you’re doing. This probably won’t be an issue for a user name or an IP address, … (Cont’d) – G-Man Says 'Reinstate Monica' Apr 18 '18 at 17:58password=$3
(where$3
iscorrect horse
) and then you say${password}
, that will be treated as two separate arguments (correct
followed byhorse
), rather than one argument with a space in it. A word that contains*
or?
can also cause problems. This is commonly seen as a concern when you write a script that handles file names. – G-Man Says 'Reinstate Monica' Apr 18 '18 at 17:58