Debian Codegraph @

lib/jnpr/junos/transport/tty.py

raw
1 from time import sleep
2 import logging
3
4 from jnpr.junos import exception as EzErrors
5 from jnpr.junos.transport.tty_netconf import tty_netconf
6
7 logger = logging.getLogger("jnpr.junos.tty")
8
9 __all__ = ["Terminal"]
10
11 # =========================================================================
12 # Terminal class
13 # =========================================================================
14
15
16 class Terminal(object):
17 """
18 Terminal is used to bootstrap Junos New Out of the Box (NOOB) device
19 over the CONSOLE port. The general use-case is to setup the minimal
20 configuration so that the device is IP reachable using SSH
21 and NETCONF for remote management.
22
23 Serial is needed for Junos devices that do not support
24 the DHCP 'auto-installation' or 'ZTP' feature; i.e. you *MUST*
25 do the NOOB configuration via the CONSOLE.
26
27 Serial is also useful for situations even when the Junos
28 device supports auto-DHCP, but is not an option due to the
29 specific situation
30 """
31
32 TIMEOUT = 0.2 # serial readline timeout, seconds
33 EXPECT_TIMEOUT = 10 # total read timeout, seconds
34 LOGIN_RETRY = 20 # total number of passes thru login state-machine
35
36 _ST_INIT = 0
37 _ST_LOADER = 1
38 _ST_LOGIN = 2
39 _ST_PASSWD = 3
40 _ST_DONE = 4
41 _ST_BAD_PASSWD = 5
42 _ST_TTY_NOLOGIN = 6
43 _ST_TTY_OPTION = 7
44 _ST_TTY_HOTKEY = 8
45
46 _re_pat_login = r"(?P<login>ogin:\s*$)"
47
48 _RE_PAT = [
49 r"(?P<loader>oader>\s*$)",
50 _re_pat_login,
51 r"(?P<passwd>assword:\s*$)",
52 "(?P<badpasswd>ogin incorrect)",
53 r"(?P<netconf_closed><!-- session end at .*-->\s*)",
54 r"(?P<shell>%|#|(~\$)\s*$)",
55 r'(?P<cli>[^\-"]>\s*$)',
56 r"(?P<option>Enter your option:\s*$)",
57 "(?P<hotkey>connection: <CTRL>Z)",
58 ]
59
60 # -----------------------------------------------------------------------
61 # CONSTRUCTOR
62 # -----------------------------------------------------------------------
63
64 def __init__(self, **kvargs):
65 """
66 :kvargs['user']:
67 defaults to 'root'
68
69 :kvargs['passwd']:
70 defaults to empty; NOOB Junos device there is
71 no root password initially
72
73 :kvargs['attempts']:
74 the total number of login attempts thru the login
75 state-machine
76 """
77 # logic args
78 self.hostname = self.__dict__.get("host")
79 self.user = kvargs.get("user", "root")
80 self.passwd = kvargs.get("passwd", "")
81 self.cs_user = kvargs.get("cs_user")
82 self.cs_passwd = kvargs.get("cs_passwd")
83 self.login_attempts = kvargs.get("attempts") or self.LOGIN_RETRY
84 self.console_has_banner = kvargs.get("console_has_banner") or False
85 self._huge_tree = kvargs.get("huge_tree", False)
86
87 # misc setup
88 self.nc = tty_netconf(self)
89 self.state = self._ST_INIT
90 self._badpasswd = 0
91 self._loader = 0
92
93 @property
94 def tty_name(self):
95 return self._tty_name
96
97 # -----------------------------------------------------------------------
98 # Login/logout
99 # -----------------------------------------------------------------------
100
101 def login(self):
102 """
103 open the TTY connection and login. once the login is successful,
104 start the NETCONF XML API process
105 """
106 logger.info("TTY: connecting to TTY:{} ...".format(self.tty_name))
107 self._tty_open()
108
109 logger.info("TTY: logging in......")
110
111 self.state = self._ST_INIT
112 self._login_state_machine()
113
114 # now start NETCONF XML
115 logger.info("TTY: OK.....starting NETCONF")
116 self.nc.open(at_shell=self.at_shell)
117 self.session_id = self.nc._session_id
118
119 return True
120
121 def logout(self):
122 """
123 cleanly logout of the TTY
124 """
125 logger.info("logout: logging out.....")
126 self.nc.close()
127 self._logout_state_machine()
128 return True
129
130 # ---------------------------------------------------------------------
131 # TTY logout state-machine
132 # ---------------------------------------------------------------------
133
134 def _logout_state_machine(self, attempt=0):
135 if 10 == attempt:
136 raise RuntimeError("logout_sm_failure")
137
138 prompt, found = self.read_prompt()
139
140 def _ev_login():
141 # back at login prompt, so we are cleanly done!
142 self._tty_close()
143
144 def _ev_shell():
145 self.write("exit")
146
147 def _ev_cli():
148 self.write("exit")
149
150 # Connection closed by foreign host
151 def _ev_netconf_closed():
152 return True
153
154 _ev_tbl = {
155 "login": _ev_login,
156 "shell": _ev_shell,
157 "cli": _ev_cli,
158 "netconf_closed": _ev_netconf_closed,
159 }
160
161 # hack for now
162 # in case of telnet to management port, after writing exit on console
163 # it exits completely and returns None
164 ###
165 if found is not None:
166 _ev_tbl[found]()
167 else:
168 return True
169
170 if found == "login":
171 return True
172
173 else:
174 sleep(1)
175 return self._logout_state_machine(attempt=attempt + 1)
176
177 # -----------------------------------------------------------------------
178 # TTY login state-machine
179 # -----------------------------------------------------------------------
180 def _login_state_machine(self, attempt=0):
181 if self.login_attempts == attempt:
182 raise RuntimeError("login_sm_failure")
183
184 prompt, found = self.read_prompt()
185
186 def _ev_loader():
187 self.state = self._ST_LOADER
188 self.write("boot")
189 self.write("\n")
190 sleep(300)
191 self._login_state_machine(attempt=0)
192 self._loader += 1
193 if self._loader == 2:
194 raise RuntimeError("probably corrupted image, stuck in loader")
195
196 def _ev_login():
197 self.state = self._ST_LOGIN
198 self.write(self.user)
199
200 def _ev_passwd():
201 self.state = self._ST_PASSWD
202 self.write(self.passwd)
203
204 def _ev_bad_passwd():
205 self.state = self._ST_BAD_PASSWD
206 self.write("\n")
207 self._badpasswd += 1
208 if self._badpasswd == 2:
209 self._tty_close()
210 # raise RuntimeError("Bad username/password")
211 raise EzErrors.ConnectAuthError(self, "Bad username/password")
212 # return through and try again ... could have been
213 # prior failed attempt
214
215 def _ev_tty_nologin():
216 if self._ST_INIT == self.state:
217 # assume we're in a hung state, i.e. we don't see
218 # a login prompt for whatever reason
219 self.state = self._ST_TTY_NOLOGIN
220 # For console based telnet connection a new-line is required.
221 # Code modified to check with a newline for telnet based connections.
222 # Keeping below code as a comment for future enhancement.
223 # if self.console_has_banner:
224 # # if console connection has a banner or warning,
225 # # use this hack
226 # sleep(5)
227 # self.write("\n")
228 sleep(5)
229 self.write("\n")
230 else:
231 # @@@ this is still a hack - used by default
232 self.write("<close-session/>")
233
234 def _ev_shell():
235 if self.state == self._ST_INIT:
236 # this means that the shell was left
237 # open. probably not a good thing,
238 # so issue a logging message, but move on.
239 logger.warning("login_warn: Shell login was open!!")
240
241 self.at_shell = True
242 self.state = self._ST_DONE
243 # if we are here, then we are done
244
245 def _ev_cli():
246 if self.state == self._ST_INIT:
247 # this means that the shell was left open. probably not a
248 # good thing, so issue a logging message, hit <ENTER> and try
249 # again just to be sure...
250 logger.warning("login_warn: waiting on TTY..... ")
251 sleep(5)
252 # return
253
254 self.at_shell = False
255 self.state = self._ST_DONE
256
257 def _ev_option():
258 self.state = self._ST_TTY_OPTION
259 self.write("1")
260
261 def _ev_hot_key():
262 self.state = self._ST_TTY_HOTKEY
263 self.write("\n")
264
265 _ev_tbl = {
266 "loader": _ev_loader,
267 "login": _ev_login,
268 "passwd": _ev_passwd,
269 "badpasswd": _ev_bad_passwd,
270 "shell": _ev_shell,
271 "cli": _ev_cli,
272 "option": _ev_option,
273 "hotkey": _ev_hot_key,
274 }
275
276 _ev_tbl.get(found, _ev_tty_nologin)()
277
278 if self.state == self._ST_DONE:
279 return True
280 else:
281 # if we are here, then loop the event again
282 self._login_state_machine(attempt + 1)