Execute a command remotely over SSH and then close the connection

(0 votes, average 0 out of 5)

It is possible to execute a command on a remote system using the ssh command. It is best if you set up password-less login for SSH if you want to run this from a script. An example would be retrieving the amount of memory usage:

1
ssh user@myremotemachine free -m

This works well except that even after the free -m command is run, the SSH connection is not terminated. Thus, if this is used in a script it may cause the script to quit prematurely or introduce some other undesireable behavior. To ensure that the SSH connection is closed after running the commands, include the exit command after the commands you want to run remotely and enclose the entire thing in a heredoc:

1
2
3
4
ssh user@myremotemachine <<-EOF
    free -m
    exit
EOF

This will ensure that the free -m command runs remotely and then the SSH connection is terminated.

Partner Links:
Last Updated on Tuesday, 15 March 2011 12:19  
Related Articles

» Grant Write Access to CIFS Mount As A Regular User

Often you may want a cifs/smbfs (Samba) mount on Linux to be writeable by normal users. If it is the case that you can write to the mounted filesystem as root but not as a normal user (Permission Denied), then you may need to adjust your mount options in /etc/fstab. The key mount options are file_mode and dir_mode, which override the default file and directory permissions for Samba shares. By manually setting these values, you can grant read/write access to normal users on the local...

» Easily "Force Quit" or "End Task" on a program in Linux with a keyboard shortcut

Note: This guide is written for an Ubuntu-based system but should work on any Linux distribution running the Gnome desktop environment.If a program stops responding in Linux, an easy way to kill it is with the xkill utility. This utility turns the mouse into crosshairs. Once the user clicks on a window with the crosshairs, said window is instantly killed. This is much more convenient than trying to find the process ID or name in a list of running processes and stopping it. In order to set up...

» How to Track an iPhone or iPad

Since the iPhone and the iPad have an internal GPS receiver, they can be tracked or a lost device can be found using Apple's Mobile Me service.You can learn more about this service or sign up for a free trial of Mobile Me at .