Bash: how to run a script remotely
How to run a local script over SSH
Synopsis:
Script execution over SSH without copying script file.You need a simple SSH connexion and a local script.
Code:
#!/bin/shprint_usage() { echo -e "`basename $0` ssh_connexion local_script" echo -e "Remote executes local_script on ssh server" echo -e "For convinient use, use ssh public key for remote connexion" exit 0}[ $# -eq "2" ] && [ $1 != "-h" ] && [ $1 != "--help" ] || print_usageINTERPRETER=$(head -n 1 $2 | sed -e 's/#!//')cat $2 | grep -v "#" | ssh -t $1 $INTERPRETER
Examples:
- ssh-remote-exec root@server1 myLocalScript.sh #for Bash - ssh-remote-exec root@server1 myLocalScript.py #for Python - ssh-remote-exec root@server1 myLocalScript.pl #for Perl - ssh-remote-exec root@server1 myLocalScript.rb #for Ruby
Step by step explanations
This script performs this operations:1° catches first line #! to get interpreter (i.e: Perl, Python, Ruby, Bash interpreter),2° starts remote interpeter over SSH,3° send all the script body over SSH.
Local Script:
Local script must start with #!/path/to/interpreter
- #!/bin/sh for Bash script - #!/usr/bin/perl for Perl script - #!/usr/bin/python for Python script - #!/usr/bin/ruby for Ruby script
This script is not based on local script extension but on #! information.
You can do it like this:
ssh -l yourid 10.1.100.100 << DONEcd /your/dir/./run.pyDONE
Above has been edited, I don't remember what it was like originally, if I want to do it in one single connection, I will do it this way.
ssh -l yourid 10.1.100.100 python < <(echo "import os"echo "os.chdir('/yourdir')"echo "print(os.getcwd())"cat yourscript.py)