Remotely run a command on a ssh-server with a script

34,707

Solution 1

As Oli commented, you can tell SSH to send commands. You could modify your script so that if your command line arg is 1 it sends ssh user@server "shutdown -h now". Keep in mind that you'll have to be superuser on the other machine to shut it down.

EDIT: Instead of using root, as is suggested in the comments put user into the sudoers file as being able to shut down the machine without a password.

Solution 2

You can pass a command (or list of commands, separated by ; or &&) to a SSH connection like this:

ssh user@server-address "./foo 1"

If you have a local script that outputs 0 or 1, you can simplify things further:

ssh user@server-address "./foo $(/path/to/your/local/script)"

The code in $(...) executes before anything else and its output is put into the line dynamically. It's called command substitution.

Solution 3

You can use runoverssh:

sudo apt install runoverssh
runoverssh -n -s localscript.sh user host

-n will use SSH default authentication (your keys)
-s runs a local script remotely

Share:
34,707

Related videos on Youtube

Malabarba
Author by

Malabarba

I: am the author of Endless Parentheses; help manage and develop CIDER, the most widely used Clojure IDE; help develop GNU Emacs when I have time; author and manage a number of open source projects, among which: Paradox: Modernized Package Menu for Emacs. sx.el: Full-feature Emacs client for StackOverflow, Super User, and the entire Stack Exchange network. aggressive-indent-mode: Minor mode that keeps your code permanently indented. smart-mode-line: A powerful and beautiful mode-line for Emacs. The Bug-Hunter: Hunt down errors in elisp files. names: A namespace system for elisp.

Updated on September 17, 2022

Comments

  • Malabarba
    Malabarba almost 2 years

    I want to run a command on a ssh-server, but this command is determined by a script on my local machine. How do I do that?

    An example for clarity:
    I want to write a script here (foo.sh) that takes an argument. If I run ./foo.sh 0 it should somehow send a shutdown signal to the server machine, but if I run ./foo.sh 1 it should send a restart signal.

    I know how to manually login via ssh, and I've already set ssh-keys to skip passwords, but I don't know how to automate the procedure with a script.

  • João Pinto
    João Pinto over 13 years
    Logging remotely with root enabled is not recommended. Instead he should to setup the sudoers file to be able to execute the shutdown command without requiring a password.
  • Oli
    Oli over 13 years
    Not quite true. They just have to be in the sudoers file as a user who can issue a shutdown without a password prompt. Not too hard to implement.
  • Malabarba
    Malabarba over 13 years
    The shutdown was really just an example, you can change "root" to "user", just to make sure less knowledgeable readers don't try to remotely login as root.