Python paramiko.SFTPServer() Examples

The following are 13 code examples of paramiko.SFTPServer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko , or try the search function .
Example #1
Source File: __init__.py    From pub with GNU General Public License v2.0 7 votes vote down vote up
def start_server(host, port, keyfile, level):
    paramiko_level = getattr(paramiko.common, level)
    paramiko.common.logging.basicConfig(level=paramiko_level)


    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    server_socket.bind((host, port))
    server_socket.listen(BACKLOG)
    print host,port
    while True:
        conn, addr = server_socket.accept()

        host_key = paramiko.RSAKey.from_private_key_file(keyfile)
        transport = paramiko.Transport(conn)
        transport.add_server_key(host_key)
        transport.set_subsystem_handler(
            'sftp', paramiko.SFTPServer, StubSFTPServer)

        server = StubServer()
        transport.start_server(server=server)

        channel = transport.accept()
        while transport.is_active():
            time.sleep(1) 
Example #2
Source File: test_sftpclone.py    From sftpclone with MIT License 7 votes vote down vote up
def _start_sftp_server():
    """Start the SFTP local server."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setblocking(False)
    sock.bind(('localhost', 2222))
    sock.listen(10)

    reads = {sock}
    others = set()

    while not event.is_set():
        ready_to_read, _, _ = select.select(reads, others, others, 1)

        if sock in ready_to_read:
            client_socket, address = sock.accept()
            ts = paramiko.Transport(client_socket)

            host_key = paramiko.RSAKey.from_private_key_file(t_path('server_id_rsa'))
            ts.add_server_key(host_key)
            server = StubServer()
            ts.set_subsystem_handler('sftp', paramiko.SFTPServer, StubSFTPServer)
            ts.start_server(server=server)

    sock.close() 
Example #3
Source File: test_sftp.py    From python-hpedockerplugin with Apache License 2.0 6 votes vote down vote up
def init_loopback():
        global sftp, tc

        socks = LoopSocket()
        sockc = LoopSocket()
        sockc.link(socks)
        tc = paramiko.Transport(sockc)
        ts = paramiko.Transport(socks)

        host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key'))
        ts.add_server_key(host_key)
        event = threading.Event()
        server = StubServer()
        ts.set_subsystem_handler('sftp', paramiko.SFTPServer, StubSFTPServer)
        ts.start_server(event, server)
        tc.connect(username='slowdive', password='pygmalion')
        event.wait(1.0)

        sftp = paramiko.SFTP.from_transport(tc) 
Example #4
Source File: test_server_proxy.py    From pysftpserver with MIT License 5 votes vote down vote up
def _start_sftp_server():
    """Start the SFTP local server."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setblocking(0)
    sock.bind(('localhost', 2223))
    sock.listen(10)

    reads = {sock}
    others = set()

    while not event.is_set():
        ready_to_read, _, _ = \
            select.select(
                reads,
                others,
                others,
                1)

        if sock in ready_to_read:
            client_socket, address = sock.accept()
            ts = paramiko.Transport(client_socket)

            host_key = paramiko.RSAKey.from_private_key_file(
                t_path('server_id_rsa')
            )
            ts.add_server_key(host_key)
            server = StubServer()
            ts.set_subsystem_handler(
                'sftp', paramiko.SFTPServer, StubSFTPServer)
            ts.start_server(server=server)

    sock.close() 
Example #5
Source File: test_server_proxy.py    From pysftpserver with MIT License 5 votes vote down vote up
def setUp(self):
        """Before running each test, create a server instance and create the required directories."""
        self.server = SFTPServer(
            SFTPServerProxyStorage(
                "test:secret@localhost",
                port=2223
            ),
            logfile=t_path('log'),
            raise_on_error=True
        ) 
Example #6
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def symlink(self, src, dest):
        try:
            os.symlink(src, dest)
        except OSError as e:
            return SFTPServer.convert_errno(e.errno)

        return paramiko.SFTP_OK 
Example #7
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def remove(self, path):
        try:
            os.remove(path)
        except OSError as e:
            return SFTPServer.convert_errno(e.errno)

        return paramiko.SFTP_OK 
Example #8
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def mkdir(self, path, attrs):
        mode = getattr(attrs, 'st_mode', 0o777)
        try:
            os.mkdir(path, mode)
        except OSError as e:
            return SFTPServer.convert_errno(e.errno)

        return paramiko.SFTP_OK 
Example #9
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def rmdir(self, path):
        try:
            os.rmdir(path)
        except OSError as e:
            return SFTPServer.convert_errno(e.errno)

        return paramiko.SFTP_OK 
Example #10
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def chattr(self, path, attrs):
        if attrs.st_mode is not None:
            try:
                os.chmod(path, attrs.st_mode)
            except OSError as e:
                return SFTPServer.convert_errno(e.errno)

        if attrs.st_uid is not None:
            try:
                os.chown(path, attrs.st_uid, attrs.st_gid)
            except OSError as e:
                return SFTPServer.convert_errno(e.errno)

        return paramiko.SFTP_OK 
Example #11
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def list_folder(self, path):
        """Looks up folder contents of `path.`"""
        # Inspired by https://github.com/rspivak/sftpserver/blob/0.3/src/sftpserver/stub_sftp.py#L70
        try:
            folder_contents = []
            for f in os.listdir(path):
                attr = paramiko.SFTPAttributes.from_stat(os.stat(os.path.join(path, f)))
                attr.filename = f
                folder_contents.append(attr)
            return folder_contents
        except OSError as e:
            return SFTPServer.convert_errno(e.errno) 
Example #12
Source File: sftp.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def __init__(self, channel, name, server, sftp_si=SFTPServerInterface,
                 *largs, **kwargs):
        kwargs["sftp_si"] = SFTPServerInterface
        super(SFTPServer, self).__init__(channel, name, server, *largs,
                                         **kwargs) 
Example #13
Source File: __init__.py    From pyrexecd with MIT License 4 votes vote down vote up
def run_server(app, sock, hostkeys, username, pubkeys, homedir, cmdexe,
               msg='Listening...'):
    def update_text(n):
        if n:
            app.set_text(msg + '\n(Clients: %d)' % n)
        else:
            app.set_text(msg)
        return
    update_text(0)
    sessions = []
    while app.idle():
        for session in sessions[:]:
            session.idle()
            ev = session.get_event()
            if ev == 'open':
                update_text(len(sessions))
                app.show_balloon('Connected', session.get_name())
                app.set_busy(True)
            elif ev == 'closing':
                session.close()
                sessions.remove(session)
                update_text(len(sessions))
                app.show_balloon('Disconnected', session.get_name())
                if not sessions:
                    app.set_busy(False)
            elif ev == 'timeout':
                sessions.remove(session)
        try:
            (conn, peer) = sock.accept()
        except socket.timeout:
            continue
        conn.settimeout(0.05)
        logging.info('Connected: addr=%r, port=%r' % peer)
        t = paramiko.Transport(conn)
        t.load_server_moduli()
        #t.set_subsystem_handler('sftp', paramiko.SFTPServer)
        for k in hostkeys:
            t.add_server_key(k)
        name = 'Session-%s-%s' % peer
        server = PyRexecServer(username, pubkeys)
        try:
            t.start_server(server=server)
            chan = t.accept(10)
            if chan is not None:
                session = PyRexecSession(app, name, chan, homedir, cmdexe, server)
                sessions.append(session)
            else:
                logging.error('Timeout')
                t.close()
        except Exception as e:
            logging.error('Error: %r' % e)
            t.close()
    while sessions:
        session = sessions.pop()
        session.close()
    return

# main