def main(): users = {'testadmin': 'x'} log.startLogging(sys.stderr) MockSSH.runServer( commands, prompt="hostname>", interface='127.0.0.1', port=9999, **users)
def setUpClass(cls): users = {'testadmin': 'x'} MockSSH.startThreadedServer(commands, prompt="hostname>", interface="localhost", port=9999, **users)
def setUpClass(cls): users = {'testadmin': 'x'} MockSSH.startThreadedServer( commands, prompt="[root@hostname:Active] testadmin # ", interface="localhost", port=1025, **users)
def setUpClass(cls): users = {'testadmin': 'x'} cls.keypath = tempfile.mkdtemp() MockSSH.startThreadedServer(commands, prompt="hostname>", keypath=cls.keypath, interface="localhost", port=9999, **users)
def main(): users = {'ansible': 'ansible'} log.startLogging(sys.stderr) MockSSH.runServer(commands, prompt="\rNexus9000v# ", interface='127.0.0.1', port=9999, **users)
def stopAll(self): """Kill the underlying thread that contains all SSH servers. Due to library limitations, you can't start a new server after killing the thread. :returns: MockAerohive -- This SSH server for chaining. """ MockSSH.stopThreadedServer() self.running = False return self
def setUpClass(cls): users = {'testadmin': 'x'} cls.keypath = tempfile.mkdtemp() MockSSH.startThreadedServer( commands, prompt="[root@hostname:Active] testadmin # ", keypath=cls.keypath, interface="localhost", port=1025, **users)
def main(): commands = [command_passwd] users = {'testadmin': 'x'} log.startLogging(sys.stderr) MockSSH.runServer(commands, prompt="[root@hostname:Active] testadmin # ", interface='127.0.0.1', port=9999, **users)
def mock_f5(): # Redirect stdout to null f = open(os.devnull, 'w') sys.stdout = f commands = [cmd_f5_bash, cmd_f5_tmctl, cmd_f5_show] users = {'test': 'test'} MockSSH.runServer(commands, prompt="user@(F5-TEST)(cfg-sync In Sync)(/S1-green-P:Active)(/Common)(tmos)# ", interface='127.0.0.1', port=9999, **users)
def mock_cisco(): # Redirect stdout to null f = open(os.devnull, 'w') sys.stdout = f commands = [cmd_cisco_show] users = {'test': 'test'} MockSSH.runServer(commands, prompt="hostname>", interface='127.0.0.1', port=9999, **users)
def mock_f5(): # Redirect stdout to null f = open(os.devnull, 'w') sys.stdout = f commands = [cmd_f5_bash, cmd_f5_tmctl, cmd_f5_show] users = {'test': 'test'} MockSSH.runServer( commands, prompt= "user@(F5-TEST)(cfg-sync In Sync)(/S1-green-P:Active)(/Common)(tmos)# ", interface='127.0.0.1', port=9999, **users)
def main(): commands = [command_en, command_conf, command_username, command_wr, command_exit] users = {'testadmin': 'x'} log.startLogging(sys.stderr) MockSSH.runServer(commands, prompt="hostname>", interface='127.0.0.1', port=9999, **users)
def setUpClass(cls): # # command: pwd # def pwd_command_success(instance): instance.writeln("[OK]") def pwd_command_failure(instance): instance.writeln("MockSSH: Supported usage: pwd") command_pwd = MockSSH.ArgumentValidatingCommand( 'pwd', [pwd_command_success], [pwd_command_failure], *[]) # # command: ls # def ls_command_success(instance): instance.writeln("[OK]") def ls_command_failure(instance): instance.writeln("MockSSH: Supported usage: ls l") command_ls = MockSSH.ArgumentValidatingCommand('ls', [ls_command_success], [ls_command_failure], *["l"]) # # command: date # def date_command_success(instance): instance.writeln("[OK]") def date_command_failure(instance): instance.writeln("MockSSH: Supported usage: date") command_date = MockSSH.ArgumentValidatingCommand( 'date', [date_command_success], [date_command_failure], *[]) commands = [command_pwd, command_ls, command_date] users = {'testadmin': 'x'} cls.keypath = tempfile.mkdtemp() MockSSH.startThreadedServer(commands, prompt="hostname>", keypath=cls.keypath, interface="localhost", port=9999, **users)
def start_cisco_mock(initial_prompt='>'): """This is where we define everything that is emulated""" # List of commands to emulate... see definitions above commands = [ command_en, command_enable, command_term_len, command_sh_ip_int_brief, command_sh_ver, command_conf, command_username, command_wr, command_quit, command_end, command_exit, ] users = {'admin': 'cisco'} MockSSH.startThreadedServer(commands, prompt=CRLF+"{0}{1}".format(HOSTNAME, initial_prompt), interface="localhost", port=2222, **users)
def spawn_server(port_low, port_high, interface, protocol_type, data): #p = psutil.Process(os.getpid()) try: os.nice(-1) except Exception as e: print "Unable to lower niceness(priority), RUN AS SUDO, running with normal priority" for i in range(port_low, port_high): try: print "Spawning " show_commands, prompt_change_commands, usr, passwd, cmd_delay, default_prompt = parse_commands( data) users = {usr: passwd} local_commands = [] for cmd in show_commands: command = getShowCommand(cmd, data, show_commands[cmd], cmd_delay) local_commands.append(command) for cmd in prompt_change_commands: if ("password" in prompt_change_commands[cmd]): command = getPasswordPromptCommand( cmd, prompt_change_commands[cmd], cmd_delay) else: command = getPromptChangingCommand( cmd, prompt_change_commands[cmd], cmd_delay) local_commands.append(command) factory = None if (protocol_type == "ssh"): factory = MockSSH.getSSHFactory(local_commands, default_prompt, ".", **users) elif (protocol_type == "telnet"): factory = MockSSHExtensions.getTelnetFactory( local_commands, default_prompt, **users) reactor.listenTCP(i, factory, interface=interface) except Exception as e: print >> sys.stderr, traceback.format_exc() print "Unable to open port at %s, due to: %s" % (i, e) reactor.run()
def run(self, interface="127.0.0.1", port=None): """Start the SSH server listening. You must add a username (addUser) before starting the server. (Errors will be thrown! It's a library limitation.) :param str interface: The interface to listen to. Defaults to ``127.0.0.1``. :param port: The port to listen to. If not provided (or None), an open port will be chosen. :type port: int or None :returns: int -- The port the SSH server is listening to. """ if port == None: port = get_open_port() self.running = True # Re-implementation of MockSSH.startThreadedServer, # that doesn't start Reactor inside a Thread if it's already running. sshFactory = MockSSH.getSSHFactory(self.commands, prompt=self.prompt(), keypath=".", **self.users) self.listener = reactor.listenTCP(port, sshFactory, interface='') if not reactor.running: Thread(target=reactor.run, args=(False, )).start() self.reactor_running = True return port
def ssh_hook_to_reactor(reactor): sshFactory = MockSSH.getSSHFactory(commands, "hostname>", tempfile.mkdtemp(), **users) reactor.listenTCP(interface='127.0.0.1', port=SshClientTest.port, factory=sshFactory)
from mock import patch, Mock from twisted.internet.protocol import Factory from netman.adapters import shell from netman.adapters.shell.ssh import SshClient from netman.adapters.shell.telnet import TelnetClient from netman.core.objects.exceptions import CouldNotConnect, CommandTimeout, ConnectTimeout from tests.adapters.shell.mock_telnet import MockTelnet from tests.adapters.shell.mock_terminal_commands import passwd_change_protocol_prompt, passwd_write_password_to_transport, \ HangingCommand, MultiAsyncWriteCommand, SkippingLineCommand, exit_command_success, KeystrokeAnsweredCommand, \ AmbiguousCommand command_passwd = MockSSH.PromptingCommand( name='passwd', password='******', prompt="Password:"******"Bonjour")], failure_callbacks=[lambda instance: instance.writeln("Nope")]) command_hang = HangingCommand(name='hang', hang_time=1.1) command_flush = MultiAsyncWriteCommand(name='flush', count=5, interval=0.1) command_skips= SkippingLineCommand(name='skips', lines=5) command_exit = MockSSH.ArgumentValidatingCommand('exit',
def tearDownClass(cls): print("tearDownClass") MockSSH.stopThreadedServer() shutil.rmtree(cls.keypath)
import MockSSH import sys from inform import send_inform users = {'ubnt': 'ubnt'} def execCommandImplemented(self, protocol, cmd): (_, _, url, key) = cmd.split(' ') print(cmd) with open('/tmp/cfg/log', 'w') as f: f.write('url=%s\nkey=%s\n' % (url, key)) send_inform(url, key, partial=True) send_inform(url, key) MockSSH.SSHAvatar.execCommand = execCommandImplemented commands = [] MockSSH.runServer(commands, prompt="ubnt#", interface='10.0.8.2', port=10022, **users)
def stop_cisco_mock(): MockSSH.stopThreadedServer()
# # command: en # def en_change_protocol_prompt(instance): instance.protocol.prompt = "hostname #" instance.protocol.password_input = False def en_write_password_to_transport(instance): instance.writeln("MockSSH: password is %s" % instance.valid_password) command_en = MockSSH.PromptingCommand( name='en', password='******', prompt="Password: "******"MockSSH: supported usage: conf t") def conf_output_success(instance): instance.writeln("Enter configuration commands, one per line. End " "with CNTL/Z")
def conf_output_error(instance): instance.writeln("MockSSH: supported usage: conf t") def conf_output_success(instance): instance.writeln("Enter configuration commands, one per line. End " "with CNTL/Z") def conf_change_protocol_prompt(instance): instance.protocol.prompt = "\rNexus9000v(config)#" command_conf = MockSSH.ArgumentValidatingCommand( 'conf', [conf_output_success, conf_change_protocol_prompt], [conf_output_error], *["t"]) def exit_command_success(instance): if 'config' in instance.protocol.prompt: instance.protocol.prompt = "\rNexus9000v(config)#" else: instance.protocol.call_command(instance.protocol.commands['_exit']) def exit_command_failure(instance): instance.writeln("MockSSH: supported usage: exit") command_exit = MockSSH.ArgumentValidatingCommand('exit',
def ssh_hook_to_reactor(reactor): sshFactory = MockSSH.getSSHFactory(commands, "hostname>", tempfile.mkdtemp(), **users) reactor.listenTCP(interface="127.0.0.1", port=SshClientTest.port, factory=sshFactory)
import MockSSH import random import string from twisted.cred import checkers # Dirty hack to override default twisted behavior class CredsToStdOut(checkers.InMemoryUsernamePasswordDatabaseDontUse): def requestAvatarId(self, credentials): print("Authentication attempt: %s / %s" % (credentials.username, credentials.password)) return super(CredsToStdOut, self).requestAvatarId(credentials) MockSSH.checkers.InMemoryUsernamePasswordDatabaseDontUse = CredsToStdOut def passwd_change_protocol_prompt(instance): instance.protocol.prompt = "hostname #" instance.protocol.password_input = False def passwd_write_password_to_transport(instance): instance.writeln("") command_passwd = MockSSH.PromptingCommand( name = 'passwd', password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(99)), prompt = "Password: "******"hostname>", interface = '0.0.0.0', port = 2222, **users)
def tearDownClass(cls): print "tearDownClass" MockSSH.stopThreadedServer() shutil.rmtree(cls.keypath)
def tearDownClass(cls): print "tearDownClass" MockSSH.stopThreadedServer()
# command: wr # def wr_build_config(instance): instance.terminal.session.conn.transport.transport.setTcpNoDelay(True) instance.write("Building configuration...") ## In a perfect world, we would sleep here to pretend ## that the router is building the configuration; however, ## there isn't a good way to make Twisted flush the TCP buffer ## so the client sees a delay between "Building configuration..." ## and "[OK]" #time.sleep(1.2) instance.write(CRLF+"[OK]") command_en = MockSSH.PromptingCommand( 'en', # the enable command ENABLE_PASS, # enable password 'Password: '******'enable', # the enable command ENABLE_PASS, # enable password 'Password: '******'conf', [conf_output_success, conf_change_protocol_prompt], [invalid_input], *["t"])
def connectionMade(self): manhole.Manhole.connectionMade(self) self.cmdstack = [MockSSH.SSHShell(self, self.prompt)]
def tearDownClass(cls): print("tearDownClass") MockSSH.stopThreadedServer()
fixture['tmctl -c pva_stat'] = open('mockssh/f5_tmctl_csv.txt').read() def cmd_parser(instance): cmd = " ".join(instance.args) if cmd in fixture: instance.writeln(fixture[cmd]) else: instance.writeln('Invalid command') def f5_prompt(instance): instance.protocol.prompt = '[user@F5-TEST:/S1-green-P:Active:In Sync] ~ # ' cmd_cisco_show = MockSSH.ArgumentValidatingCommand('show', [cmd_parser], [cmd_parser], *[]) cmd_f5_show = MockSSH.ArgumentValidatingCommand('show', [cmd_parser], [cmd_parser], *[]) cmd_f5_bash = MockSSH.ArgumentValidatingCommand('bash', [f5_prompt], [f5_prompt], *[]) cmd_f5_tmctl = MockSSH.ArgumentValidatingCommand('tmctl', [cmd_parser], [cmd_parser], *[]) def mock_cisco(): # Redirect stdout to null f = open(os.devnull, 'w') sys.stdout = f