Reputation: 15808
I have a script (say run.py
) and I want to scp that to a remote machine (say 10.1.100.100
), cd into a directory in that remote machine, and execute run.py
in that directory.
How do I wrap the above procedure in one single bash script? I don't know how to let bash execute commands remotely in another machine.
Hopefully I can see that stdout of run.py
in my terminal. But if I can only redirect it, that's fine as well.
Upvotes: 4
Views: 5944
Reputation: 1
Remember, that this is not a rule, that you HAVE TO cd to the requested directory.
Once you get access to the remote machine, just type a relative path to this file, without using cd:
/some_folder/./run.py
Upvotes: 0
Reputation: 104
Script execution over SSH without copying script file. You need a simple SSH connexion and a local script.
#!/bin/sh
print_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_usage
INTERPRETER=$(head -n 1 $2 | sed -e 's/#!//')
cat $2 | grep -v "#" | ssh -t $1 $INTERPRETER
- 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
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 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.
Upvotes: 3
Reputation: 7640
You can do it like this:
ssh -l yourid 10.1.100.100 << DONE
cd /your/dir/
./run.py
DONE
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
)
Upvotes: 1
Reputation: 16399
chmod +x ./run.py
scp -pq ./run.py 10.1.100.100:'/home/myremotedirectory/run.py'
ssh 10.1.100.100 'cd /somedirectory && /home/myremotedirectory/run.py'
See if that helps
Upvotes: 5