When managing remote servers via SSH, there may be instances where you need to execute commands on the server without waiting for them to complete. While you can run background processes locally using the 'nohup' command or by appending & to the command, these methods don't work as expected with remote SSH commands.
The challenge arises because even if you run a command in the background on the remote server, the SSH session remains blocked until the command finishes. This is problematic when you need to keep the connection active while running commands in the background, especially in automated scripts.
To resolve this issue and run remote commands in the background without blocking the SSH session, follow these steps:
- Prevent SSH from blocking input by redirecting it to /dev/null using the -n option.
- Send the SSH session to the background just before executing the command using the -f option.
These options allow you to run commands on the remote server while freeing up the SSH session immediately.
-n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote ma‐ chine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automat‐ ically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)
-f Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm.
To execute a remote command in the background and suppress any output, use the following command:
$ ssh -n -f user@remote_server 'command_to_execute > /dev/null 2>&1 &'
Alternatively, if you don't need to suppress the output, a simplified version of the command would be:
$ ssh -fn user@remote_server 'nohup command_to_execute &'
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.