monkey/chaos_monkey/network/tools.py

53 lines
1.1 KiB
Python
Raw Normal View History

import socket
import select
2015-10-08 18:30:36 +08:00
import logging
2015-09-30 20:05:30 +08:00
DEFAULT_TIMEOUT = 10
BANNER_READ = 1024
2015-10-08 18:30:36 +08:00
LOG = logging.getLogger(__name__)
2015-11-30 16:56:20 +08:00
def check_port_tcp(ip, port, timeout=DEFAULT_TIMEOUT, get_banner=False):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
sock.connect((ip, port))
2015-10-08 18:30:36 +08:00
except socket.timeout:
2015-11-30 16:56:20 +08:00
return False, None
2015-10-08 18:30:36 +08:00
except socket.error, exc:
LOG.debug("Check port: %s:%s, Exception: %s", ip, port, exc)
2015-11-30 16:56:20 +08:00
return False, None
banner = None
try:
if get_banner:
read_ready, _, _ = select.select([sock], [], [], timeout)
if len(read_ready) > 0:
banner = sock.recv(BANNER_READ)
except:
pass
sock.close()
2015-11-30 16:56:20 +08:00
return True, banner
def check_port_udp(ip, port, timeout=DEFAULT_TIMEOUT):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
data = None
is_open = False
try:
sock.sendto("-", (ip, port))
data, _ = sock.recvfrom(BANNER_READ)
is_open = True
except:
pass
sock.close()
2015-11-30 16:56:20 +08:00
return is_open, data