This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
misc-csiraut/entrouvert-remotes/test_connections.py

102 lines
3.4 KiB
Python
Executable File

#!/usr/bin/python2
# hobo - portal to configure and deploy applications
# Copyright (C) 2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import errno
import json
import socket
import sys
from urlparse import urlparse
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def ad_argument(self, parser):
parser.add_argument('json_filename', type=str)
def handle(self, json_filename, verbosity=0, *args, **kwargs):
cache = {}
if json_filename == '-':
entries = json.load(sys.stdin)
else:
entries = json.load(open(json_filename))
for tenant, addresses in entries.iteritems():
for entry in addresses:
if entry in cache.keys():
# return cache.get(entry)
continue
if verbosity > 0:
print("testing %s %s" % (tenant, entry))
host, port, scheme = self.parse_entry(entry)
rs = self.netcat(host, port)
cache[entry] = rs
if not rs:
print("Failed: %s (%s:%s %s) %s" % (tenant, host, port, scheme, rs))
def netcat(self, host, port, content=''):
def connect(host, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((host, int(port)))
s.sendall(content.encode())
s.shutdown(socket.SHUT_WR)
while True:
try:
data = s.recv(4096)
if not data:
break
# print(repr(data))
except socket.error as e:
if e.errno != errno.ECONNRESET:
raise
s.close()
try:
connect(host, port, content)
return True
# python3
# except socket.ConnectionResetError:
# return True
# except socket.ConnectionRefusedError:
# return False
except socket.timeout:
return False
except socket.gaierror:
return False
except socket.error:
return False
def parse_entry(self, entry):
parsed = urlparse(entry)
try:
host, port = parsed.netloc.split(':')
port = int(port)
except ValueError:
host, port = parsed.netloc, 443
if parsed.scheme == 'ldap':
port = 389
if parsed.scheme == 'ldaps':
port = 636
if parsed.scheme == 'http':
port = 80
if '@' in host:
host = host.split('@')[-1]
return host, port, parsed.scheme
command = Command()
command.handle(sys.argv[1])