Statistics
| Branch: | Tag: | Revision:

root / ncclient / ssh.py @ 3ad93428

History | View | Annotate | Download (5.1 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
import paramiko
17

    
18
from os import SEEK_CUR
19
from cStringIO import StringIO
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
        if load_known_hosts:
46
            self._client.load_system_host_keys()
47
        self._client.set_missing_host_key_policy(missing_host_key_policy)
48
        self._in_buf = StringIO()
49
        self._parsing_state = 0
50
        self._parsing_pos = 0
51
    
52
    def load_host_keys(self, filename):
53
        self._client.load_host_keys(filename)
54
    
55
    def set_missing_host_key_policy(self, policy):
56
        self._client.set_missing_host_key_policy(policy)
57
    
58
    # paramiko exceptions ok?
59
    # user might be looking for ClientError
60
    def connect(self, hostname, port=830, username=None, password=None,
61
                key_filename=None, timeout=None, allow_agent=True,
62
                look_for_keys=True):
63
        self._client.connect(hostname, port=port, username=username,
64
                            password=password, key_filename=key_filename,
65
                            timeout=timeout, allow_agent=allow_agent,
66
                            look_for_keys=look_for_keys)    
67
        transport = self._client.get_transport()
68
        self._channel = transport.open_session()
69
        self._channel.invoke_subsystem('netconf')
70
        self._channel.set_name('netconf')
71
        self._connected = True
72
        self._post_connect()
73
    
74
    def run(self):
75
        chan = self._channel
76
        chan.setblocking(0)
77
        q = self._q
78
        try:
79
            while True:    
80
                if chan.closed:
81
                    raise SessionCloseError(self._in_buf.getvalue())         
82
                if chan.send_ready() and not q.empty():
83
                    data = q.get() + SSHSession.MSG_DELIM
84
                    while data:
85
                        n = chan.send(data)
86
                        if n <= 0:
87
                            raise SessionCloseError(self._in_buf.getvalue(), data)
88
                        data = data[n:]
89
                if chan.recv_ready():
90
                    data = chan.recv(SSHSession.BUF_SIZE)
91
                    if data:
92
                        self._in_buf.write(data)
93
                        self._fresh_data()
94
                    else:
95
                        raise SessionCloseError(self._in_buf.getvalue())
96
        except Exception as e:
97
            logger.debug('*** broke out of main loop ***')
98
            self.dispatch('error', e)
99
    
100
    def _close(self):
101
        self._channel.close()
102
        self._connected = False
103
    
104
    def _fresh_data(self):
105
        delim = SSHSession.MSG_DELIM
106
        n = len(delim) - 1
107
        state = self._parsing_state
108
        buf = self._in_buf
109
        buf.seek(self._parsing_pos)
110
        while True:
111
            x = buf.read(1)
112
            if not x: # done reading
113
                break
114
            elif x == delim[state]:
115
                state += 1
116
            else:
117
                continue
118
            # loop till last delim char expected, break if other char encountered
119
            for i in range(state, n):
120
                x = buf.read(1)
121
                if not x: # done reading
122
                    break
123
                if x==delim[i]: # what we expected
124
                    state += 1 # expect the next delim char
125
                else:
126
                    state = 0 # reset
127
                    break
128
            else: # if we didn't break out of above loop, full delim parsed
129
                till = buf.tell() - n
130
                buf.seek(0)
131
                msg = buf.read(till)
132
                self.dispatch('reply', msg)
133
                buf.seek(n+1, SEEK_CUR)
134
                rest = buf.read()
135
                buf = StringIO()
136
                buf.write(rest)
137
                buf.seek(0)
138
                state = 0
139
        self._in_buf = buf
140
        self._parsing_state = state
141
        self._parsing_pos = self._in_buf.tell()
142

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