linux - Bash 脚本 - 连接到远程服务器并获取结果

标签 linux bash shell

我正在尝试编写一个脚本来连接到远程服务器,ping 其他服务器(IP 作为参数)并输出结果。

所以这是我写的:

#!/bin/bash
# IP as argument
IP=$1
# Remote connection
ssh -p 22 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384851565f5d4a784c5d4b4c5d4a1655414b5d4a4e5d4a165b5755" rel="noreferrer noopener nofollow">[email protected]</a>
# Pinging and saving only latency results to RESULT
RESULT=`ping -i 2 -c 4 $IP | grep icmp_seq | awk '{print $7}' | cut -b 6-12`
# Outputs the result    
echo $RESULT

但是我收到错误:

Name or service not known name tester.myserver.com

当然 tester.myserver.com 只是示例,但如果我使用真实的远程服务器地址手动键入 ssh 命令,它确实可以工作。所以我真的不知道为什么这不能作为脚本使用。

最佳答案

将相应的行更改为:

RESULT=`ssh <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5c5dcdbd2d0c7f5c1d0c6c1d0c79bd8ccc6d0c7c3d0c79bd6dad8" rel="noreferrer noopener nofollow">[email protected]</a> "ping -i 2 -c 4 ${IP}" | grep icmp_seq | awk '{print $7}' | cut -b 6-12`

或者不使用 awk:

RESULT=`ssh <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b2abaca5a7b082b6a7b1b6a7b0ecafbbb1a7b0b4a7b0eca1adaf" rel="noreferrer noopener nofollow">[email protected]</a> "ping -i 2 -c 4 ${IP} | grep icmp_seq | sed 's/^.*time=\([0-9.]\+\).*/\1/'"`

问候

关于linux - Bash 脚本 - 连接到远程服务器并获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556169/

相关文章:

linux - bash 错误地输出星号和引号

linux - 如何在 Linux 下使用属于子用户命名空间的文件?

bash - 无法将目录更改为符号链接(symbolic link)目录

linux - 比较和显示哈希值

shell - Hbase put shell 命令

linux - grep 包含两个或多个单词,一行一行包含多个文件

linux - rsync 未更改文件

string - Bash:字符串包含连字符

linux - 与 BC 合作

linux - 在 Linux 中,有没有办法在分隔符上对齐文本?