SSH: Execute Remote Command or Script – Linux

This is quite a common task for Linux system administrators, when it is needed to execute some command or a local Bash script from a one Linux workstation or a server on another remote Linux machine over SSH.

In this article you will find the examples of how to execute a remote command, multiple commands or a Bash script over SSH between remote Linux hosts and get back the output (result).

This information will be especially useful for ones, who want to create a Bash script that will be hosted locally on a one Linux machine but would be executed remotely on the other hosts over SSH. (more…)

Start a GUI Application on a Remote Computer using SSH

This article describes how to log into the remote computer (server) using SSH and run a GUI (graphical) application that requires screen. The GUI program will be displayed on the physical monitor, connected to that remote machine.

Run a GUI Program on a Remote Computer’s Screen

The Basic Procedure

Log into a remote machine using SSH:

$ ssh 192.168.1.100

Tell GUI applications to be launched on the local screen (so, any graphical program that you run, will be displayed on the remote computer’s screen):

$ export DISPLAY=:0

Execute GUI Program. For, example lets start Firefox browser that will be launched and displayed on the remote machine’s screen in which we logged in:

$ firefox "www.shellhacks.com"

Use nohup to prevent a process from being stopped after closing SSH session:

$ nohup firefox "www.shellhacks.com"

More Examples

Send a pop-up notification (notify-send) that will be shown on the remote computer’s screen:

$ ssh 192.168.0.100 'DISPLAY=:0 nohup notify-send "Hello" "World"'

Start a music player (rhythmbox) on the remote computer:

$ ssh 192.168.0.100 'DISPLAY=:0 nohup rhythmbox ./Smoke-on-the-Water.mp3'

SSH Login Slow — Removing Delay

Problem: When I’m trying to log into the remote server via SSH, after I enter the UserName, it takes a lot of time before it displays the Password prompt. How to solve this problem?

Solution: Basically, a long delay during authentication process is caused by “GSS API Authentication method” or/and by “UseDNS” option. The solution is to disable the GSSAPIAuthentication method and to set the UseDNS to “no” on the SSH Server.

Edit SSH Server configuration file:

# vi /etc/ssh/sshd_config

UseDNS: Specifies whether sshd should look up the remote host name and check that the resolved host name for the remote IP address maps back to the very same IP address. The default is “yes”.

Set the UseDNS to “no” as shown below:

UseDNS no

GSSAPIAuthentication: Specifies whether user authentication based on GSSAPI is allowed. The default is “no”.

Set the GSSAPIAuthentication to “no”:

GSSAPIAuthentication no

Restart the OpenSSH server to apply changes

For Fedora/Centos/RHEL etc.:

# service sshd restart

For Debian/Ubuntu/LinuxMint etc.:

# sudo service ssh restart

Now you could connect to your Server with SSH quick as usual.

HowTo: Set a Warning Message (Banner) in SSH

SSH warning banners and welcome messages are necessary when organization wishes to prosecute an unauthorized user or just give out some information or announcement.

Display SSH Warning Message BEFORE the Login

Pre login SSH warning banner shows before the password prompt, during an interactive session using SSH. It usually uses for legal warnings to establish the terms and conditions by which someone is allowed to use the system.

The SSH warning messages are commonly located in the files ‘/etc/issue’ and ‘/etc/issue.net’, but you can also use your custom file like ‘/etc/ssh/sshd-banner’. The content of the specified file is sent to the remote user before authentication.

Create an SSH login banner file:

$ vi /etc/ssh/sshd-banner

Append some Warning text:

WARNING:  Unauthorized access to this system is forbidden and will be
prosecuted by law. By accessing this system, you agree that your actions
may be monitored if unauthorized usage is suspected.

Open the sshd_config file:

$ vi /etc/ssh/sshd_config

Edit the path to the banner file:

Banner /etc/ssh/sshd-banner

Save the file and reload the sshd:

$ service sshd reload

Display SSH Welcome Message AFTER the Login

The content of the file ‘/etc/motd’ is displayed after successful authentication, but just before the shell. It is used for system announcements and other important information, that you want authenticated users to know about before they start using the system.

Edit the file ‘/etc/motd’:

$ vi /etc/motd

Place the announcement message and save the file.

Now this message will be shown after the successful authentication through SSH.

3 Steps to Perform SSH Login Without Password

It is very easy to perform SSH login to the remote server without prompting a password.

With a help of utilities from OpenSSH package, you can generate authentication keys on your local machine, copy public key to the remote server and add identities to your authentication agent.

Just three simple steps separate you from the possibility of connecting to a remote server without prompting a password.

Step 1: Generate a key pair on the local server

Use ssh-keygen to generate authentication keys for SSH.

$ ssh-keygen

Output:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): 
Created directory '/home/user/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
8c:2a:ed:82:98:6d:12:0a:3a:ba:b2:1c:c0:25:be:5b

Step 2: Install your public key on the remote server

Use ssh-copy-id to connect to the remote machine and install your public key by adding it the authorized_keys file.

$ ssh-copy-id -i ~/.ssh/id_rsa.pub UserName@RemoteServer

Output:

UserName@RemoteServer's password: ********
Now try logging into the machine, with "ssh 'username@remoteserver'", and check in:
~/.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

Step 3: Add a private key to the authentication agent on the local server

Use ssh-add to add identities to the ssh-agent – the authentication agent.

$ ssh-add

Output:

Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)

Now you can log into the remote server via the SSH protocol without prompting a password.

10 Examples: Copying Files over SSH

SCP (Secure CoPy) – is a remote file copy program, that copies files between hosts on a network.

It uses SSH for data transfer, and uses the same authentication and provides the same security as SSH.

When copying a source file to a target file which already exists, SCP will replace the contents of the target file. If the target file does not yet exist, an empty file with the target file name is created, then filled with the source file contents.

Example 1: Copy the file “file.txt” from a remote host to the local host.

$ scp user@remote.host:file.txt /some/local/directory

Example 2: Copy the file “file.txt” from the local host to a remote host.

$ scp file.txt user@remote.host:/some/remote/directory

Example 3: Copy the directory “dir1” from the local host to a remote host’s directory “dir2”.

$ scp -r dir1 user@remote.host:/some/remote/directory/dir2

Example 4: Copy the file “file.txt” from remote host “remote.host1” to remote host “remote.host2”.

$ scp user@remote.host1:/directory/file.txt user@remote.host2:/some/directory/

Example 5: Copy the files “file1.txt” and “file2.txt” from the local host to your home directory on the remote host.

$ scp file1.txt file2.txt user@remote.host:~

Example 6: Copy the file “file.txt” from the local host to a remote host using port 2222.

$ scp -P 2222 file.txt user@remote.host:/some/remote/directory

Example 7: Copy the file “file.txt” from the local host to a remote host’s home directory. Preserve the modification and access times, as well as the permissions of the source-file in the destination-file.

$ scp -p file.txt user@remote.host:~

Example 8: Copy the file “file.txt” from the local host to a remote host’s home directory. Increase SCP speed by changing the cipher from the default AES-128 to Blowfish.

$ scp -c blowfish file.txt user@remote.host:~

Example 9: Copy the file “file.txt” from the local host to a remote host’s home directory. limit the bandwidth used by SCP command to 100 Kbit/s.

$ scp -l 100 file.txt user@remote.host:~

Example 10: Copy multiple files from the remote host to your current directory on the local host.

$ scp user@remote.host:~/\{file1,file2,file3\} .

Fast Connection with SSH Aliases

If you need to regularly connect to a lot of different servers over SSH, this trick is for you.

Editing SSH configuration file and adding SSH aliases will make the process of the remote connection much more convenient.

Edit SSH configuration file for current user:

$ vi ~/.ssh/config

or edit the main configuration file, if you want to make this alias available for all users:

$ vi /etc/ssh/ssh_config 

Add the next lines:

###   Fast connection aliases   ###
Host AliasName
HostName 1.2.3.4
User YourUserName
Port YourSSHPort

Where:

  • Host – an alias for the target host;
  • HostName – a domain name or an IP address of the target host;
  • User – a user name for the ssh connection;
  • Port – an ssh port on the target host.

Now you can connect to the target host using simple alias:

$ ssh AliasName

SSH with Public Key-Based Authentication

To improve the system security and to enable running automated maintenance tasks on other machines, you can use the key-based authentication instead of standard password authentication.

Key-based authentication uses two keys, one “public” key that anyone is allowed to see, and another “private” key that only the owner is allowed to see.

To securely communicate using key-based authentication, you need to create a public key for the computer you’re logging in from, and securely transmit it to the computer you’re logging in to.

1. Generating a key pair on the local computer

Note that keys must be generated for each user separately.

Create a directory if it doesn’t already exist and set the permissions:

$ mkdir -p ~/.ssh
$ chmod 700 ~/.ssh

Enter the directory and generate public/private RSA key pair:

$ cd ~/.ssh
$ ssh-keygen -t rsa

You can add comment to your public key:
$ ssh-keygen -t rsa -C “A comment… usually an email is enough here…”

Copy the public key to the remote host:

$ scp -p id_rsa.pub RemoteUser@RemoteHost

2. Connecting to the remote server and installing the public key

$ ssh RemoteUser@RemoteHost
Password: ********

Create a directory if it doesn’t already exist and set the permissions:

RemoteHost$ mkdir -p ~/.ssh
RemoteHost$ chmod 700 ~/.ssh

Copy the public key to ‘authorized_keys’ file and set the permissions:

RemoteHost$ cat id_rsa.pub >> ~/.ssh/authorized_keys
RemoteHost$ chmod 600 ~/.ssh/authorized_keys

Remove the public key from the home directory and log out:

RemoteHost$ rm -f ~/id_rsa.pub
RemoteHost$ logout

3. Adding the private key to the authentication agent on the local server

$ ssh-add
Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)

Now you can log into the remote server via the SSH protocol without a password.