Linux/Unix Shell Scripting Examples: SSH
Last updated:- SSH using a private key
- SSH command flags
- SSH with simple remote command
- SSH with multiline remote command
- SSH with multiline remote command and save result into a variable
- Force a remote command to be run on bash
WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.
Unless otherwise defined, examples are written in the bash dialect
SSH using a private key
Your key is located under
~/.ssh
, e.g.~/.ssh/id_rsa
.
$ ssh -i /path/to/your/key username@hostnameorip
Remember:
permissions for the
.ssh
directory must be700
the public key (e.g.
id_rsa.pub
) must be644
the private key (e.g.
id_rsa
) must be600
authorized_keys
must be600
SSH command flags
-i path/to/key
: uses the given private key to login using key-based authentication-q
: quiet mode. Useful when you need to usessh
inside scripts.-t
: forces a pseudo-terminal to be used. This is useful to fix errors and warning messages about there not being a tty set when you use SSH to run remote commands.
SSH with simple remote command
$ ssh myusername@remotehost 'ls -lha'
SSH with multiline remote command
Note the use of the
-t
flag, to avoid errors
The "ENDSSH"
...ENDSSH
block is a HEREDOC multi-line string.
The quotes around the first ENDSSH
marker tell bash you don't want it to perform variable expansion within the block.
#!/usr/bin/env bash
# you can add other options to the ssh command too
ssh -t myusername@remotehost << "ENDSSH"
cd /home/myusername
ls -lha
ENDSSH
SSH with multiline remote command and save result into a variable
If you also want to retrieve the output and store it in a variable, do this:
#!/usr/bin/env bash
output=$(ssh -t myusername@remotehost << "ENDSSH"
cd /home/myusername
ls -lha
ENDSSH
)
# do something with the results
echo "$output"
Force a remote command to be run on bash
For the cases when bash is not the default shell in the machine you're SSH'ing to, you can call it as a command:
output=$(ssh myusername@remotehost /bin/bash << ENDSSH
# some bash-specific code
ENDSSH
)
# do something with the results
echo "$output"
Troubleshooting: "here-document at line N delimited by end of-of-file wanted endssh"
Make sure there are no spaces before or after the final ENDSSH