Skip to content

Instantly share code, notes, and snippets.

@otherwiseguy
Last active May 19, 2017 00:41
Show Gist options
  • Save otherwiseguy/d8d8e8d11d4e16cc5cbb7626e69c9354 to your computer and use it in GitHub Desktop.
Save otherwiseguy/d8d8e8d11d4e16cc5cbb7626e69c9354 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import abc
import subprocess
import six
from six.moves import urllib
from six.moves import input
class ProtocolRegistry(type):
registry = {}
scheme = None
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, name, bases, class_dict)
if cls.scheme:
ProtocolRegistry.registry[cls.scheme] = cls
return cls
@six.add_metaclass(ProtocolRegistry)
@six.add_metaclass(abc.ABCMeta)
class Protocol(object):
def __init__(self, url):
self.url = url
@abc.abstractproperty
def cli(self):
"""Array of CLI arguments to pass to execute()"""
@staticmethod
def from_url(url):
p = urllib.parse.urlparse(url)
cls = Protocol.registry[p.scheme]
return cls(p)
def execute(self):
return subprocess.call(str(a) for a in self.cli)
class Telnet(Protocol):
scheme = 'telnet'
@property
def cli(self):
return ('telnet', self.url.hostname, self.url.port or '23')
class Gopher(Protocol):
scheme = 'gopher'
@property
def cli(self):
return ('gopher', self.url.geturl())
if __name__ == '__main__':
import logging
import sys
logging.basicConfig()
LOG = logging.getLogger(__name__)
try:
Protocol.from_url(sys.argv[1]).execute()
except Exception as e:
LOG.exception(e)
input("Press Enter to continue...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment