|
| 1 | +# This file is part of ssh2-python. |
| 2 | +# Copyright (C) 2017 Panos Kittenis |
| 3 | + |
| 4 | +# This library is free software; you can redistribute it and/or |
| 5 | +# modify it under the terms of the GNU Lesser General Public |
| 6 | +# License as published by the Free Software Foundation, version 2.1. |
| 7 | + |
| 8 | +# This library is distributed in the hope that it will be useful, |
| 9 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 | +# Lesser General Public License for more details. |
| 12 | + |
| 13 | +# You should have received a copy of the GNU Lesser General Public |
| 14 | +# License along with this library; if not, write to the Free Software |
| 15 | +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 16 | + |
| 17 | +import os |
| 18 | +import socket |
| 19 | + |
| 20 | +from subprocess import Popen |
| 21 | +from time import sleep |
| 22 | + |
| 23 | + |
| 24 | +SERVER_KEY = os.path.sep.join([os.path.dirname(__file__), 'rsa.key']) |
| 25 | +SSHD_CONFIG = os.path.sep.join([os.path.dirname(__file__), 'sshd_config']) |
| 26 | + |
| 27 | +class OpenSSHServer(object): |
| 28 | + |
| 29 | + def __init__(self, port=2222): |
| 30 | + self.port = port |
| 31 | + self.server_proc = None |
| 32 | + |
| 33 | + def start_server(self): |
| 34 | + cmd = ['/usr/sbin/sshd', '-q', '-D', '-p', str(self.port), |
| 35 | + '-h', SERVER_KEY, '-f', SSHD_CONFIG] |
| 36 | + server = Popen(cmd) |
| 37 | + self.server_proc = server |
| 38 | + self._wait_for_port() |
| 39 | + |
| 40 | + def _wait_for_port(self): |
| 41 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 42 | + while sock.connect_ex(('127.0.0.1', self.port)) != 0: |
| 43 | + sleep(.1) |
| 44 | + del sock |
| 45 | + |
| 46 | + def stop(self): |
| 47 | + if self.server_proc is not None and self.server_proc.returncode is None: |
| 48 | + self.server_proc.terminate() |
| 49 | + self.server_proc.wait() |
| 50 | + |
| 51 | + def __del__(self): |
| 52 | + self.stop() |
0 commit comments