[英]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. 我将数据发送到远程计算机并执行命令,但我在远程计算机上的$ PATH设置为原始计算机中用户的$ PATH而不是从机计算机中的$ PATH。 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 但是,如果我使用ssh到远程计算机并执行echo $ PATH,则会将其正确设置为新计算机中的登录用户
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 这将打印用户的PATH,在本例中为root在host1上,而不是admin在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. 即使我登录到远程计算机,它仍然以某种方式保留了host1的root环境。 If I do ls -al /, it shows the directories from the remote machine, which means i am logged in to the remote machine 如果我执行ls -al /,它将显示远程计算机上的目录,这意味着我已登录到远程计算机
Let's use set -x
to debug what we actually run: 让我们使用set -x
调试我们实际运行的内容:
$ 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. 毫不奇怪,无论远程PATH
是什么,这也是我们获得的价值。
We can single quote the command to ensure that we send echo $PATH
instead of echo /usr/local/bin:...
to the server: 我们可以单引号命令以确保将echo $PATH
而不是echo /usr/local/bin:...
发送到服务器:
$ 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. 现在, set -x
显示ssh
正在使用unexpanded命令而不是expanded命令运行,并且我们得到了远程PATH
作为返回。
Use -t
: 使用-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. 单引号很重要,因此$PATH
在执行之前不会扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.