Execute Command on Remote Server via Ssh

Using ssh to login to linux terminal from windows and run command in a logged in shell

Try this :

start cmd /k ssh user@host "/full/path/to/roslaunch launchFile.launch; exec /bin/bash"

How to execute a remote command over ssh with arguments?

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.

Update

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 $__"
}
  • When declaring a function with function, () is not necessary.
  • Don't comment back about it just because you're a POSIXist.

Starting Bash version 4.4, it can also be simplified to this:

function mycommand {
ssh user@123.456.789.0 "cd testdir;./test.sh ${1@Q}"
}

See ${parameter@operator} section in Shell Parameter Expansion.

SSH remote machine and execute command

Let's use set -x to debug what we actually run:

$ set -x
$ ssh localhost echo $PATH
+ ssh localhost echo /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

The line with the + tells us that the command we actually run is:

ssh localhost echo /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

Unsurprisingly, this is also the value we get back, regardless of what the remote PATH is.

We can single quote the command to ensure that we send echo $PATH instead of echo /usr/local/bin:... to the server:

$ ssh localhost 'echo $PATH'
+ ssh localhost 'echo $PATH'

Now set -x shows that ssh is being run with the unexpanded command instead of the expanded command, and we get the remote PATH in return.

Execute command on remote server via ssh

Your PATH is setup differently when your shell is interactive (= when you are logged in on the server), and when not interactive (running commands with ssh).

Look into the rc files used by your shell, for example .bashrc, .bash_profile, .profile (depends on your system). If you set PATH at the right place, then ttisql can work when you run it via ssh.

Another solution is to use the absolute path of ttisql, then it will not depend on your PATH setup.

Can't build go program on remote server through remote ssh command

Use full path to the go binary instead, don't rely on the PATH. Execute whereis go to check where it's located, so it should be sth like:

ssh user@host "/usr/local/go/bin/go version"

More information why did it happen here and here.



Related Topics



Leave a reply



Submit