Quick Tip: Pass a Command to an SSH Session as an Argument

Today’s Quick Tip isn’t necessarily an easier way of accomplishing a task, it’s simply a time saver I find myself using often. SSH is a fabulous tool for administrating remote systems via a remote shell, but you may not always need a fully interactive environment to accomplish a given task. Let’s take for example restarting a service. In order to restart a service via a traditional SSH session you must connect to the machine, restart the service with either the¬†service command¬†or /etc/init.d/, and disconnect. Using today’s Quick Tip, that entire process can be wrapped up into a single command. First, we’ll look at the basic method of passing the command then show how a service can be restarted in this way.

Passing a command into an SSH session upon connection is actually quite simple and can be achieved with this command:

[code language=”bash”]ssh username@host ‘commands to be executed upon connection go here. Separate commands with a semicolon(;)'[/code]

Going back to our service restart example:

[code language=”bash”]ssh foo@bar ‘service httpd restart'[/code]

The above command connects to a machine named “bar”, restarts httpd, prints the output of the command to the screen, and disconnects.

Granted, using SSH in this way may not save very much time day-to-day, but I find it much simpler to type a single command when I know exactly what commands I need to run against a remote machine.

//J

Leave a Reply

Your email address will not be published. Required fields are marked *