├── .coveragerc ├── .gitignore ├── .travis.yml ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── bastion_ssh.ini ├── bastion_ssh ├── __init__.py ├── argparser.py ├── bastionssh.py ├── config.py ├── context.py ├── errors.py ├── log.py ├── plugins │ ├── __init__.py │ ├── audit │ │ ├── __init__.py │ │ ├── main.py │ │ ├── screen.py │ │ └── stream.py │ └── ssh │ │ ├── __init__.py │ │ ├── main.py │ │ ├── ssh_filter.py │ │ └── ssh_transport.py └── utils.py ├── docs ├── Makefile ├── bastion_ssh.png ├── doc_requirements.txt ├── make.bat ├── screenshots.gif └── source │ ├── conf.py │ └── index.rst ├── requirements.txt ├── scripts └── ci │ ├── install.py │ ├── run-integ-tests.py │ └── run-tests.py ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── functional └── __init__.py ├── integration └── __init__.py └── unit ├── __init__.py └── test_utils.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | include = 4 | bastion_ssh/* 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .coverage 3 | MANIFEST 4 | coverage.xml 5 | nosetests.xml 6 | junit-report.xml 7 | pylint.txt 8 | toy.py 9 | tox.ini 10 | violations.pyflakes.txt 11 | cover/ 12 | build/ 13 | docs/_build 14 | requests.egg-info/ 15 | *.pyc 16 | *.swp 17 | *.egg 18 | env/ 19 | 20 | .workon 21 | 22 | t.py 23 | 24 | t2.py 25 | dist 26 | __pycache__/ 27 | *$py.class 28 | 29 | # PyCharm 30 | .idea/* 31 | 32 | # C extensions 33 | *.so 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .coverage.* 49 | .cache 50 | *,cover 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | 59 | # Sphinx documentation 60 | docs/_build/ 61 | 62 | # Distribution / packaging 63 | .Python 64 | develop-eggs/ 65 | downloads/ 66 | eggs/ 67 | .eggs/ 68 | lib/ 69 | lib64/ 70 | parts/ 71 | sdist/ 72 | var/ 73 | *.egg-info/ 74 | *~ 75 | .installed.cfg 76 | 77 | .hypothesis/ 78 | 79 | # PyBuilder 80 | target/ 81 | 82 | #Ipython Notebook 83 | .ipynb_checkpoints 84 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "2.7" 5 | 6 | sudo: false 7 | cache: 8 | pip: true 9 | 10 | before_install: 11 | - if [ "$TRAVIS_PULL_REQUEST" != "false" ] && [ "$TRAVIS_BRANCH" == "master" ]; then 12 | echo "No pull requests can be sent to the master branch" 1>&2; 13 | exit 1; 14 | fi 15 | install: 16 | - python scripts/ci/install.py 17 | script: python scripts/ci/run-tests.py 18 | after_success: 19 | - pip install python-coveralls && cd tests && coveralls 20 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | Release History 4 | --------------- 5 | 6 | 0.0.1 (2016-03-09) 7 | ++++++++++++++++++ 8 | 9 | * Frustration 10 | * Conception 11 | 12 | 0.0.2 (2016-03-15) 13 | ++++++++++++++++++ 14 | 15 | * Fix Bugs 16 | 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2016 wcc526 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include HISTORY.rst 3 | include LICENSE 4 | include requirements.txt 5 | recursive-include bastion_ssh * *.* 6 | recursive-exclude bastion_ssh *~ *.pyc 7 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | **************************************** 2 | Bastion SSH: Bastion host for SSH 3 | **************************************** 4 | 5 | Bastion SSH is designed for protecting,monitoring and accessing multiple SSH resources. 6 | 7 | ----- 8 | 9 | |pypiv| |pypidm| |doc| |codeclimate| |code_health| |build| |coverage| |gitter| 10 | 11 | ----- 12 | 13 | .. contents:: 14 | :local: 15 | :depth: 1 16 | :backlinks: none 17 | 18 | ============= 19 | Main Features 20 | ============= 21 | 22 | * Monitor user's input 23 | 24 | ============= 25 | ScreenShots 26 | ============= 27 | 28 | .. image:: https://raw.githubusercontent.com/wcc526/bastion-ssh/master/docs/screenshots.gif 29 | :alt: ScreenShots 30 | :width: 679 31 | :height: 781 32 | :align: center 33 | 34 | 35 | ============ 36 | Installation 37 | ============ 38 | 39 | To install Bastion SSH, simply: 40 | 41 | .. code-block:: bash 42 | 43 | $ pip install bastion_ssh 44 | 45 | ===== 46 | Usage 47 | ===== 48 | 49 | Hello World: 50 | 51 | .. code-block:: bash 52 | 53 | $ bastion_ssh.py -H 192.168.0.1 -u root 54 | 55 | 56 | .. |pypiv| image:: https://img.shields.io/pypi/v/bastion_ssh.svg 57 | :target: https://pypi.python.org/pypi/bastion_ssh 58 | :alt: Latest version released on PyPi 59 | 60 | .. |pypidm| image:: https://img.shields.io/pypi/dm/bastion_ssh.svg 61 | :target: https://pypi.python.org/pypi/bastion_ssh 62 | :alt: Latest version released on PyPi 63 | 64 | .. |coverage| image:: https://img.shields.io/coveralls/wcc526/bastion-ssh/master.svg 65 | :target: https://coveralls.io/r/wcc526/bastion-ssh?branch=master 66 | :alt: Test coverage 67 | 68 | .. |build| image:: https://travis-ci.org/wcc526/bastion-ssh.svg?branch=master 69 | :target: https://travis-ci.org/wcc526/bastion-ssh 70 | :alt: Build status of the master branch on Mac/Linux 71 | 72 | .. |gitter| image:: https://badges.gitter.im/wcc526/bastion-ssh.svg 73 | :target: https://gitter.im/wcc526/bastion-ssh 74 | :alt: Chat on Gitter 75 | 76 | .. |doc| image:: https://readthedocs.org/projects/bastion-ssh/badge/?version=latest 77 | :target: http://bastion-ssh.readthedocs.org/en/latest/?badge=latest 78 | :alt: Documentation Status 79 | 80 | .. |codeclimate| image:: https://codeclimate.com/github/wcc526/bastion-ssh/badges/gpa.svg 81 | :target: https://codeclimate.com/github/wcc526/bastion-ssh 82 | :alt: Code Climate 83 | 84 | .. |code_health| image:: https://landscape.io/github/wcc526/bastion-ssh/master/landscape.svg 85 | :target: https://landscape.io/github/wcc526/bastion-ssh/master 86 | :alt: Code Health 87 | -------------------------------------------------------------------------------- /bastion_ssh.ini: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Config data 3 | ############################################################################### 4 | [DEFAULT] 5 | debug = true 6 | -------------------------------------------------------------------------------- /bastion_ssh/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.0.3' 2 | -------------------------------------------------------------------------------- /bastion_ssh/argparser.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | 4 | 5 | class FromJSON(): 6 | def __init__(self, string): 7 | self.string = string 8 | 9 | def decode(self): 10 | return json.loads(self.string) 11 | 12 | 13 | def get_parser(): 14 | parser = argparse.ArgumentParser(description='bastion SSH host via the command line') 15 | parser.add_argument('--hostname', '-H', type=str, help='the hostname to connect') 16 | parser.add_argument('--username', '-u', type=str, help='the username to connect') 17 | parser.add_argument('--port', '-p', help='select port of ssh(default: 22)', default=22, type=int) 18 | parser.add_argument('-v', '--version', help='displays the current version of bastion ssh', 19 | action='store_true') 20 | return parser 21 | -------------------------------------------------------------------------------- /bastion_ssh/bastionssh.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | 5 | import logging 6 | 7 | LOG = logging.getLogger(__name__) 8 | 9 | from bastion_ssh.log import configure_logging 10 | from bastion_ssh.context import Context 11 | from bastion_ssh.plugins.audit.main import AuditCMDFilter 12 | from bastion_ssh.plugins.ssh.main import InteractiveShell 13 | from bastion_ssh.argparser import get_parser 14 | from bastion_ssh import __version__ 15 | import sys 16 | 17 | 18 | def command_line_runner(): 19 | parser = get_parser() 20 | args = vars(parser.parse_args()) 21 | 22 | if args['version']: 23 | print(__version__) 24 | return 25 | 26 | if len(sys.argv) == 1: 27 | parser.print_help() 28 | sys.exit(1) 29 | 30 | if args['hostname'] and args['username']: 31 | hostname = args['hostname'] 32 | username = args['username'] 33 | port = 22 34 | if args['port']: 35 | port = args['port'] 36 | context = Context(hostname=hostname, username=username, port=port) 37 | interactiveshell = InteractiveShell(context) 38 | 39 | auditcmdfilter = AuditCMDFilter(context) 40 | interactiveshell.attach(auditcmdfilter) 41 | 42 | interactiveshell.shell() 43 | 44 | 45 | if __name__ == '__main__': 46 | configure_logging() 47 | command_line_runner() 48 | -------------------------------------------------------------------------------- /bastion_ssh/config.py: -------------------------------------------------------------------------------- 1 | import glob 2 | from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError 3 | from os.path import expanduser 4 | 5 | 6 | class Config(object): 7 | """A ConfigParser wrapper to support defaults when calling instance 8 | methods, and also tied to a single section""" 9 | 10 | def __init__(self, section=None, values=None, extra_sources=()): 11 | if section is None: 12 | sources = self._getsources() 13 | self.cp = SafeConfigParser() 14 | self.cp.read(sources) 15 | for fp in extra_sources: 16 | self.cp.readfp(fp) 17 | else: 18 | self.cp = SafeConfigParser(values) 19 | self.cp.add_section(section) 20 | 21 | def _getsources(self): 22 | sources = [expanduser('~/.bastion_ssh.ini')] 23 | return sources 24 | 25 | def _getany(self, method, section, option, default): 26 | try: 27 | return method(section, option) 28 | except (NoSectionError, NoOptionError): 29 | if default is not None: 30 | return default 31 | raise 32 | 33 | def get(self, section, option, default=None): 34 | return self._getany(self.cp.get, section, option, default) 35 | 36 | def getint(self, section, option, default=None): 37 | return (int)(self._getany(self.cp.get, section, option, default)) 38 | 39 | def getfloat(self, section, option, default=None): 40 | return (float)(self._getany(self.cp.get, section, option, default)) 41 | 42 | def getboolean(self, section, option, default=None): 43 | return (bool)(self._getany(self.cp.get, section, option, default)) 44 | 45 | def items(self, section, default=None): 46 | try: 47 | return self.cp.items(section) 48 | except (NoSectionError, NoOptionError): 49 | if default is not None: 50 | return default 51 | raise 52 | -------------------------------------------------------------------------------- /bastion_ssh/context.py: -------------------------------------------------------------------------------- 1 | import getpass 2 | 3 | 4 | class Context(object): 5 | def __init__(self, hostname, username, port=22): 6 | self.hostname = hostname 7 | self.username = username 8 | self.port = port 9 | self.user = getpass.getuser() 10 | -------------------------------------------------------------------------------- /bastion_ssh/errors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | class ClientError(Exception): 5 | pass 6 | 7 | 8 | class ServerError(Exception): 9 | pass 10 | 11 | 12 | class BadParameter(RuntimeError): 13 | pass 14 | 15 | 16 | class DockerNotFound(RuntimeError): 17 | pass 18 | 19 | 20 | class PublicImageNotFound(RuntimeError): 21 | pass 22 | 23 | 24 | class StreamOutputError(Exception): 25 | pass 26 | 27 | 28 | class InternalError(RuntimeError): 29 | pass 30 | 31 | 32 | class ConnectionError(RuntimeError): 33 | pass 34 | 35 | 36 | class MissingAsset(RuntimeError): 37 | pass 38 | 39 | 40 | class NothingChanged(RuntimeError): 41 | pass 42 | -------------------------------------------------------------------------------- /bastion_ssh/log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | import logging 5 | import logging.handlers 6 | import os 7 | from logging.config import dictConfig 8 | 9 | default_formatter = logging.Formatter( 10 | "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s", 11 | "%d/%m/%Y %H:%M:%S") 12 | DEFAULT_LOGGING = { 13 | 'version': 1, 14 | 'disable_existing_loggers': False, 15 | 'loggers': { 16 | 'paramiko': { 17 | 'level': 'WARNING' 18 | } 19 | } 20 | } 21 | 22 | 23 | def configure_logging(): 24 | def_logpath = os.path.join(os.getenv('USERPROFILE') or os.getenv('HOME'), 'bastion_ssh.log') 25 | dictConfig(DEFAULT_LOGGING) 26 | file_handler = logging.handlers.RotatingFileHandler(def_logpath, maxBytes=10485760, backupCount=300, 27 | encoding='utf-8') 28 | file_handler.setLevel(logging.DEBUG) 29 | 30 | console_handler = logging.StreamHandler() 31 | console_handler.setLevel(logging.ERROR) 32 | 33 | # file_handler.setFormatter(default_formatter) 34 | console_handler.setFormatter(default_formatter) 35 | 36 | logging.root.setLevel(logging.DEBUG) 37 | logging.root.addHandler(file_handler) 38 | logging.root.addHandler(console_handler) 39 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/bastion_ssh/plugins/__init__.py -------------------------------------------------------------------------------- /bastion_ssh/plugins/audit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/bastion_ssh/plugins/audit/__init__.py -------------------------------------------------------------------------------- /bastion_ssh/plugins/audit/main.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import logging 3 | from bastion_ssh.plugins.ssh.ssh_filter import SSHFilter 4 | from bastion_ssh.utils import get_console_dimensions 5 | from bastion_ssh.plugins.audit.screen import BetterScreen 6 | from bastion_ssh.plugins.audit.stream import BetterStream 7 | import os 8 | 9 | LOG = logging.getLogger(__name__) 10 | 11 | 12 | class AuditCMDFilter(SSHFilter): 13 | def __init__(self, context): 14 | self.context = context 15 | self.stream = BetterStream() 16 | width, height = get_console_dimensions() 17 | self.screen = BetterScreen(columns=width, lines=height) 18 | self.stream.attach(self.screen) 19 | self.input_mode = False 20 | self.command_path = os.path.join(os.getenv('USERPROFILE') or os.getenv('HOME'), 'bastion_command.log') 21 | self.channel_path = os.path.join(os.getenv('USERPROFILE') or os.getenv('HOME'), 'bastion_channel.log') 22 | 23 | def before_channel(self, x): 24 | self.stream.feed(x) 25 | with open(self.channel_path, "ab+") as f: 26 | for line in self.screen.display: 27 | print(line, file=f) 28 | 29 | def before_stdin(self, x): 30 | self.input_mode = True 31 | if str(x) in ['\r', '\n', '\r\n']: 32 | with open(self.command_path, "ab+") as f: 33 | print(self.screen.get_command(), file=f) 34 | self.input_mode = False 35 | 36 | def when_resize(self): 37 | width, height = get_console_dimensions() 38 | self.screen.resize(columns=width, lines=height) 39 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/audit/screen.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from pyte.screens import Screen 3 | import operator 4 | import logging 5 | from bastion_ssh.utils import command_parser 6 | 7 | LOG = logging.getLogger(__name__) 8 | 9 | 10 | class BetterScreen(Screen): 11 | def __init__(self, columns, lines): 12 | super(BetterScreen, self).__init__(columns=columns, lines=lines) 13 | 14 | def get_command(self): 15 | command = None 16 | for line in reversed(self.buffer): 17 | x = "".join(map(operator.attrgetter("data"), line)).strip() 18 | if len(x) > 0: 19 | command = command_parser(x) 20 | if command is not None: 21 | break 22 | return command 23 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/audit/stream.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from pyte.streams import ByteStream 3 | import logging 4 | 5 | LOG = logging.getLogger(__name__) 6 | 7 | 8 | class BetterStream(ByteStream): 9 | def __init__(self): 10 | super(BetterStream, self).__init__() 11 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/ssh/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/bastion_ssh/plugins/ssh/__init__.py -------------------------------------------------------------------------------- /bastion_ssh/plugins/ssh/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | import os 4 | import sys 5 | import tty 6 | import select 7 | import signal 8 | import paramiko 9 | import termios 10 | import logging 11 | from bastion_ssh.plugins.ssh.ssh_transport import SSHTransport 12 | from bastion_ssh.utils import get_console_dimensions 13 | 14 | LOG = logging.getLogger(__name__) 15 | 16 | 17 | class InteractiveShell(object): 18 | def __init__(self, context, input=sys.stdin, output=sys.stdout): 19 | self.ssh_transport = SSHTransport(context=context) 20 | width, height = get_console_dimensions() 21 | self.channel = self.ssh_transport.transport.open_session() 22 | paramiko.agent.AgentRequestHandler(self.channel) 23 | self.channel.get_pty(term=os.getenv('TERM') or 'vt100', width=width, height=height) 24 | self.channel.invoke_shell() 25 | signal.signal(signal.SIGWINCH, self.sigwinch) 26 | self.input = input 27 | self.output = output 28 | self.listeners = [] 29 | 30 | def sigwinch(self, signal, data): 31 | # We do as little as possible when the WINCH occurs!! 32 | self.channel.resize_pty(*get_console_dimensions()) 33 | for listener in self.listeners: 34 | listener.when_resize() 35 | 36 | def process_channel(self, channel): 37 | """Process the given channel.""" 38 | if channel.closed: 39 | return False 40 | 41 | if channel.recv_ready(): 42 | try: 43 | data = channel.recv(4096) 44 | 45 | if not data: 46 | return False 47 | 48 | for listener in self.listeners: 49 | listener.before_channel(data) 50 | 51 | # self.audit_cmd.audit_channel(data) 52 | self.output.write(data) 53 | self.output.flush() 54 | 55 | except Exception: 56 | pass 57 | 58 | if channel.exit_status_ready(): 59 | return False 60 | 61 | return True 62 | 63 | def process_stdin(self, channel): 64 | """Read data from stdin and send it over the channel.""" 65 | try: 66 | buf = os.read(self.input.fileno(), 1) 67 | except OSError: 68 | buf = None 69 | if not buf: 70 | return False 71 | for listener in self.listeners: 72 | listener.before_stdin(buf) 73 | channel.send(buf) 74 | return True 75 | 76 | def handle_communications(self): 77 | while True: 78 | try: 79 | r, w, x = select.select([self.input, self.channel], [], [], 5) 80 | except Exception: 81 | pass 82 | 83 | if self.channel in r: 84 | if not self.process_channel(self.channel): 85 | break 86 | 87 | if self.input in r: 88 | if not self.process_stdin(self.channel): 89 | self.channel.shutdown_write() 90 | break 91 | 92 | def shell(self): 93 | """Open a shell.""" 94 | # Make sure we can restore the terminal to a working state after 95 | # interactive stuff is over 96 | oldtty = None 97 | try: 98 | oldtty = termios.tcgetattr(self.input.fileno()) 99 | 100 | # Set tty mode to raw - this is a bit dangerous because it stops 101 | # Ctrl+C working! But that is required so that you can Ctrl+C 102 | # remote things 103 | tty.setraw(self.input.fileno()) 104 | 105 | # For testing you could use cbreak mode - here Ctrl+C will kill the 106 | # local yaybu instance but otherwise is quite like raw mode 107 | # tty.setcbreak(self.input.fileno()) 108 | 109 | # We want non-blocking mode, otherwise session might hang 110 | # This might cause socket.timeout exceptions, which we just ignore 111 | # for read() operations 112 | self.channel.settimeout(0.0) 113 | 114 | self.handle_communications() 115 | except Exception, e: 116 | LOG.warn(e, exc_info=True) 117 | finally: 118 | if oldtty: 119 | termios.tcsetattr(self.input.fileno(), termios.TCSADRAIN, oldtty) 120 | self.channel.close() 121 | 122 | def attach(self, sshfilter): 123 | """Adds a given ssh filter to the listener queue. 124 | """ 125 | self.listeners.append(sshfilter) 126 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/ssh/ssh_filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | class SSHFilter(object): 5 | def before_stdin(self, command): 6 | pass 7 | 8 | def before_channel(self, command): 9 | pass 10 | 11 | def when_resize(self): 12 | pass 13 | -------------------------------------------------------------------------------- /bastion_ssh/plugins/ssh/ssh_transport.py: -------------------------------------------------------------------------------- 1 | import paramiko 2 | import socket 3 | import time 4 | import logging 5 | from paramiko.ssh_exception import SSHException 6 | import bastion_ssh.errors 7 | 8 | LOG = logging.getLogger(__name__) 9 | 10 | 11 | class SSHTransport(object): 12 | """ This object wraps a shell in yet another shell. When the shell is 13 | switched into "simulate" mode it can just print what would be done. """ 14 | 15 | def __init__(self, context): 16 | self.context = context 17 | self.connection_attempts = 20 18 | self.transport = None 19 | self.client = paramiko.SSHClient() 20 | self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 21 | for tries in range(self.connection_attempts): 22 | try: 23 | self.client.connect(hostname=self.context.hostname, 24 | username=self.context.username, 25 | port=self.context.port, 26 | allow_agent=True, 27 | look_for_keys=True) 28 | break 29 | except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException: 30 | LOG.warning("Unable to authenticate with remote server") 31 | raise bastion_ssh.errors.ConnectionError( 32 | "Unable to authenticate with remote server") 33 | except (socket.error, EOFError): 34 | LOG.warning("connection refused. retrying.") 35 | time.sleep(tries + 1) 36 | else: 37 | self.client.close() 38 | raise bastion_ssh.errors.ConnectionError( 39 | "Connection refused %d times, giving up." % self.connection_attempts) 40 | self.transport = self.client.get_transport() 41 | self.transport.set_keepalive(30) 42 | self.transport.use_compression(True) 43 | 44 | def __del__(self): 45 | self.client.close() 46 | -------------------------------------------------------------------------------- /bastion_ssh/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | import struct 4 | import fcntl 5 | import sys 6 | import termios 7 | import re 8 | 9 | 10 | def get_console_dimensions(): 11 | """ 12 | This function use to get the size of the windows! 13 | """ 14 | width, height = 80, 24 15 | try: 16 | fmt = 'HH' 17 | buffer = struct.pack(fmt, 0, 0) 18 | result = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, buffer) 19 | height, width = struct.unpack(fmt, result) 20 | except Exception, e: 21 | pass 22 | finally: 23 | return width, height 24 | 25 | 26 | def command_parser(ps1_command): 27 | """ 28 | :param ps1_command: which contain ps1. 29 | :return: user's input command 30 | """ 31 | ret = None 32 | ps1_pattern = re.compile('(\[.*@.*\][\$#])(.*)') 33 | match = ps1_pattern.search(ps1_command) 34 | if match: 35 | ret = match.group(2).strip() 36 | return ret 37 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/bastion_ssh.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/bastion_ssh.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/bastion_ssh" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/bastion_ssh" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/bastion_ssh.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/docs/bastion_ssh.png -------------------------------------------------------------------------------- /docs/doc_requirements.txt: -------------------------------------------------------------------------------- 1 | Sphinx==1.3.6 2 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | set I18NSPHINXOPTS=%SPHINXOPTS% source 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 1>NUL 2>NUL 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\bastion_ssh.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\bastion_ssh.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /docs/screenshots.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/docs/screenshots.gif -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # bastion_ssh documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Mar 16 16:43:28 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | import shlex 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | #sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # source_suffix = ['.rst', '.md'] 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'bastion_ssh' 50 | copyright = u'2016, wcc526' 51 | author = u'wcc526' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | # 57 | # The short X.Y version. 58 | version = u'0.0.2' 59 | # The full version, including alpha/beta/rc tags. 60 | release = u'0.0.2' 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # There are two options for replacing |today|: either, you set today to some 70 | # non-false value, then it is used: 71 | #today = '' 72 | # Else, today_fmt is used as the format for a strftime call. 73 | #today_fmt = '%B %d, %Y' 74 | 75 | # List of patterns, relative to source directory, that match files and 76 | # directories to ignore when looking for source files. 77 | exclude_patterns = [] 78 | 79 | # The reST default role (used for this markup: `text`) to use for all 80 | # documents. 81 | #default_role = None 82 | 83 | # If true, '()' will be appended to :func: etc. cross-reference text. 84 | #add_function_parentheses = True 85 | 86 | # If true, the current module name will be prepended to all description 87 | # unit titles (such as .. function::). 88 | #add_module_names = True 89 | 90 | # If true, sectionauthor and moduleauthor directives will be shown in the 91 | # output. They are ignored by default. 92 | #show_authors = False 93 | 94 | # The name of the Pygments (syntax highlighting) style to use. 95 | pygments_style = 'sphinx' 96 | 97 | # A list of ignored prefixes for module index sorting. 98 | #modindex_common_prefix = [] 99 | 100 | # If true, keep warnings as "system message" paragraphs in the built documents. 101 | #keep_warnings = False 102 | 103 | # If true, `todo` and `todoList` produce output, else they produce nothing. 104 | todo_include_todos = False 105 | 106 | 107 | # -- Options for HTML output ---------------------------------------------- 108 | 109 | # The theme to use for HTML and HTML Help pages. See the documentation for 110 | # a list of builtin themes. 111 | html_theme = 'alabaster' 112 | 113 | # Theme options are theme-specific and customize the look and feel of a theme 114 | # further. For a list of options available for each theme, see the 115 | # documentation. 116 | #html_theme_options = {} 117 | 118 | # Add any paths that contain custom themes here, relative to this directory. 119 | #html_theme_path = [] 120 | 121 | # The name for this set of Sphinx documents. If None, it defaults to 122 | # " v documentation". 123 | #html_title = None 124 | 125 | # A shorter title for the navigation bar. Default is the same as html_title. 126 | #html_short_title = None 127 | 128 | # The name of an image file (relative to this directory) to place at the top 129 | # of the sidebar. 130 | #html_logo = None 131 | 132 | # The name of an image file (within the static path) to use as favicon of the 133 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 134 | # pixels large. 135 | #html_favicon = None 136 | 137 | # Add any paths that contain custom static files (such as style sheets) here, 138 | # relative to this directory. They are copied after the builtin static files, 139 | # so a file named "default.css" will overwrite the builtin "default.css". 140 | html_static_path = ['_static'] 141 | 142 | # Add any extra paths that contain custom files (such as robots.txt or 143 | # .htaccess) here, relative to this directory. These files are copied 144 | # directly to the root of the documentation. 145 | #html_extra_path = [] 146 | 147 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 148 | # using the given strftime format. 149 | #html_last_updated_fmt = '%b %d, %Y' 150 | 151 | # If true, SmartyPants will be used to convert quotes and dashes to 152 | # typographically correct entities. 153 | #html_use_smartypants = True 154 | 155 | # Custom sidebar templates, maps document names to template names. 156 | #html_sidebars = {} 157 | 158 | # Additional templates that should be rendered to pages, maps page names to 159 | # template names. 160 | #html_additional_pages = {} 161 | 162 | # If false, no module index is generated. 163 | #html_domain_indices = True 164 | 165 | # If false, no index is generated. 166 | #html_use_index = True 167 | 168 | # If true, the index is split into individual pages for each letter. 169 | #html_split_index = False 170 | 171 | # If true, links to the reST sources are added to the pages. 172 | #html_show_sourcelink = True 173 | 174 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 175 | #html_show_sphinx = True 176 | 177 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 178 | #html_show_copyright = True 179 | 180 | # If true, an OpenSearch description file will be output, and all pages will 181 | # contain a tag referring to it. The value of this option must be the 182 | # base URL from which the finished HTML is served. 183 | #html_use_opensearch = '' 184 | 185 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 186 | #html_file_suffix = None 187 | 188 | # Language to be used for generating the HTML full-text search index. 189 | # Sphinx supports the following languages: 190 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 191 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 192 | #html_search_language = 'en' 193 | 194 | # A dictionary with options for the search language support, empty by default. 195 | # Now only 'ja' uses this config value 196 | #html_search_options = {'type': 'default'} 197 | 198 | # The name of a javascript file (relative to the configuration directory) that 199 | # implements a search results scorer. If empty, the default will be used. 200 | #html_search_scorer = 'scorer.js' 201 | 202 | # Output file base name for HTML help builder. 203 | htmlhelp_basename = 'bastion_sshdoc' 204 | 205 | # -- Options for LaTeX output --------------------------------------------- 206 | 207 | latex_elements = { 208 | # The paper size ('letterpaper' or 'a4paper'). 209 | #'papersize': 'letterpaper', 210 | 211 | # The font size ('10pt', '11pt' or '12pt'). 212 | #'pointsize': '10pt', 213 | 214 | # Additional stuff for the LaTeX preamble. 215 | #'preamble': '', 216 | 217 | # Latex figure (float) alignment 218 | #'figure_align': 'htbp', 219 | } 220 | 221 | # Grouping the document tree into LaTeX files. List of tuples 222 | # (source start file, target name, title, 223 | # author, documentclass [howto, manual, or own class]). 224 | latex_documents = [ 225 | (master_doc, 'bastion_ssh.tex', u'bastion\\_ssh Documentation', 226 | u'wcc526', 'manual'), 227 | ] 228 | 229 | # The name of an image file (relative to this directory) to place at the top of 230 | # the title page. 231 | #latex_logo = None 232 | 233 | # For "manual" documents, if this is true, then toplevel headings are parts, 234 | # not chapters. 235 | #latex_use_parts = False 236 | 237 | # If true, show page references after internal links. 238 | #latex_show_pagerefs = False 239 | 240 | # If true, show URL addresses after external links. 241 | #latex_show_urls = False 242 | 243 | # Documents to append as an appendix to all manuals. 244 | #latex_appendices = [] 245 | 246 | # If false, no module index is generated. 247 | #latex_domain_indices = True 248 | 249 | 250 | # -- Options for manual page output --------------------------------------- 251 | 252 | # One entry per manual page. List of tuples 253 | # (source start file, name, description, authors, manual section). 254 | man_pages = [ 255 | (master_doc, 'bastion_ssh', u'bastion_ssh Documentation', 256 | [author], 1) 257 | ] 258 | 259 | # If true, show URL addresses after external links. 260 | #man_show_urls = False 261 | 262 | 263 | # -- Options for Texinfo output ------------------------------------------- 264 | 265 | # Grouping the document tree into Texinfo files. List of tuples 266 | # (source start file, target name, title, author, 267 | # dir menu entry, description, category) 268 | texinfo_documents = [ 269 | (master_doc, 'bastion_ssh', u'bastion_ssh Documentation', 270 | author, 'bastion_ssh', 'One line description of project.', 271 | 'Miscellaneous'), 272 | ] 273 | 274 | # Documents to append as an appendix to all manuals. 275 | #texinfo_appendices = [] 276 | 277 | # If false, no module index is generated. 278 | #texinfo_domain_indices = True 279 | 280 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 281 | #texinfo_show_urls = 'footnote' 282 | 283 | # If true, do not generate a @detailmenu in the "Top" node's menu. 284 | #texinfo_no_detailmenu = False 285 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. bastion_ssh documentation master file, created by 2 | sphinx-quickstart on Wed Mar 16 16:43:28 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to bastion_ssh's documentation! 7 | ======================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ecdsa==0.13 2 | paramiko==1.16.0 3 | pycrypto==2.6.1 4 | pyte==0.5.2 5 | wcwidth==0.1.6 6 | wheel==0.24.0 7 | -------------------------------------------------------------------------------- /scripts/ci/install.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | from subprocess import check_call 5 | import shutil 6 | 7 | _dname = os.path.dirname 8 | 9 | REPO_ROOT = _dname(_dname(_dname(os.path.abspath(__file__)))) 10 | os.chdir(REPO_ROOT) 11 | 12 | 13 | def run(command): 14 | return check_call(command, shell=True) 15 | 16 | try: 17 | # Has the form "major.minor" 18 | python_version = os.environ['PYTHON_VERSION'] 19 | except KeyError: 20 | python_version = '.'.join([str(i) for i in sys.version_info[:2]]) 21 | 22 | run('pip install -r requirements.txt') 23 | run('pip install coverage') 24 | if os.path.isdir('dist') and os.listdir('dist'): 25 | shutil.rmtree('dist') 26 | run('python setup.py bdist_wheel') 27 | wheel_dist = os.listdir('dist')[0] 28 | run('pip install %s' % (os.path.join('dist', wheel_dist))) 29 | -------------------------------------------------------------------------------- /scripts/ci/run-integ-tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Don't run tests from the root repo dir. 3 | # We want to ensure we're importing from the installed 4 | # binary package not from the CWD. 5 | 6 | import os 7 | from subprocess import check_call 8 | 9 | _dname = os.path.dirname 10 | 11 | REPO_ROOT = _dname(_dname(_dname(os.path.abspath(__file__)))) 12 | os.chdir(os.path.join(REPO_ROOT, 'tests')) 13 | 14 | 15 | def run(command): 16 | return check_call(command, shell=True) 17 | 18 | run('nosetests --with-xunit --cover-erase --with-coverage ' 19 | '--cover-package bastion_ssh --cover-xml -v integration') 20 | -------------------------------------------------------------------------------- /scripts/ci/run-tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Don't run tests from the root repo dir. 3 | # We want to ensure we're importing from the installed 4 | # binary package not from the CWD. 5 | 6 | import os 7 | from subprocess import check_call 8 | 9 | _dname = os.path.dirname 10 | 11 | REPO_ROOT = _dname(_dname(_dname(os.path.abspath(__file__)))) 12 | os.chdir(os.path.join(REPO_ROOT, 'tests')) 13 | 14 | 15 | def run(command): 16 | return check_call(command, shell=True) 17 | 18 | 19 | run('nosetests --with-coverage --cover-erase --cover-package bastion_ssh ' 20 | '--with-xunit --cover-xml -v unit/ functional/') 21 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import re 5 | import sys 6 | from pip.req import parse_requirements 7 | 8 | from codecs import open 9 | 10 | try: 11 | from setuptools import setup 12 | except ImportError: 13 | from distutils.core import setup 14 | 15 | if sys.argv[-1] == 'publish': 16 | os.system('python setup.py sdist bdist_wheel upload') 17 | sys.exit() 18 | 19 | packages = [ 20 | 'bastion_ssh', 21 | 'bastion_ssh.plugins', 22 | 'bastion_ssh.plugins.audit', 23 | 'bastion_ssh.plugins.ssh', 24 | ] 25 | 26 | install_reqs = parse_requirements('requirements.txt', session=False) 27 | requires = [str(ir.req) for ir in install_reqs] 28 | 29 | version = '' 30 | with open('bastion_ssh/__init__.py', 'r') as fd: 31 | version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', 32 | fd.read(), re.MULTILINE).group(1) 33 | 34 | if not version: 35 | raise RuntimeError('Cannot find version information') 36 | 37 | with open('README.rst', 'r', 'utf-8') as f: 38 | readme = f.read() 39 | with open('HISTORY.rst', 'r', 'utf-8') as f: 40 | history = f.read() 41 | 42 | setup( 43 | name='bastion_ssh', 44 | version=version, 45 | keywords=('bastion', 'bastion host for ssh'), 46 | description='bastion host for ssh.', 47 | long_description=readme + '\n\n' + history, 48 | author='wcc526', 49 | author_email='949409306@qq.com', 50 | url='http://www.python.org', 51 | packages=packages, 52 | package_data={'': ['LICENSE','requirements.txt'], 'bastion_ssh': ['*.pem']}, 53 | include_package_data=True, 54 | install_requires=requires, 55 | license='Apache 2.0', 56 | zip_safe=False, 57 | scripts=[ 58 | 'bastion_ssh/bastionssh.py' 59 | ], 60 | classifiers=( 61 | 'Development Status :: 5 - Production/Stable', 62 | 'Intended Audience :: Developers', 63 | 'Natural Language :: English', 64 | 'License :: OSI Approved :: Apache Software License', 65 | 'Programming Language :: Python :: 2.7', 66 | ), 67 | extras_require={ 68 | }, 69 | ) 70 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/tests/__init__.py -------------------------------------------------------------------------------- /tests/functional/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/tests/functional/__init__.py -------------------------------------------------------------------------------- /tests/integration/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/tests/integration/__init__.py -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wcc526/bastion-ssh/15211937c706ff970588ccdc99dec6bc660a4077/tests/unit/__init__.py -------------------------------------------------------------------------------- /tests/unit/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from bastion_ssh.utils import command_parser 3 | 4 | class TestCommandParser(unittest.TestCase): 5 | def test_genernal_command_parser(self): 6 | ps1_command = "0;vagrant@cyberivy-test-dev002-shjj:~[vagrant@cyberivy-test-dev002-shjj ~]$ ls" 7 | self.assertEquals(command_parser(ps1_command), "ls") 8 | 9 | def test_special_command_parser(self): 10 | ps1_command = "[vagrant@cyberivy-test-dev002-shjj ~]$ cd" 11 | self.assertEquals(command_parser(ps1_command), "cd") 12 | 13 | def test_genernal_space_command_parser(self): 14 | ps1_command = "0;vagrant@cyberivy-test-dev002-shjj:~[vagrant@cyberivy-test-dev002-shjj ~]$ cat 1.txt >> 2.txt" 15 | self.assertEquals(command_parser(ps1_command), "cat 1.txt >> 2.txt") 16 | 17 | def test_null_command_parser(self): 18 | ps1_command = "0;vagrant@cyberivy-test-dev002-shjj:~[vagrant@cyberivy-test-dev002-shjj ~]$" 19 | self.assertEquals(command_parser(ps1_command), "") 20 | 21 | def test_special_space_command_parser(self): 22 | ps1_command = "[vagrant@cyberivy-test-dev002-shjj ~]$ cd /var/tmp && dd" 23 | self.assertEquals(command_parser(ps1_command), "cd /var/tmp && dd") 24 | 25 | def test_not_special_space_command_parser(self): 26 | ps1_command = "[vagrant ~]$ cd /var/tmp && dd" 27 | self.assertEquals(command_parser(ps1_command), None) --------------------------------------------------------------------------------