Statistics
| Branch: | Tag: | Revision:

root / ncclient / manager.py @ e3b66e4b

History | View | Annotate | Download (6.6 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
"This module is a thin layer of abstraction around the library. It exposes all core functionality."
16

    
17
import capabilities
18
import operations
19
import transport
20

    
21
import logging
22
logger = logging.getLogger('ncclient.manager')
23

    
24
CAPABILITIES = [
25
    "urn:ietf:params:netconf:base:1.0",
26
    "urn:ietf:params:netconf:capability:writable-running:1.0",
27
    "urn:ietf:params:netconf:capability:candidate:1.0",
28
    "urn:ietf:params:netconf:capability:confirmed-commit:1.0",
29
    "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
30
    "urn:ietf:params:netconf:capability:startup:1.0",
31
    "urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file,https,sftp",
32
    "urn:ietf:params:netconf:capability:validate:1.0",
33
    "urn:ietf:params:netconf:capability:xpath:1.0",
34
    "urn:liberouter:params:netconf:capability:power-control:1.0"
35
    "urn:ietf:params:netconf:capability:interleave:1.0"
36
    #'urn:ietf:params:netconf:capability:notification:1.0', # TODO    
37
]
38
"""A list of URI's representing the client's capabilities. This is used during the initial
39
capability exchange. Modify this if you need to announce some capability not already included.
40
"""
41

    
42
OPERATIONS = {
43
    "get": operations.Get,
44
    "get_config": operations.GetConfig,
45
    "edit_config": operations.EditConfig,
46
    "copy_config": operations.CopyConfig,
47
    "validate": operations.Validate,
48
    "commit": operations.Commit,
49
    "discard_changes": operations.DiscardChanges,
50
    "delete_config": operations.DeleteConfig,
51
    "lock": operations.Lock,
52
    "unlock": operations.Unlock,
53
    "close_session": operations.CloseSession,
54
    "kill_session": operations.KillSession,
55
    "poweroff_machine": operations.PoweroffMachine,
56
    "reboot_machine": operations.RebootMachine
57
}
58
"""Dictionary of method names and corresponding `~ncclient.operations.RPC` subclasses. It is used to
59
lookup operations, e.g. "get_config" is mapped to `~ncclient.operations.GetConfig`. It is thus
60
possible to add additional operations to the `Manager` API."""
61

    
62
def connect_ssh(*args, **kwds):
63
    """Initializes a NETCONF session over SSH, and creates a connected `Manager` instance. *host*
64
    must be specified, all the other arguments are optional and depend on the kind of host key
65
    verification and user authentication you want to complete.
66
        
67
    For the purpose of host key verification, on -NIX systems a user's :file:`~/.ssh/known_hosts`
68
    file is automatically considered. The *unknown_host_cb* argument specifies a callback that will
69
    be invoked when the server's host key cannot be verified. See
70
    :func:`~ncclient.transport.ssh.default_unknown_host_cb` for function signature.
71
    
72
    First, ``publickey`` authentication is attempted. If a specific *key_filename* is specified, it
73
    will be loaded and authentication attempted using it. If *allow_agent* is :const:`True` and an
74
    SSH agent is running, the keys provided by the agent will be tried. If *look_for_keys* is
75
    :const:`True`, keys in the :file:`~/.ssh/id_rsa` and :file:`~.ssh/id_dsa` will be tried. In case
76
    an encrypted key file is encountered, the *password* argument will be used as a decryption
77
    passphrase.
78
    
79
    If ``publickey`` authentication fails and the *password* argument has been supplied,
80
    ``password`` / ``keyboard-interactive`` SSH authentication will be attempted.
81
    
82
    :param host: hostname or address on which to connect
83
    :type host: `string`
84
    
85
    :param port: port on which to connect
86
    :type port: `int`
87
    
88
    :param timeout: timeout for socket connect
89
    :type timeout: `int`
90
    
91
    :param unknown_host_cb: optional; callback that is invoked when host key verification fails
92
    :type unknown_host_cb: `function`
93
    
94
    :param username: username to authenticate with, if not specified the username of the logged-in user is used
95
    :type username: `string`
96
    
97
    :param password: password for ``password`` authentication or passphrase for decrypting private key files
98
    :type password: `string`
99
    
100
    :param key_filename: location of a private key file on the file system
101
    :type key_filename: `string`
102
    
103
    :param allow_agent: whether to try connecting to SSH agent for keys
104
    :type allow_agent: `bool`
105
    
106
    :param look_for_keys: whether to look in usual locations for keys
107
    :type look_for_keys: `bool`
108
    
109
    :raises: :exc:`~ncclient.transport.SSHUnknownHostError`
110
    :raises: :exc:`~ncclient.transport.AuthenticationError`
111
    
112
    :rtype: `Manager`
113
    """    
114
    session = transport.SSHSession(capabilities.Capabilities(CAPABILITIES))
115
    session.load_known_hosts()
116
    session.connect(*args, **kwds)
117
    return Manager(session)
118

    
119
connect = connect_ssh
120
"Same as :func:`connect_ssh`, since SSH is the default (and currently, the only) transport."
121

    
122
class Manager(object):
123

    
124
    def __init__(self, session):
125
        self._session = session
126
        self._async_mode = False
127
        self._timeout = None
128
        self._raise_mode = 'all'
129

    
130
    def __enter__(self):
131
        return self
132

    
133
    def __exit__(self, *argss):
134
        self.close_session()
135
        return False
136

    
137
    def __getattr__(self, name):
138
        op = OPERATIONS.get(name, None)
139
        if op is None:
140
            raise AttributeError
141
        else:
142
            return op(self._session,
143
                      async=self._async_mode,
144
                      timeout=self._timeout,
145
                      raise_mode=self._raise_mode).request
146
    
147
    def locked(self, target):
148
        return operations.LockContext(self._session, target)
149
    
150
    @property
151
    def client_capabilities(self):
152
        return self._session._client_capabilities
153

    
154
    @property
155
    def server_capabilities(self):
156
        return self._session._server_capabilities
157

    
158
    @property
159
    def session_id(self):
160
        return self._session.id
161

    
162
    @property
163
    def connected(self):
164
        return self._session.connected
165

    
166
    def set_async_mode(self, mode):
167
        self._async_mode = mode
168

    
169
    def set_raise_mode(self, mode):
170
        assert(choice in ("all", "errors", "none"))
171
        self._raise_mode = mode
172

    
173
    async_mode = property(fget=lambda self: self._async_mode, fset=set_async_mode)
174

    
175
    raise_mode = property(fget=lambda self: self._raise_mode, fset=set_raise_mode)