How to Run Command Using SSH On Remote Machine?
There are different ways to run multiple commands on a remote Unix server using SSH. This article shows the most straightforward and easy approach to SSH and runs multiple commands in using the bash shell.
Single-line command
Executing a single command:
ssh user@server lsExecuting multiple commands, inlined, isolated with ;
ssh user@server ls; pwd; apt updateExecuting a command with sudo
ssh user@server sudo apt update
sudo: no tty present and no askpass program specifiedsudo requires interactive shell, it can be enabled with -t option.
ssh -t user@server sudo ls /root
[sudo] password for user:Multi-line command with variables expansion
Let's say you have a variable VAR1 that you want to run on the remote server. For example, let's consider the following snippet:
VAR1="Variable 1"
ssh user@server '
ls
pwd
if true; then
echo "True"
echo $VAR1 # <-- it won't work
else
echo "False"
fi
'Here SSH will not allow us to run that variable with this method. To make variables expansion work, use bash -c.
VAR1="Variable 1"
ssh user@server bash -c "'
ls
pwd
if true; then
echo $VAR1
else
echo "False"
fi
'"Multi-line command from local script
Use stdin redirection to run a local script using SSH. Let's say you have a script.sh, and it has the following commands.
ls
pwd
hostnameNow to run it using SSH, use the following snippet:
ssh user@server < script.shMulti-line command using Heredoc
Heredoc is presumably the most helpful approach to execute multi-line commands on a remote machine. Likewise, variables extension works out-of-the-box.
VAR1="Variable 1"
ssh -T user@server << EOSSH
ls
pwd
if true; then
echo $VAR1
else
echo "False"
fi
EOSSHIf you need to assign variables inside the heredoc block, put the opening heredoc in single quotes.
ssh user@server <<'EOSSH'
VAR1=`pwd`
echo $VAR1
VAR2=$(uname -a)
echo $VAR2
EOSSHUsing the above snippet, you may get this below warning message:
Pseudo-terminal will not be allocated because stdin is not a terminal.You can disable by adding -T parameter to the SSH command.
ssh -T user@server <<'EOSSH'
VAR1=`pwd`
echo $VAR1
VAR2=$(uname -a)
echo $VAR2
EOSSH
Please login or create new account to add your comment.