class CreateSession(): def __init__(self, host, username, password, logger=None): self.cli = CLI() self.logger = logger self.mode = CommandMode(r'$') # for example r'%\s*$' enable_action_map = { "[Pp]assword for {}".format(username): lambda session, logger: session.send_line(password, logger) } self.elevated_mode = CommandMode(r'(?:(?!\)).)#\s*$', enter_command='sudo su', exit_command='exit', enter_action_map=enable_action_map) self.mode.add_child_node(self.elevated_mode) self.elevated_mode.add_parent_mode(self.mode) self.session_types = [ SSHSession(host=host, username=username, password=password) ] self.session = self.cli.get_session(command_mode=self.elevated_mode, new_sessions=self.session_types) def send_terminal_command(self, command, password=None): outp = [] out = None with self.session as my_session: if isinstance(command, list): for single_command in command: if password: single_command = '{command}'.format( command=single_command, password=password) # single_command = 'echo {password} | sudo -S sh -c "{command}"'.format(command=single_command, # password=password) self.logger.info( 'sending command {}'.format(single_command)) current_outp = my_session.send_command(single_command) outp.append(current_outp) self.logger.info('got output {}'.format(current_outp)) out = '\n'.join(outp) else: if password: command = '{command}'.format(command=command) out = my_session.send_command(command) return out
class CreateSession(): def __init__(self, host, username, password): self.cli = CLI() self.mode = CommandMode(r'#')# for example r'%\s*$' self.clish_mode = CommandMode(r'>', enter_command='clish', exit_command='exit')# for example r'%\s*$' self.mode.add_child_node(self.clish_mode) self.session_types = [SSHSession(host=host, username=username, password=password)] self.session = self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types) def send_terminal_command(self, command): with self.session as my_session: out = my_session.send_command(command) return out def send_clish_terminal_command(self, commands): outp = [] with self.cli.get_session(command_mode=self.mode, new_sessions=self.session_types) as session: with session.enter_mode(self.clish_mode) as clish_session: for command in commands: outp.append(clish_session.send_command(command)) return '\n'.join(outp) def config_license(self): outp = [] outp.append(self.send_terminal_command('\r\n')) outp.append(self.send_terminal_command('config log syslogd setting\r\n')) outp.append(self.send_terminal_command('set status enable\r\n')) outp.append(self.send_terminal_command('set server {}\r\n'.format(self.splunk_address))) outp.append(self.send_terminal_command('end\r\n')) return outp