1

I am trying to write a script in server1 which will be executed using user1 to execute some commands in server2 with user2

So in server1 if I try to execute the below command using user1, I am not able to see the environment variables of user2 (which is defined in /home/user2/.profile)

user1> ssh user2@server2 "env"

Due to this I am not able to execute the user2 specific commands from server1 using ssh.

Note : proper ssh is configured between server1/user1 and server2/user2, and I can view the processes running in server2 from server1 if I give

user1> ssh user2@server2 "ps -ef|grep user2"

1 Answers1

1

tl;dr

user1> ssh user2@server2 '$env'

Long answer

You're missing a $ in your first example of running an ssh command...if you really did type ssh user2@server2 "env" then the "env" would stay a literal string and not expand into any environment variables.

If you want user2 to execute a command using user2's environment variables, you need to pass a string that, when run, will expand into those variables. For example:

user1> ssh user2@server2 'echo $PATH'

Would echo user2's PATH to the terminal.

However, you also need to know that when you run a command via ssh, ~/.profile is not run beforehand (see discussion here). So, if you want access to environment variables defined in ~/.profile, run this:

user1> ssh user2@server2 'source ~/.profile; $env'

WARNING: If you use double quotes (") instead of single quotes ('), then the shell run by user1 will expand any environment variables inside the double quotes to user1's environment variables before the command ever gets sent across ssh to user2.