1#
2# Copyright (C) 2010-2017 Samuel Abels
3# The MIT License (MIT)
4#
5# Permission is hereby granted, free of charge, to any person obtaining
6# a copy of this software and associated documentation files
7# (the "Software"), to deal in the Software without restriction,
8# including without limitation the rights to use, copy, modify, merge,
9# publish, distribute, sublicense, and/or sell copies of the Software,
10# and to permit persons to whom the Software is furnished to do so,
11# subject to the following conditions:
12#
13# The above copyright notice and this permission notice shall be
14# included in all copies or substantial portions of the Software.
15#
16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23"""
24A driver for devices running JunOS (by Juniper).
25"""
26import re
27from Exscript.protocols.drivers.driver import Driver
28
29# JunOS prompt examples:
30#   sab@DD-EA3>
31#
32#   [edit]
33#   sab@DD-EA3>
34#
35#   {backup}
36#   sab@DD-EA3>
37#
38#   {backup}[edit]
39#   sab@DD-EA3>
40#
41#   {backup}[edit interfaces]
42#   sab@DD-EA3>
43#
44#   {master:3}
45#   pheller@sw3>
46#
47#   {primary:node0}
48#   pheller@fw1>
49#
50
51_user_re = [re.compile(r'[\r\n]login: $')]
52_password_re = [re.compile(r'[\r\n](Local )?[Pp]assword: ?$')]
53_mb = r'(?:\{master(?::\d+)?\}|\{backup(?::\d+)?\})'
54_ps = r'(?:\{primary:node\d+\}|\{secondary:node\d+\})'
55_re_re = r'(?:' + _mb + r'|' + _ps + r')'
56_edit = r'(?:\[edit[^\]\r\n]*\])'
57_prefix = r'(?:[\r\n]+' + _re_re + r'?' + _edit + r'?)'
58_prompt = r'[\r\n]+[\w\-\.]+@[\-\w+\.:]+[%>#] $'
59_prompt_re = [re.compile(_prefix + r'?' + _prompt)]
60_error_re = [re.compile(r'[\r\n](unknown|invalid|error|syntax error)', re.I)]
61_junos_re = re.compile(r'\bjunos\b', re.I)
62
63
64class JunOSDriver(Driver):
65
66    def __init__(self):
67        Driver.__init__(self, 'junos')
68        self.user_re = _user_re
69        self.password_re = _password_re
70        self.prompt_re = _prompt_re
71        self.error_re = _error_re
72
73    def check_head_for_os(self, string):
74        if _junos_re.search(string):
75            return 80
76        if _user_re[0].search(string):
77            return 35
78        return 0
79
80    def init_terminal(self, conn):
81        conn.execute('set cli screen-length 0')
82        conn.execute('set cli screen-width 0')
83        conn.execute('set cli terminal ansi')
84