pmfl
pmfl

Reputation: 2089

SSH remote machine and execute command

I am sshing to a remote machine and executing a command but my $PATH on the remote machine is set to the $PATH of user in the original machine and not that of sshed machine. But if I ssh to the remote machine and execute echo $PATH, it is set correctly to the logged in user in the new machine

root@host1> ssh admin@remotemachine echo $PATH

This prints the PATH of the user, in this case root on host1 and not admin on remotemachine

root@host1> ssh admin@remotemachine 
admin@remotemachine's password: ****
echo $PATH

Above works fine

Basically it's not changing the environment to the new user on remote machine. Somehow even though i am logged in to remote machine, it preserves the environment of root from host1. If I do ls -al /, it shows the directories from the remote machine, which means i am logged in to the remote machine

Upvotes: 0

Views: 3094

Answers (2)

ryanpcmcquen
ryanpcmcquen

Reputation: 6445

Use -t:

ssh admin@remotemachine -t 'echo $PATH'

From the man page:

 -t      Force pseudo-terminal allocation.  This can be used to execute arbitrary screen-based programs on a
         remote machine, which can be very useful, e.g. when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

The explanation is a bit cryptic, but it will execute whatever you put in quotes. Single quotes are important so that $PATH does not expand before being executed.

Upvotes: 1

that other guy
that other guy

Reputation: 123410

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.

Upvotes: 4

Related Questions