Secure Shell includes a lot of tricks, many of which can make your admin’s life exponentially easier. One such trick is the ability to run commands on remote servers, without logging in.
Sure, you can take the time to log into the server, run the command, and log out, but why not just do it all in one fell swoop? Not only is this handy, it’s quite easy.
SEE: Top Commands Linux Admins Need to Know (TechRepublic Premium)
What you need
The only thing you need for this is two more Linux machines, including the openssh-server up and running (and accepting connections). You can do this from the standard repositories if you don’t have the SSH daemon installed. For instance, on the Ubuntu Server platform, the command to install the SSH daemon is:
sudo apt-get install openssh-server -y
Once installed, you’ll want to enable the server with the commands:
sudo systemctl start sshd
sudo systemctl enable sshd
Note that on Ubuntu systems, the service for the OpenSSH server is named ssh, not sshd. Therefore, the commands to start and enable the SSH server would be:
sudo systemctl start ssh
sudo systemctl enable ssh
Now that you have the SSH daemon running on your remote servers, you can send commands to them. Let’s find out how.
SEE: How to View Your SSH Keys in Linux, macOS, and Windows (TechRepublic)
Running a basic command
Let’s get a listing of files on a remote /etc directory. To do this, the command is:
ssh USER@SERVER_IP "ls /etc"
Where USER is a remote username, and SERVER_IP is the IP address of the remote server. Once you successfully enter the remote user’s password, you will get a listing of the /etc/ directory on the remote server.
Easy-peasy.
SEE: How to Quickly Give Users sudo Privileges in Linux (TechRepublic)
Running a command that requires sudo
But what if you need to run a command that requires sudo privileges on a remote server? If you do that, you’ll see a tty error.
How do you get around that? Fortunately, there’s a little switch you can add to the command. Said switch is -t. What does -t do? It forces pseudo-terminal allocation, so ssh has no idea it doesn’t have a local terminal to use.
So, to run a remote command, via ssh, that requires sudo privileges, the ssh command looks like:
ssh -t USER@SERVER_IP "sudo COMMAND"
Say, for instance, you want the user jack to upgrade a remote server at 192.168.1.201. This command is:
ssh -t jack@192.168.1.201 "sudo apt-get upgrade -y"
You will first be asked for the user’s password for the SSH connection, followed by a second request for the user’s password for sudo privileges.
The command will run as though it was executed on the local machine (only it’s running on the remote machine). When the command completes, you’ll return to the local prompt, ready to keep working.
And that’s all there is to running commands that require sudo privileges on a remote machine, via SSH.
This article was originally published in July 2019. It was updated by Antony Peyton in January 2025.