Bash 脚本 - 连接到远程服务器并获取结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36556169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script - connect to remote server and get results
提问by Cassie Kasandr
I am trying to write a script that connects to remote server, pings other server (IP as argument) and outputs the result.
我正在尝试编写一个连接到远程服务器的脚本,ping 其他服务器(IP 作为参数)并输出结果。
So here is what I wrote:
所以这是我写的:
#!/bin/bash
# IP as argument
IP=
# Remote connection
ssh -p 22 [email protected]
# Pinging and saving only latency results to RESULT
RESULT=`ping -i 2 -c 4 $IP | grep icmp_seq | awk '{print }' | cut -b 6-12`
# Outputs the result
echo $RESULT
But I am getting an error:
但我收到一个错误:
Name or service not known name tester.myserver.com
Of course tester.myserver.com
is just example but if I manually type that ssh command with my real remote server address it does work. So I've really no idea why this won't work as a script.
当然tester.myserver.com
只是示例,但如果我使用我的真实远程服务器地址手动键入该 ssh 命令,它确实有效。所以我真的不知道为什么这不能作为脚本工作。
回答by NiebieskiLuk
Change your corresponding line to this:
将相应的行更改为:
RESULT=`ssh [email protected] "ping -i 2 -c 4 ${IP}" | grep icmp_seq | awk '{print }' | cut -b 6-12`
or without awk:
或没有 awk:
RESULT=`ssh [email protected] "ping -i 2 -c 4 ${IP} | grep icmp_seq | sed 's/^.*time=\([0-9.]\+\).*//'"`
regards
问候
回答by Pitt
So the usual way to send a command or list of commands to be executed on a remote server is as follows:
所以在远程服务器上发送要执行的命令或命令列表的常用方法如下:
ssh [email protected] "<your commands go here>"
or in your case:
或者在你的情况下:
ssh -p 22 [email protected] "ping -i 2 -c 4 $IP | grep icmp_seq | awk '{print $7}' | cut -b 6-12"
Notice the "\" before $7 to escape the "$". This prevents the $7 to be evaluated to a local variable $7 (which might or not be set) when you run the ssh command, keeping the $7 in the right context with the other commands.
注意 $7 之前的“\”来转义“$”。这可以防止在您运行 ssh 命令时将 $7 计算为局部变量 $7(可能会或不会设置),从而将 $7 与其他命令保持在正确的上下文中。
You would still have to set $IP for it to work though, and so all together looks like this:
你仍然需要设置 $IP 才能让它工作,所以所有的看起来像这样:
IP =
ssh -p 22 [email protected] "ping -i 2 -c 4 $IP | grep icmp_seq | awk '{print $7}' | cut -b 6-12"
Now $IP is resolved locally, while $7 is resolved remotely.
现在 $IP 在本地解析,而 $7 在远程解析。
I had a similar problem to yourswhen I tried to connect to a remote server to run some commands and use a local variable - just like you are doing with $IP.
当我尝试连接到远程服务器以运行一些命令并使用本地变量时,我遇到了与您类似的问题- 就像您使用 $IP 所做的一样。