Skip to content

Commit

Permalink
Fix remove hostname validation (#267)
Browse files Browse the repository at this point in the history
* Fix remove hostname validation

* Change cleaned up ping call

* Add ping tests
  • Loading branch information
johnfzc authored and jathanism committed Apr 17, 2016
1 parent cbd52f6 commit 5f1f4cf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
6 changes: 6 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import datetime
from pytz import timezone
from trigger.utils import cli
from trigger.utils.network import ping


def test_pretty_time():
Expand All @@ -10,3 +11,8 @@ def test_pretty_time():
tomorrow = now + datetime.timedelta(days=1)
pretty = cli.pretty_time(tomorrow)
assert 'tomorrow' in pretty

def test_ping():
"""Validate network.ping functionality"""
assert ping("localhost")
assert not ping("unresolvable_test_host")
21 changes: 12 additions & 9 deletions trigger/utils/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,14 @@
__email__ = 'jathan.mccollum@teamaol.com'
__copyright__ = 'Copyright 2009-2013, AOL Inc.; 2013-2014 Salesforce.com'

import commands
import os
import subprocess
import shlex
import re
import socket
import telnetlib
from trigger.conf import settings


VALID_HOST_RE = re.compile("^[a-z0-9\-\.]+$")


# Exports
__all__ = ('ping', 'test_tcp_port', 'test_ssh', 'address_is_internal')

Expand All @@ -43,17 +41,20 @@ def ping(host, count=1, timeout=5):
>>> network.ping('192.168.199.253')
False
"""
# Make the command silent even for bad input
if not VALID_HOST_RE.findall(host):
return False

ping_command = "ping -q -c%d -W%d %s" % (count, timeout, host)
status, results = commands.getstatusoutput(ping_command)
DEVNULL = open(os.devnull, 'w')
status = subprocess.call(
shlex.split(ping_command),
stdout=DEVNULL,
stderr=DEVNULL,
close_fds=True)

# Linux RC: 0 = success, 256 = failure, 512 = unknown host
# Darwin RC: 0 = success, 512 = failure, 17408 = unknown host
return status == 0


def test_tcp_port(host, port=23, timeout=5, check_result=False,
expected_result=''):
"""
Expand Down Expand Up @@ -94,6 +95,7 @@ def test_tcp_port(host, port=23, timeout=5, check_result=False,
t.close()
return True


def test_ssh(host, port=22, timeout=5, version=('SSH-1.99', 'SSH-2.0')):
"""
Connect to a TCP port and confirm the SSH version. Defaults to SSHv2.
Expand Down Expand Up @@ -122,6 +124,7 @@ def test_ssh(host, port=22, timeout=5, version=('SSH-1.99', 'SSH-2.0')):
return test_tcp_port(host, port, timeout, check_result=True,
expected_result=version)


def address_is_internal(ip):
"""
Determines if an IP address is internal to your network. Relies on
Expand Down

0 comments on commit 5f1f4cf

Please sign in to comment.