使用ssh在Linux上的本地服务器上执行远程脚本

时间:2017-02-21 09:29:10

标签: linux bash ssh

我有一个名为" test"的脚本在远程服务器的主文件夹中,其中包含以下行:

#!/bin/bash

tengbe=`ifconfig | grep -B1 192.168 | awk 'NR==1 { print $1 }' | sed 's/://g'`

基本上,它只是在调用脚本后将本地服务器的接口名称存储到变量中。当我进入远程服务器调用脚本时,我收到一个错误:

ssh remoteserver-IP './test'
./test: line 3: ifconfig: command not found

我的脚本可能有什么问题?我看到各种答案都无法解决我的问题。

1 个答案:

答案 0 :(得分:1)

尝试:

$ ssh remotehost ifconfig
bash: ifconfig: command not found

ifconfig不在远程主机上的PATH中。你可以用以下方式证明:

$ which ifconfig
/sbin/ifconfig
$ ssh remotehost 'echo $PATH'
(returns lots of dirs, none of which is /sbin)

要解决此问题,请指定ifconfig的完整路径:

$ ssh remotehost /sbin/ifconfig

...或在调用之前配置$PATH

$ ssh remotehost 'PATH=$PATH:/sbin ifconfig'

...或修改$HOME/.bashrc(或替代方案 - 了解您的shell的初始化过程),始终将/sbin添加到$PATH

为了安全起见,在脚本中通常最好指定绝对路径,可能是通过变量。所以在你的脚本中:

#!/bin/bash
IFCONFIG=/sbin/ifconfig
tengbe=$(${IFCONFIG} | grep -B1 192.168 | awk 'NR==1 { print $1 }' | sed 's/://g')

注意,我已用$()替换了你的反引号 - 这不是必需的,但这是一个习惯采用的好习惯 - What is the benefit of using $() instead of backticks in shell scripts?

相关问题