Commit 542cef51 authored by Antoine Millet's avatar Antoine Millet
Browse files

Added examples

parent 4f5e7141
Loading
Loading
Loading
Loading
+55 −0
Original line number Diff line number Diff line
#!/usr/bin/env python

'''
sjRpc client example.
'''

from __future__ import absolute_import

import sys
import threading
import time

from sjrpc.core import RpcConnection
from sjrpc.core.protocols import TunnelProtocol

bytes_received = 0

def perf(socket):
    global bytes_received
    while True:
        read = socket.recv(1024 * 1024)
        bytes_received += len(read)

# Get arguments from the command line:
if len(sys.argv) < 3:
    print 'Usage: %s <listening address> <listening port>' % sys.argv[0]
    sys.exit(2)
address = sys.argv[1]
port = int(sys.argv[2])

# Create the rpc connection:
conn = RpcConnection.from_addr_ssl(address, port)

print 'connected.'

# Run the connection mainloop in another thread:
threading.Thread(target=conn.run).start()
time.sleep(0.1)

label = conn.call('launch_perf')
tun = conn.register_protocol(label, TunnelProtocol)
t = threading.Thread(target=perf, args=(tun._socket,))
t.daemon = True
t.start()

last = 0
while True:
    bytes_received, b = 0, bytes_received
    bw = ((b / 1024.0 / 1024) / 2)
    print '%.2f MB/s\t\t\t%.2f Mb/s\t\t\tDelta: %+0.2f' % (bw, bw * 8, (bw - last) * 8)
    last = bw
    time.sleep(2)

conn.shutdown()
+105 −0
Original line number Diff line number Diff line
#!/usr/bin/env python

'''
sjRpc client example.
'''

from __future__ import absolute_import

import sys
import threading
import logging
import time
import fcntl
import os
import tty

from sjrpc.core import RpcConnection
from sjrpc.core.protocols import TunnelProtocol


#logger = logging.getLogger()
#logger.setLevel(logging.DEBUG)
#fmt = logging.Formatter('%(levelname)s %(name)s %(message)s')
#handler = logging.StreamHandler()
#handler.setFormatter(fmt)
#logger.addHandler(handler)

def iperf(socket):
    f = open('/dev/null', 'w')
    while True:
        read = socket.recv(1024 * 64)
        f.write(read)


class _FakeStdio(object):

    '''
    A fake standard io to make stdin/stdout look like a socket.
    '''

    def __init__(self):
        tty.setraw(sys.stdin.fileno())

    def recv(self, size):
        return sys.stdin.read(size)

    def send(self, data):
        sys.stdout.write(data)
        sys.stdout.flush()
        return len(data)

    def fileno(self):
        return sys.stdin.fileno()

    def setblocking(self, blocking):
        if not blocking:
            # Disable blocking mode on stdin:
            current_flags = fcntl.fcntl(sys.stdin, fcntl.F_GETFL)
            fcntl.fcntl(sys.stdin, fcntl.F_SETFL, current_flags | os.O_NONBLOCK)
        else:
            raise NotImplementedError('Not implemented')

# Get arguments from the command line:
if len(sys.argv) < 3:
    print 'Usage: %s <listening address> <listening port>' % sys.argv[0]
    sys.exit(2)
address = sys.argv[1]
port = int(sys.argv[2])

# Create the rpc connection:
conn = RpcConnection.from_addr(address, port)

print 'connected.'

# Run the connection mainloop in another thread:
threading.Thread(target=conn.run).start()
time.sleep(0.1)

# Create the tunnel on the remote server:
label = conn.call('launch_remote_console')

# Create a fake socket object wrapping stdin and stdout:
fake_stdio = _FakeStdio()

# Create the tunnel on the local side:
conn.register_protocol(label, TunnelProtocol, endpoint=fake_stdio)

#label = conn.call('iperf')
#tun = conn.register_protocol(label, TunnelProtocol)
#t = threading.Thread(target=iperf, args=(tun._socket,))
#t.daemon = True
#t.start()

#f = open('/dev/null', 'w')
#while True:
#    read = tun._socket.recv(1024 * 64)
#    f.write(read)

# Start the shell

rcode = conn.call('wait_for_pshell', _timeout=None)
print '\nremote process returned with code %s\n' % rcode

conn.shutdown()
+50 −0
Original line number Diff line number Diff line
#!/usr/bin/env python

'''
sjRpc client example.
'''

from __future__ import absolute_import

import sys
import threading
import logging
import time

from sjrpc.core import RpcConnection
from sjrpc.core.protocols import VpnProtocol

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('%(levelname)s %(name)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(fmt)
logger.addHandler(handler)

# Get arguments from the command line:
if len(sys.argv) < 3:
    print 'Usage: %s <listening address> <listening port>' % sys.argv[0]
    sys.exit(2)
address = sys.argv[1]
port = int(sys.argv[2])

# Create the rpc connection:
conn = RpcConnection.from_addr(address, port)

print 'connected.'

# Run the connection mainloop in another thread:
threading.Thread(target=conn.run).start()
time.sleep(0.1)

# Create the tunnel on the remote server:
label = conn.call('launch_vpn')

# Create the vpn on the local side:
conn.register_protocol(label, VpnProtocol, tun_prefix='vpnc')

raw_input('Type enter to quit.')

print 'shutdown'
conn.shutdown()
+72 −0
Original line number Diff line number Diff line
#!/usr/bin/env python

'''
Server mode using Gevent, using tunnelling feature to give a remote shell.
'''

from __future__ import absolute_import

import os
import sys
import fcntl

from sjrpc.server import RpcServer, SSLRpcServer
from sjrpc.utils import RpcHandler, pass_connection
from sjrpc.core.protocols import TunnelProtocol

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('%(levelname)s %(name)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(fmt)
logger.addHandler(handler)


class _FakeDevZeroSocket(object):

    def __init__(self):
        self._devzero = open('/dev/zero', 'rb')

    def recv(self, size):
        return '\0' * size#self._devzero.read(size)

    def send(self, data):
        pass # Cannot write on /dev/zero

    def fileno(self):
        return self._devzero.fileno()

    def setblocking(self, blocking):
        if not blocking:
            # Disable blocking mode on devzero:
            current_flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFL)
            fcntl.fcntl(self.fileno(), fcntl.F_SETFL, current_flags | os.O_NONBLOCK)
            pass
        else:
            raise NotImplementedError('Not implemented')


class PerfHandler(RpcHandler):

    @pass_connection
    def launch_perf(self, connection):
        devzero = _FakeDevZeroSocket()
        connection.register_protocol(2, TunnelProtocol, endpoint=devzero)
        return 2


# Get arguments from the command line:
if len(sys.argv) < 3:
    print 'Usage: %s <listening address> <listening port>' % sys.argv[0]
    sys.exit(2)
address = sys.argv[1]
port = int(sys.argv[2])

# Create the server instance:
import pyev
loop = pyev.default_loop(flags=~ pyev.EVBACKEND_EPOLL)
rpcserver = SSLRpcServer.from_addr(address, port, loop=loop, certfile='/var/lib/cc-server/ccserver.crt', keyfile='/var/lib/cc-server/ccserver.key', conn_kw=dict(handler=PerfHandler()))
#rpcserver = RpcServer.from_addr(address, port, loop=loop, conn_kw=dict(handler=PerfHandler()))
rpcserver.run()
+125 −0
Original line number Diff line number Diff line
#!/usr/bin/env python

'''
Server mode using Gevent, using tunnelling feature to give a remote shell.
'''

from __future__ import absolute_import

import os
import sys
import pty
import time
import subprocess
import threading
import logging
import fcntl
import socket

from sjrpc.server import RpcServer
from sjrpc.utils import RpcHandler, pass_connection
from sjrpc.core.protocols import TunnelProtocol

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('%(levelname)s %(name)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(fmt)
logger.addHandler(handler)


class _FakePtySocket(object):

    '''
    A fake socket object wrapping a :class:`subprocess.Popen` object standard
    input/output.
    '''

    def __init__(self, fd):
        self._fd = fd

    def recv(self, size):
        return os.read(self._fd, size)

    def send(self, data):
        return os.write(self._fd, data)

    def fileno(self):
        return self._fd

    def setblocking(self, blocking):
        if not blocking:
            # Disable blocking mode on stdin:
            current_flags = fcntl.fcntl(self._fd, fcntl.F_GETFL)
            fcntl.fcntl(self._fd, fcntl.F_SETFL, current_flags | os.O_NONBLOCK)
            pass
        else:
            raise NotImplementedError('Not implemented')


class _FakeDevZeroSocket(object):

    def __init__(self):
        self._devzero = open('/dev/zero', 'rb')

    def recv(self, size):
        return self._devzero.read(size)

    def send(self, data):
        pass # Cannot write on /dev/zero

    def fileno(self):
        return self._devzero.fileno()

    def setblocking(self, blocking):
        if not blocking:
            # Disable blocking mode on devzero:
            current_flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFL)
            fcntl.fcntl(self.fileno(), fcntl.F_SETFL, current_flags | os.O_NONBLOCK)
            pass
        else:
            raise NotImplementedError('Not implemented')


class RemoteShellHandler(RpcHandler):

    @pass_connection
    def launch_remote_console(self, connection, shell='/bin/bash'):

        master, slave = pty.openpty()
        endpoint = _FakePtySocket(master)
        # Create the tunnel on the label 1
        connection.register_protocol(1, TunnelProtocol, endpoint=endpoint)
        # Launch the shell process:
        self.pshell = subprocess.Popen(shell, stdout=slave, bufsize=0,
                                  stdin=slave, cwd='/',
                                  stderr=subprocess.STDOUT)
        return 1 # Return the tunnel id.

    #@pass_connection
    #def iperf(self, connection):
    #    devzero = _FakeDevZeroSocket()
    #    tun = connection.register_protocol(2, TunnelProtocol, endpoint=devzero)
    #    return 2

    @pass_connection
    def wait_for_pshell(self, conn):
        #conn.get_protocol(1)._send_get(1024 * 1024)
        return self.pshell.wait()

    def hup(self, *args, **kwargs):
        self.pshell.kill()

# Get arguments from the command line:
if len(sys.argv) < 3:
    print 'Usage: %s <listening address> <listening port>' % sys.argv[0]
    sys.exit(2)
address = sys.argv[1]
port = int(sys.argv[2])

# Create the server instance:
import pyev
loop = pyev.default_loop(flags=~ pyev.EVBACKEND_EPOLL)
rpcserver = RpcServer.from_addr(address, port, loop=loop, conn_kw=dict(handler=RemoteShellHandler(), on_disconnect='hup'))
rpcserver.run()
Loading