def __init__(self, handler=None, prompt='CMD> ', port=20022): self.commands = {} self.port = port if self.PROMPT: self.prompt = self.PROMPT else: self.prompt = prompt self.server = sshim.Server(self.handle_command, port=int(self.port)) self.response = '' self.__running = True if handler is None: handler = self self.commands['HELP'] = self.command_help for key in dir(handler): cmd = getattr(handler, key) try: cmd_name = cmd.command_name except: if key[:8] == 'command_': cmd_name = key[8:] else: continue cmd_name = cmd_name.upper() self.commands[cmd_name] = cmd for alias in getattr(cmd, "aliases", []): self.commands[alias.upper()] = self.commands[cmd_name]
def test_unexpected(self): def echo(script): script.expect('moose') script.writeline('return') with sshim.Server(echo, port=3000) as server: with connect(server) as fileobj: fileobj.write('goose\n') fileobj.flush() server.exceptions.get()
def test_eof(self): def echo(script): script.expect('goose') self.assertRaises(EOFError, script.expect, '') with sshim.Server(echo, port=3000) as server: with connect(server) as fileobj: fileobj.write('goose\n') fileobj.flush() fileobj.close()
def start_ssh_server(port): global server print('Starting fake SSH server on port %d' % port) server = sshim.Server(ask_for_password, port=port) try: server.run() except KeyboardInterrupt: server.stop()
def test_echo(self): def echo(script): groups = script.expect(re.compile('(?P<value>.*)')).groupdict() assert groups['value'] == 'test_echo' script.writeline('return %(value)s' % groups) with sshim.Server(echo, port=3000) as server: with connect(server) as fileobj: fileobj.write('test_echo\n') fileobj.flush() assert fileobj.readline() == 'test_echo\r\n' assert fileobj.readline() == 'return test_echo\r\n'
def test_grep(self): """Check if basic runner grep functionality works""" r = Runner(self.services) def grep_response(script): script.writeline(self.template) with sshim.Server(grep_response, port=1025, handler=ExecHandler): for response in r.grep("foo"): self.assertEqual( (FakeService.name, FakeServer.hostname, self.template), response, )
def __init__(self, handler=None, prompt='CMD> ', port=20022): self.port = port if self.PROMPT: self.prompt = self.PROMPT else: self.prompt = prompt self.server = sshim.Server(self.handle_command, port=int(self.port)) self.response = '' if handler is None: handler = self self.command_handler = command.Command_Handler() self.thread_stop = threading.Event()
def test_unicode_echo(self): def decode(value): if isinstance(value, six.text_type): return value return codecs.decode(value, 'utf8') def echo(script): groups = script.expect(re.compile( six.u('(?P<value>.*)'))).groupdict() value = groups['value'] assert value == six.u('£test') script.writeline(six.u('return {0}').format(value)) with sshim.Server(echo, port=3000, encoding='utf8') as server: with connect(server) as fileobj: fileobj.write(six.u('£test\n').encode('utf8')) fileobj.flush() assert decode(fileobj.readline()) == six.u('£test\r\n') assert decode(fileobj.readline()) == six.u('return £test\r\n')
def test_another_server(self): with sshim.Server(success, port=3000) as server: self.assert_success(server)
commands = {'adduser': adduser} def cursor(self, key): if key == 'A': self.script.writeline('up') def prompt(self): self.script.write('root@device # ') def run(self): while True: self.prompt() match = self.script.expect( re.compile('(?P<command>\S+)?\s*(?P<arguments>.*)')) self.history.append(match.group(0)) groups = match.groupdict() if groups['command'] == 'exit': break if groups['command'] in Device.commands: Device.commands[groups['command']](self, *shlex.split( groups['arguments'])) else: self.script.writeline('-bash: %s: command not found' % groups['command']) server = sshim.Server(Device, port=3000) try: server.run() except KeyboardInterrupt: server.stop()
script.write('Nokia_1830PSS_Sim# ') def main(script): pss = NokiaPSS1830Sim(fixture_path) welcome(script) logger.info('running main script') while True: groups = script.expect(re.compile('(?P<command>.*)'), True).groupdict() command = groups['command'] logger.info('got command %s' % command) if command == 'logout': script.writeline('Logging out....') break else: script.write(pss.execute_command(command)) server = sshim.Server(main, port=0) def run_forever(server): try: server.run() except KeyboardInterrupt: server.stop() if __name__ == "__main__": run_forever(server)
logging.basicConfig(level='DEBUG') import sshim, time, re from six.moves import range # define the callback function which will be triggered when a new SSH connection is made: def counter(script): while True: for n in range(0, 10): # send the numbers 0 to 10 to the client with a little pause between each one for dramatic effect: script.writeline(n) time.sleep(0.1) # ask them if they are interested in seeing the show again script.write('Again? (y/n): ') # parse their input with a regular expression and pull it into a named group groups = script.expect(re.compile('(?P<again>[yn])')).groupdict() # if they didn't say yes, break out the loop and disconnect them if groups['again'] != 'y': break # create a server and pass in the callback method # connect to it using `ssh localhost -p 3000` server = sshim.Server(counter, port=3000) try: server.run() except KeyboardInterrupt: server.stop()
import logging logging.basicConfig(level='DEBUG') logger = logging.getLogger() import sshim, re # define the callback function which will be triggered when a new SSH connection is made: def hello_world(script): # ask the SSH client to enter a name script.write('Please enter your name: ') # match their input against a regular expression which will store the name in a capturing group called name groups = script.expect(re.compile('(?P<name>.*)')).groupdict() # log on the server-side that the user has connected logger.info('%(name)s just connected', **groups) # send a message back to the SSH client greeting it by name script.writeline('Hello %(name)s!' % groups) # create a server and pass in the callback method # connect to it using `ssh localhost -p 3000` server = sshim.Server(hello_world, port=3000) try: server.run() except KeyboardInterrupt: server.stop()