2016-11-17 76 views
0

在脚本继续之前,我需要在bash脚本中检查远程服务器上的端口。 我在这里和在互联网上搜索,但我无法找到适合我的答案。在bash脚本中检查远程端口状态

我正在使用RHEL 7.2虚拟机,所以我没有-z参数nc命令或/dev/tcp/的事情。 也nc remote.host.com 1284 < /dev/null鸵鸟政策工作,因为每次我得到退出代码1.

基本上我需要类似的东西:

/bin/someting host port 

if [ $? -eq 0 ]; then 
echo "Great, remote port is ready." 
else 
exit 1 
fi 
+0

对于它的价值,'NC host.com 1234 | grep -q“打开”'? – eddiem

+0

使用RHEL7可以使用/ dev/tcp。用'ls'命令不可见。 – Cyrus

+0

@Cyrus:我鸵鸟政策工作: '$ /dev/tcp/google.com/80 -bash:/dev/tcp/google.com/80:没有这样的文件或directory' @eddiem : 'nc remote_server 1313 Rohlik

回答

1

如何NMAP?

SERVER=google.com 
PORT=443 
state=`nmap -p $PORT $SERVER | grep "$PORT" | grep open` 
if [ -z "$state" ]; then 
    echo "Connection to $SERVER on port $PORT has failed" 
else 
    echo "Connection to $SERVER on port $PORT was successful" 
    exit 1 
fi 

请注意您必须安装nmap。

yum install nmap #Centos/RHEL 
apt-get install nmap #Debian/Ubuntu 

我们可以从source进行编译和安装。

0

而不是使用“/ dev/null”,你应该使用一个简短的字符串。当使用/ dev/null时,它会导致远程服务器等待,因为它期待响应。但是,如果您将“/ dev/null”与“-w”标志配对,则您将按所需的行为进行转换。换句话说,这里使用的是netcat的两种可能的方法:

# With bogus input 
echo x | nc www.example.com &> /dev/null/ 
# With null input 
nc -w1 www.example.com < /dev/null 
+0

以下我试过了你的两个命令,但是我每次都得到退出代码1。 – Rohlik

0

你可以用猛砸自己做到这一点,使用它的内置的/ dev/TCP设备文件。 如果一个端口关闭,以下将会抛出一个拒绝连接消息。

: </dev/tcp/remote.host.com/1284

可以编写脚本是这样的:在bash参考手册/dev/tcp

(: </dev/tcp/remote.host.com/1284) &>/dev/null && echo "OPEN" || echo "CLOSED"

详情:https://www.gnu.org/software/bash/manual/html_node/Redirections.html

+0

Thx为您的答复。我试过你的解决方案,但这个命令有很长的超时时间--2分钟。 – Rohlik

+0

是的,你可以在'timeout'命令之前使它更早完成。 – Zlemini