ssh命令不是从bash脚本内部运行的,而是从shell运行的。
我创建了一个简单的脚本,它显示ssh命令在到达远程计算机之前失败。
shell输出如下所示:
外壳的输出:
~ $ nping -c 1 104.248.173.32
Starting Nping 0.7.01 ( https://nmap.org/nping ) at 2019-04-23 22:04 ICT
libnsock mksock_bind_addr(): Bind to 0.0.0.0:0 failed (IOD #1): Invalid argument (22)
SENT (0.0016s) Starting TCP Handshake > 104.248.173.32:80
RECV (0.0017s) Handshake with 104.248.173.32:80 completed
Max rtt: 0.177ms | Min rtt: 0.177ms | Avg rtt: 0.177ms
TCP connection attempts: 1 | Successful connections: 1 | Failed: 0 (0.00%)
Nping done: 1 IP address pinged in 0.00 seconds
~ $ cat /tmp/test.sh
#!/usr/bin/env bash
function doit() {
RUN="/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@104.248.173.32 hostname"
"$RUN"
echo "RESULT: $?"
}
doit
~ $ /tmp/test.sh
/tmp/test.sh: line 5: /usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@104.248.173.32 hostname: No such file or directory
RESULT: 127
~ $ /usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@104.248.173.32 hostname
Host key verification failed.
~ $ echo $?
255我期望脚本中的ssh命令尝试在远程机器上运行主机名,并且由于没有设置键,远程机器会出错。
实际发生的情况是脚本中的ssh命令没有运行,因为有一个“没有这样的文件或目录”错误。
当ssh命令从脚本中运行时,我为什么会看到一个“没有这样的文件或目录”错误,即使脚本在那里,ssh在那里,远程机器在那里?
发布于 2019-04-23 15:59:33
/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@ipaddress hostname和
"/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@ipaddress hostname"...are不一样。前者使用指定的参数执行命令/usr/bin/ssh。后者将整个字符串(包括参数)作为命令名处理。
在shell中运行命令时执行了前者。但是,doit函数使用"$RUN"来处理后者。您将得到“没有这样的文件或目录”,因为实际上,在ssh -o BatchMode...中没有名为/usr/bin (为了简洁而截断)的文件。
如果可能,可以直接执行命令,或者删除引号:
function doit1() {
/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@ipaddress hostname
echo "RESULT: $?"
}
function doit2() {
# assuming there is some usefulness to using a variable in the actual script
RUN="/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=3 root@ipaddress hostname"
$RUN
echo "RESULT: $?"
}https://stackoverflow.com/questions/55814876
复制相似问题