In my .bashrc
I define a function which I can use on the command line later:
function mycommand() {
ssh user@123.456.789.0 cd testdir;./test
This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH
# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`
ssh \
-o StrictHostKeyChecking=no \
-i ~/.ssh/id_rsa \
user@remotehost.example.com \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!
EOF
I'm using the following to execute commands on the remote from my local computer:
ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2
Do it this way instead:
function mycommand {
ssh user@123.456.789.0 "cd testdir;./test.sh \"$1\""
}
You still have to pass the whole command as a single string, yet in that single string you need to have $1
expanded before it is sent to ssh so you need to use ""
for it.
Another proper way to do this actually is to use printf %q
to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:
function mycommand {
printf -v __ %q "$1"
ssh user@123.456.789.0 "cd testdir;./test.sh $__"
}
function
, ()
is not necessary.Reviving an old thread, but this pretty clean approach was not listed.
function mycommand() {
ssh user@123.456.789.0 <<+
cd testdir;./test.sh "$1"
+
}