Statistics
| Branch: | Tag: | Revision:

root / ncclient / ssh.py @ ee4bb099

History | View | Annotate | Download (5.2 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
import logging
16
from cStringIO import StringIO
17
from os import SEEK_CUR
18

    
19
import paramiko
20

    
21
from session import Session, SessionError
22

    
23
logger = logging.getLogger('ncclient.ssh')
24

    
25

    
26
class SessionCloseError(SessionError):
27
    
28
    def __str__(self):
29
        return 'RECEIVED: %s | UNSENT: %s' % (self._in_buf, self._out_buf)
30
    
31
    def __init__(self, in_buf, out_buf=None):
32
        SessionError.__init__(self)
33
        self._in_buf, self._out_buf = in_buf, out_buf
34

    
35

    
36
class SSHSession(Session):
37

    
38
    BUF_SIZE = 4096
39
    MSG_DELIM = ']]>]]>'
40
    
41
    def __init__(self, load_known_hosts=True,
42
                 missing_host_key_policy=paramiko.RejectPolicy):
43
        Session.__init__(self)
44
        self._client = paramiko.SSHClient()
45
        self._channel = None
46
        if load_known_hosts:
47
            self._client.load_system_host_keys()
48
        self._client.set_missing_host_key_policy(missing_host_key_policy)
49
        self._in_buf = StringIO()
50
        self._parsing_state = 0
51
        self._parsing_pos = 0
52
    
53
    def _close(self):
54
        self._channel.close()
55
        self._connected = False
56
    
57
    def _fresh_data(self):
58
        delim = SSHSession.MSG_DELIM
59
        n = len(delim) - 1
60
        state = self._parsing_state
61
        buf = self._in_buf
62
        buf.seek(self._parsing_pos)
63
        while True:
64
            x = buf.read(1)
65
            if not x: # done reading
66
                break
67
            elif x == delim[state]:
68
                state += 1
69
            else:
70
                continue
71
            # loop till last delim char expected, break if other char encountered
72
            for i in range(state, n):
73
                x = buf.read(1)
74
                if not x: # done reading
75
                    break
76
                if x==delim[i]: # what we expected
77
                    state += 1 # expect the next delim char
78
                else:
79
                    state = 0 # reset
80
                    break
81
            else: # if we didn't break out of above loop, full delim parsed
82
                till = buf.tell() - n
83
                buf.seek(0)
84
                msg = buf.read(till)
85
                self.dispatch('reply', msg)
86
                buf.seek(n+1, SEEK_CUR)
87
                rest = buf.read()
88
                buf = StringIO()
89
                buf.write(rest)
90
                buf.seek(0)
91
                state = 0
92
        self._in_buf = buf
93
        self._parsing_state = state
94
        self._parsing_pos = self._in_buf.tell()
95

    
96
    def load_host_keys(self, filename):
97
        self._client.load_host_keys(filename)
98
    
99
    def set_missing_host_key_policy(self, policy):
100
        self._client.set_missing_host_key_policy(policy)
101
    
102
    # paramiko exceptions ok?
103
    # user might be looking for ClientError
104
    def connect(self, hostname, port=830, username=None, password=None,
105
                key_filename=None, timeout=None, allow_agent=True,
106
                look_for_keys=True):
107
        self._client.connect(hostname, port=port, username=username,
108
                            password=password, key_filename=key_filename,
109
                            timeout=timeout, allow_agent=allow_agent,
110
                            look_for_keys=look_for_keys)    
111
        transport = self._client.get_transport()
112
        self._channel = transport.open_session()
113
        self._channel.invoke_subsystem('netconf')
114
        self._channel.set_name('netconf')
115
        self._connected = True
116
        self._post_connect()
117
    
118
    def run(self):
119
        chan = self._channel
120
        chan.setblocking(0)
121
        q = self._q
122
        try:
123
            while True:    
124
                if chan.closed:
125
                    raise SessionCloseError(self._in_buf.getvalue())         
126
                if chan.send_ready() and not q.empty():
127
                    data = q.get() + SSHSession.MSG_DELIM
128
                    while data:
129
                        n = chan.send(data)
130
                        if n <= 0:
131
                            raise SessionCloseError(self._in_buf.getvalue(), data)
132
                        data = data[n:]
133
                if chan.recv_ready():
134
                    data = chan.recv(SSHSession.BUF_SIZE)
135
                    if data:
136
                        self._in_buf.write(data)
137
                        self._fresh_data()
138
                    else:
139
                        raise SessionCloseError(self._in_buf.getvalue())
140
        except Exception as e:
141
            logger.debug('*** broke out of main loop ***')
142
            self.dispatch('error', e)
143

    
144
class MissingHostKeyPolicy(paramiko.MissingHostKeyPolicy):
145
    
146
    def __init__(self, cb):
147
        self._cb = cb
148
    
149
    def missing_host_key(self, client, hostname, key):
150
        if not self._cb(hostname, key):
151
            raise SSHError