SSH远程机器并执行命令 [英] SSH remote machine and execute command

查看:54
本文介绍了SSH远程机器并执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 SSH 到远程机器并执行命令,但我在远程机器上的 $PATH 设置为原始机器中用户的 $PATH,而不是 sshed 机器的 $PATH.但是如果我 ssh 到远程机器并执行 echo $PATH,它被正确设置为新机器中的登录用户

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

这会打印用户的 PATH,在这种情况下是 host1 上的 root 而不是远程机器上的 admin

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

以上工作正常

基本上它不会将环境更改为远程机器上的新用户.不知何故,即使我登录到远程机器,它也保留了来自 host1 的 root 环境.如果我执行 ls -al/,它会显示来自远程机器的目录,这意味着我已登录到远程机器

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

推荐答案

让我们使用 set -x 来调试我们实际运行的内容:

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

不出所料,这也是我们返回的值,无论远程 PATH 是什么.

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

我们可以将命令单引号以确保我们向服务器发送 echo $PATH 而不是 echo/usr/local/bin:... :>

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'

现在 set -x 显示 ssh 正在使用未扩展命令而不是扩展命令运行,我们得到远程 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.

这篇关于SSH远程机器并执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆