Home > Mac administration, Mac OS X, Unix > Running remote commands via SSH

Running remote commands via SSH

On occasion, I need to run a single remote command on a single system, but don’t have a tool handy (like Apple Remote Desktop’s Send Unix function) to do it. If the machine in question has SSH enabled though, there’s a simple way to do this.

1. Open Terminal

2. Run the following command:

ssh username@server.domain.com "your command here"

For example, if you wanted to use tail to display the latest entries to /var/log/system.log, you would run the following command:

ssh username@server.domain.com "tail -f /var/log/system.log"

You’ll be prompted for a password, which will be used by SSH to log into the remote system. If the password is accepted, tail should start displaying the latest entries to /var/log/system.log as they’re written. To stop, you would hit Control-C as usual. That will stop the command’s execution and close the SSH connection automatically.

Screen Shot 2013-01-16 at 1.07.04 PM

When running commands that require elevated privileges, you’ll need to add the -t flag to your SSH command. -t tells SSH to force pseudo-tty allocation, which in turn provides a way to feed your account’s password to the remote server and run the command via sudo.

For example, if you wanted to restart opendirectoryd on a remote Mac running 10.8.x, you would run the following command:

ssh -t username@server.domain.com "sudo killall opendirectoryd"

You’ll be prompted for a password, which will be used by SSH to log into the remote system. You’ll then be prompted again for a password, which will be used by sudo to authenticate that your account is authorized to run the command with sudo. Once the command is run and completes successfully, the SSH connection closes automatically.

Screen Shot 2013-01-16 at 1.25.12 PM

  1. Shane
    January 17, 2013 at 8:03 pm

    Thanks for the great tip!

    I have ARD but it doesn’t really work well with commands like tail that continuously output data. I have been using ssh for a while to do odd little tasks, but overlooked this feature.

    I would also add to this tip in that if you need to do this frequently on client or lab Macs you should create an SSH key pair for authentication. This will allow your tip to work without needing to type in a password every time.

  2. January 19, 2013 at 2:20 pm

    This tip is gold. I’ve wanted to tail a log file on a remote server (and put on my desktop with Geektool) for months. Tipping my hat to Shane’s comment about the key pair, it’s the perfect solution.

  1. No trackbacks yet.

Leave a comment