1+ from cloudshell .cli .service .cli import CLI
2+ from cloudshell .cli .session .ssh_session import SSHSession
3+ from cloudshell .cli .service .command_mode import CommandMode
4+
5+
6+ class CreateSession ():
7+ def __init__ (self , host , username , password , logger = None , base_mode = "#" ):
8+ self .cli = CLI ()
9+ self .logger = logger
10+ self .mode = CommandMode (fr'{ base_mode } ' ) # for example r'%\s*$'
11+ enable_action_map = {
12+ "[Pp]assword for {}" .format (username ): lambda session , logger : session .send_line (password , logger )}
13+ self .elevated_mode = CommandMode (r'(?:(?!\)).)#\s*$' , enter_command = 'sudo su' , exit_command = 'exit' ,
14+ enter_action_map = enable_action_map )
15+ self .mode .add_child_node (self .elevated_mode )
16+ self .elevated_mode .add_parent_mode (self .mode )
17+ self .session_types = [SSHSession (host = host ,
18+ username = username ,
19+ password = password )]
20+
21+ self .session = self .cli .get_session (command_mode = self .mode ,
22+ defined_sessions = self .session_types )
23+
24+ def send_terminal_command (self , command , password = None ):
25+ outp = []
26+ out = None
27+ with self .session as my_session :
28+ if isinstance (command , list ):
29+ for single_command in command :
30+ if password :
31+ single_command = '{command}' .format (command = single_command , password = password )
32+ # single_command = 'echo {password} | sudo -S sh -c "{command}"'.format(command=single_command,
33+ # password=password)
34+ self .logger .info ('sending command {}' .format (single_command ))
35+ current_outp = my_session .send_command (single_command )
36+ outp .append (current_outp )
37+ self .logger .info ('got output {}' .format (current_outp ))
38+ out = '\n ' .join (outp )
39+ else :
40+ if password :
41+ command = '{command}' .format (command = command )
42+ out = my_session .send_command (command )
43+ return out
44+
45+
46+ if __name__ == "__main__" :
47+ import cli_credentials
48+
49+ # juniper switch example
50+ base_mode = "%"
51+ cli = CreateSession (host = cli_credentials .HOST ,
52+ username = cli_credentials .USER ,
53+ password = cli_credentials .PASSWORD ,
54+ base_mode = base_mode )
55+ sample_command = 'ls'
56+ outp = cli .send_terminal_command (sample_command )
57+ print (outp )
0 commit comments