forked from jathanism/netscaler-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetscaler.py
187 lines (144 loc) · 5.89 KB
/
netscaler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# module netscaler.py
#
# Special thanks to Allen Sanabria (asanabria@linuxdynasty.org) for the initial
# work on getting the API working with python-suds.
#
# Original post: http://tinyurl.com/yl4o6vq
#
"""
A container for interacting with a Citrix NetScaler application delivery
controller, utilizing the SOAP API to execute commands.
"""
__author__ = 'Jathan McCollum <jathan+bitbucket@gmail.com>'
import logging
from suds.client import Client, WebFault
from suds.xsd.doctor import Import, ImportDoctor
try:
import psyco
psyco.full()
except ImportError:
pass
# Register suds.client as a console handler... and disable it.
# This is necessary because sometimes suds.client can be chatty
# with warnings and it confuses end-users.
logging.basicConfig(level=logging.ERROR)
logging.getLogger('suds.client').setLevel(logging.ERROR)
logging.disable(logging.ERROR)
# Flip this if you want chatter
DEBUG = False
# The name of the default WSDL file.
DEFAULT_WSDL = 'NSConfig.wsdl'
# Commands/prefixes that don't modify the configuration on the device.
READONLY_COMMANDS = ('login', 'logout', 'get', 'save',)
__all__ = ['API', 'InteractionError']
class InteractionError(Exception):
"""Generic API error"""
def __init__(self, msg):
Exception.__init__(self, msg)
class API(object):
"""
Pass any kwargs to init that you would to the suds.client.Client constructor.
A little bit of magic is performed with the ImportDoctor to cover missing
types used in the WSDL.
* If you specify wsdl, this file will be pulled from the default http URL
* If you specify wsdl_url, it will override the wsdl file. Local
"file://" URLs work just fine.
* If you do not specify autosave, it will be enabled by default for
volatile operations.
To save time for re-usable code, it is a good idea subclassing this to
create methods for commonly used commands in your application. Example:
class MyAPI(netscaler.API):
def change_password(self, username, newpass):
return self.run("setsystemuser_password",
username=username, password=newpass)
"""
def __init__(self, host=None, wsdl_url=None, soap_url=None,
wsdl=DEFAULT_WSDL, autosave=True, **kwargs):
"""
Creates the suds.client.Client object and loads the WSDL.
Pass autosave=False to disable the auto-save feature.
"""
self.host = host
self.wsdl = wsdl
self.wsdl_url = wsdl_url or "http://%s/api/%s" % (self.host, self.wsdl)
self.soap_url = soap_url or "http://%s/soap/" % self.host
self.autosave = autosave
# fix missing types with ImportDoctor, otherwise we get:
# suds.TypeNotFound: Type not found: '(Array, # http://schemas.xmlsoap.org/soap/encoding/, )
self._import = Import('http://schemas.xmlsoap.org/soap/encoding/')
self._import.filter.add("urn:NSConfig")
self.doctor = ImportDoctor(self._import)
for key, value in kwargs.items():
# set attributes, but don't reset explicit ones.
if not hasattr(self, key):
if DEBUG: print "setting %s to %s" % (key, value)
setattr(self, key, value)
if DEBUG:
print 'wsdl_url:', self.wsdl_url
print 'soap_url:', self.soap_url
self.client = Client(self.wsdl_url, doctor=self.doctor, location=self.soap_url, **kwargs)
self.config_changed = False
self.logged_in = False
def __repr__(self):
return u'<NetScaler:API host:%s user:%s logged_in:%s>' % (self.host,
self.username,
self.logged_in)
def __str__(self):
"""Print me!"""
return str(self.client)
@property
def service(self):
return self.client.service
def is_readonly(self, cmd):
"""Validates whether a command is read-only based on READONLY_COMMANDS"""
ret = False
for ROC in READONLY_COMMANDS:
if cmd.startswith(ROC):
ret = True
return ret
def login(self):
"""Performs API login."""
resp = self.client.service.login(username=self.username, password=self.password)
if resp.rc != 0:
raise InteractionError(resp.message)
if DEBUG: print resp.message
self.logged_in = True
return True
def logout(self):
"""Performs API logout."""
resp = self.client.service.logout()
if resp.rc != 0:
raise InteractionError(resp.message)
if DEBUG: print resp.message
self.logged_in = False
return True
def save(self):
"""Saves NS Config."""
resp = self.client.service.savensconfig()
if resp.rc != 0:
raise InteractionError(resp.message)
if DEBUG: print resp.message
return True
def run(self, command, **kwargs):
"""
Runs the equivalent of self.client.service.command(**kwargs).
Will perform login() if self.logged_in == False.
Will perform save() on volatile operations if self.autosave == True.
"""
if not self.logged_in:
if DEBUG: print 'not logged in; logging you in.'
_login = self.login()
resp = getattr(self.client.service, command)(**kwargs)
if resp.rc != 0:
raise InteractionError(resp.message)
# Set this whenever a command is not read-only
if not self.is_readonly(command):
if DEBUG: print 'config changed; consider saving!'
self.config_changed = True
# Auto save if command changes config
if self.autosave and self.config_changed:
if DEBUG: print 'config changed; autosaving.'
self.save()
return resp