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

» How to Use a Linux (or Mac OS X) Terminal

Every computer hobbyist, at some point, learns to use Linux.  The transition from using a UI based interface in Windows or Mac to performing many functions through the terminal can be a jarring experience for many people.  Many users find the terminal difficult to use and inferior to navigating a UI.  However, the Linux terminal is an extremely powerful device that many learn to love and use often.  Here is a basic introduction to get your feet wet with a terminal.  It...

» How to connect an Apple Bluetooth Keyboard to Ubuntu (Troubleshooting)

Note: This guide uses programs specific to Ubuntu 10.04 (Lucid Lynx) and newer. For older versions of Ubuntu, please refer to .Sometimes the Ubuntu bluetooth stack can behave erratically and prevent you from connecting your Apple Bluetooth Keyboard (or other bluetooth device). The normal procedure for connecting your bluetooth keyboard involves the following steps:First, make sure the bluetooth applet is running by looking for the bluetooth icon on your panel:If it is not running, press ALT+F2,...

» How to Keep a Window Always on Top in Windows

Each iteration of Windows has welcomed some great functionality, but it still lacks an ability which can be very useful: keeping a window permanently visible.  Having a video or reference document visible can be great while trying to multi-task in other windows. Thankfully, third-party solutions exist to work around this problem.All that is needed is a quick, simple download.  Download from box.net, and unzip it somewhere easily accessible (such as your desktop).  Run the...