网络 - 测试连接性 [Python 或 C]
假设我想检查一下我的FTP服务器是否在线,我该怎么在程序里实现呢?你觉得最简单、最不打扰的方法是什么?
2 个回答
2
我个人会先试试 nmap 来完成这个任务,http://nmap.org。
nmap $HOSTNAME -p 21
在 Python 中测试一系列服务器的 21 号端口(ftp)可能会像这样:
#!/usr/bin/env python
from socket import *
host_list=['localhost', 'stackoverflow.com']
port=21 # (FTP port)
def test_port(ip_address, port, timeout=3):
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(timeout)
result = s.connect_ex((ip_address, port))
s.close()
if(result == 0):
return True
else:
return False
for host in host_list:
if test_port(gethostbyname(host), port):
print 'Successfully connected to',
else:
print 'Failed to connect to',
print '%s on port %d' % (host, port)
1