├── netscalertool ├── __init__.py ├── utils.py ├── netscalerapi.py └── netscalertool.py ├── .gitignore ├── requirements.txt ├── MANIFEST.in ├── Dockerfile ├── netscalertool.conf.example ├── python-netscalertool.spec ├── CONTRIBUTE.md ├── setup.py ├── README.rst ├── CLA.txt └── LICENSE.txt /netscalertool/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | build 4 | dist 5 | *.egg-info 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | PyYAML 2 | argparse 3 | httplib2 4 | setuptools 5 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CLA.txt 2 | include CONTRIBUTE.md 3 | include LICENSE.txt 4 | include netscalertool.conf.example 5 | include python-netscalertool.spec 6 | include README.rst 7 | include requirements.txt 8 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM centos:7 2 | 3 | RUN yum update -y && yum install python-setuptools -y 4 | 5 | RUN mkdir /var/log/netscaler-tool 6 | RUN touch /var/log/netscaler-tool/netscaler-tool.log 7 | 8 | COPY netscalertool.conf.example /etc/netscalertool.conf 9 | -------------------------------------------------------------------------------- /netscalertool.conf.example: -------------------------------------------------------------------------------- 1 | --- 2 | # NetScaler API user 3 | user: user 4 | 5 | # NetScaler API user's password 6 | passwd: passwd 7 | 8 | # List of lb vservers that can be managed 9 | manage_vservers: 10 | - vserver1 11 | - vserver1 12 | 13 | # External command that returns a newline separated list of 14 | # hosts that are allowed to be managed. If you don't care about limiting 15 | # which servers can be managed, leave this value empty 16 | #external_nodes: /usr/local/bin/servers --env development staging 17 | external_nodes: 18 | -------------------------------------------------------------------------------- /python-netscalertool.spec: -------------------------------------------------------------------------------- 1 | %{!?python_sitelib: %global python_sitelib %(%{__python} -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")} 2 | 3 | Name: python-netscaler-tool 4 | Version: 1.28.0 5 | Release: 1%{?dist} 6 | Summary: Managed Citrix NetScaler using Nitro API 7 | Source0: netscaler-tool-%{version}.tar.gz 8 | 9 | Group: Development/Tools 10 | License: Apache v2.0 11 | URL: http://www.github.com/tagged/netscaler-tool 12 | BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) 13 | 14 | BuildArch: noarch 15 | BuildRequires: python-devel 16 | Requires: python-argparse 17 | Requires: python-httplib2 18 | Requires: python-setuptools 19 | 20 | %description 21 | Managed Citrix NetScaler using Nitro API 22 | 23 | %prep 24 | %setup -q -n netscaler-tool-%{version} 25 | 26 | %build 27 | %{__python} setup.py build 28 | 29 | %install 30 | rm -rf $RPM_BUILD_ROOT 31 | %{__python} setup.py install -O1 --skip-build --root $RPM_BUILD_ROOT 32 | install -D netscalertool.conf.example $RPM_BUILD_ROOT/etc/netscalertool.conf 33 | mkdir -p $RPM_BUILD_ROOT/var/log/netscaler-tool/ 34 | 35 | %clean 36 | rm -rf $RPM_BUILD_ROOT 37 | 38 | %files 39 | %defattr(-,root,root,-) 40 | %{python_sitelib}/* 41 | %config /etc/netscalertool.conf 42 | /usr/bin/netscaler-tool 43 | /var/log/netscaler-tool 44 | 45 | %changelog 46 | -------------------------------------------------------------------------------- /netscalertool/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2014 Tagged Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | import json 17 | 18 | 19 | def print_list(list): 20 | """ 21 | Used for printing a list 22 | """ 23 | for entry in list: 24 | print entry 25 | 26 | return 0 27 | 28 | 29 | def print_items_json(dict, *args): 30 | """ 31 | Used for printing certain items of a dictionary in json form 32 | """ 33 | 34 | new_dict = {} 35 | # Testing to see if any attrs were passed in and if so only print those 36 | # key/values 37 | try: 38 | for key in args[0]: 39 | try: 40 | new_dict[key] = dict[key] 41 | except KeyError, e: 42 | msg = "%s is not a valid attr" % (e,) 43 | raise KeyError(msg) 44 | except KeyError: 45 | raise 46 | 47 | print json.dumps(new_dict) 48 | 49 | return 0 50 | -------------------------------------------------------------------------------- /CONTRIBUTE.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 1. Read and complete the [Contributor License Agreement](https://github.com/tagged/netscaler-tool/blob/master/CLA.txt). 3 | 1. When complete, email a PDF of the signed agreement to [legal@tagged.com](mailto:legal@tagged.com). 4 | 1. Once you have received a confirmation that your signed CLA was received, contribute your code, documentation, or any other materials with a pull request. 5 | 6 | ## Coding Style 7 | * PEP8 8 | * Indents are 4 whitespaces 9 | 10 | ### Add a new top level argument, i.e. show 11 | 1. Creating a new parser off of the main subparser 12 | 13 | ```parser_show = subparser.add_parser( 14 | 'show', help='sub-command for showing objects' 15 | )``` 16 | 17 | 18 | ### Add a new second level argument, i.e. lb-vservers 19 | 1. Create a new subparser off of parent subparser 20 | * `subparser_show = parser_show.add_subparsers(dest='subparser_name')` 21 | 1. Create parser 22 | 23 | subparser_show.add_parser('lb-vservers', help='Shows all lb vservers') 24 | 25 | * If the subparser will need an argument 26 | - 27 | ```parser_show_lbvserver.add_argument( 28 | 'vserver', help='Shows stats for specified vserver' 29 | )``` 30 | 31 | 1. Create new method under respective class 32 | 33 | def lbvservers(self): 34 | ns_object = ["lbvserver"] 35 | list_of_lbvservers = [] 36 | 37 | try: 38 | output = self.client.get_object(ns_object) 39 | except RuntimeError as e: 40 | msg = "Problem while trying to get list of LB vservers " \ 41 | "on %s.\n%s" % (self.args.host, e) 42 | raise RuntimeError(msg) 43 | 44 | for vserver in output['lbvserver']: 45 | list_of_lbvservers.append(vserver['name']) 46 | 47 | utils.print_list(sorted(list_of_lbvservers)) 48 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Copyright 2014 Tagged Inc. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | """ 18 | import sys 19 | 20 | from setuptools import setup, find_packages 21 | 22 | PYTHON_REQ_BLACKLIST = [] 23 | 24 | if sys.version_info >= (2, 7) or sys.version_info >= (3, 2): 25 | PYTHON_REQ_BLACKLIST.extend(['argparse', 'ordereddict']) 26 | 27 | if sys.version_info >= (2, 6) or sys.version_info >= (3, 1): 28 | PYTHON_REQ_BLACKLIST.append('simplejson') 29 | 30 | 31 | def load_requirements(fname): 32 | requirements = [] 33 | 34 | #TODO: use pkg_resources to grab the file (in case we're inside an archive) 35 | with open(fname, 'r') as reqfile: 36 | reqs = reqfile.read() 37 | 38 | for req in filter(None, reqs.strip().splitlines()): 39 | if any(req.startswith(bl) for bl in PYTHON_REQ_BLACKLIST): 40 | continue 41 | requirements.append(req) 42 | 43 | return requirements 44 | 45 | REQUIREMENTS = load_requirements('requirements.txt') 46 | LONG_DESCRIPTION = open('README.rst').read() 47 | 48 | setup( 49 | name='netscaler-tool', 50 | version='1.27.4', 51 | packages=find_packages(), 52 | 53 | author="Brian Glogower", 54 | author_email="bglogower@tagged.com", 55 | classifiers=[ 56 | 'Development Status :: 5 - Production/Stable', 57 | 'Environment :: Console', 58 | 'Intended Audience :: Developers', 59 | 'Intended Audience :: Information Technology', 60 | 'Intended Audience :: System Administrators', 61 | 'License :: OSI Approved :: Apache Software License', 62 | 'Natural Language :: English', 63 | 'Operating System :: Unix', 64 | 'Programming Language :: Python', 65 | 'Programming Language :: Python :: 2', 66 | 'Programming Language :: Python :: 2.6', 67 | 'Programming Language :: Python :: 2.7', 68 | 'Topic :: Internet', 69 | 'Topic :: Software Development', 70 | 'Topic :: Software Development :: Libraries :: Python Modules', 71 | 'Topic :: System :: Networking', 72 | 'Topic :: System :: Networking :: Monitoring', 73 | 'Topic :: System :: Operating System', 74 | 'Topic :: System :: Systems Administration', 75 | 'Topic :: Utilities', 76 | ], 77 | description="Nitro API tool for managing NetScalers.", 78 | entry_points={ 79 | 'console_scripts': [ 80 | 'netscaler-tool = netscalertool.netscalertool:main', 81 | ] 82 | }, 83 | install_requires=REQUIREMENTS, 84 | keywords=[ 85 | 'API', 86 | 'Automation', 87 | 'library', 88 | 'Nitro', 89 | 'Networking', 90 | 'NetScaler', 91 | ], 92 | license="Apache v2.0", 93 | long_description=LONG_DESCRIPTION, 94 | url="https://github.com/tagged/netscaler-tool", 95 | ) 96 | -------------------------------------------------------------------------------- /netscalertool/netscalerapi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2014 Tagged Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | 17 | import httplib2 18 | import json 19 | import urllib 20 | import socket 21 | 22 | 23 | class Client: 24 | def __init__(self, args): 25 | self.api_timeout = 10; 26 | for k, v in vars(args).iteritems(): 27 | setattr(self, k, v) 28 | 29 | 30 | def _call(self, method, path, payload=None, error_message=""): 31 | """ 32 | Dedupes much of the code necessary to facilitate api requests. 33 | """ 34 | 35 | url = "https://%s%s" % (self.host, path) 36 | 37 | headers = {'Content-type': 'application/json'} 38 | if 'session_id' in dir(self): 39 | headers['Cookie'] = 'sessionid='+self.session_id 40 | 41 | payload_encoded = json.dumps(payload) if payload else None 42 | 43 | http = httplib2.Http(disable_ssl_certificate_validation=True, timeout=self.api_timeout) 44 | try: 45 | response, content = http.request(url, method, body=payload_encoded, 46 | headers=headers) 47 | except socket.error, e: 48 | msg = "Problem connecting to NetScaler %s:\n%s" % (self.host, e) 49 | raise RuntimeError(msg) 50 | 51 | if len(content) > 0: 52 | data = json.loads(content) 53 | errorcode = data["errorcode"] 54 | else: 55 | data = None 56 | errorcode = 0 57 | 58 | if response.status not in [200, 201] or errorcode != 0: 59 | raise RuntimeError("%s: %s" % (error_message, content)) 60 | 61 | return data 62 | 63 | 64 | def login(self): 65 | """ 66 | Starts a session with the netscaler. 67 | """ 68 | 69 | path = "/nitro/v1/config/login" 70 | 71 | payload = {"login": {"username": self.user, "password": 72 | self.passwd}} 73 | 74 | data = self._call('POST', path, payload, 75 | error_message="Couldn't login") 76 | 77 | self.session_id = data["sessionid"] 78 | 79 | 80 | def logout(self): 81 | """ 82 | Logout of the netscaler 83 | """ 84 | 85 | path = "/nitro/v1/config/logout" 86 | 87 | payload = {"logout": {}} 88 | 89 | data = self._call('POST', path, payload, 90 | error_message="Couldn't logout") 91 | 92 | 93 | def save_config(self): 94 | """ 95 | Save netscaler config 96 | """ 97 | 98 | path = "/nitro/v1/config/nsconfig?action=save" 99 | 100 | payload = {"nsconfig": {}} 101 | 102 | self._call('POST', path, payload, 103 | error_message="Couldn't save config") 104 | 105 | 106 | def get_object(self, ns_object, *args): 107 | """ 108 | If we get stat in our optional args list, that means we need to change 109 | the url to handle fetching stat objects 110 | """ 111 | 112 | if 'stats' in args: 113 | path = "/nitro/v1/stat/%s" % ('/'.join(ns_object)) 114 | else: 115 | path = "/nitro/v1/config/%s" % ('/'.join(ns_object)) 116 | 117 | data = self._call('GET', path, 118 | error_message="Couldn't Get object") 119 | 120 | return data 121 | 122 | 123 | def enable_object(self, ns_object, properties): 124 | 125 | path = "/nitro/v1/config/%s?action=enable" % (ns_object) 126 | 127 | data = self._call('POST', path, properties, 128 | error_message="Couldn't enable object") 129 | 130 | 131 | def disable_object(self, ns_object, properties): 132 | 133 | path = "/nitro/v1/config/%s?action=disable" % (ns_object) 134 | 135 | data = self._call('POST', path, properties, 136 | error_message="Couldn't disable object") 137 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | netscaler-tool 2 | =============== 3 | 4 | System Requirements 5 | ------------------- 6 | 7 | - Python >= 2.6 and Python < 3 8 | - Python modules are in requirements.txt 9 | 10 | NetScaler Requirements 11 | ---------------------- 12 | 13 | - Known to work with NS12.1 14 | - System user account that has appropriate access 15 | - Depending on your use case, you might only need a system user that 16 | has read-only permissions 17 | 18 | Installation 19 | ------------ 20 | 21 | From PyPI 22 | ~~~~~~~~~ 23 | 24 | **Notes** 25 | 26 | - Don't forget to `modify <#configure>`__ **/etc/netscalertool.conf** 27 | after installation 28 | 29 | :: 30 | 31 | sudo pip install netscaler-tool 32 | sudo mkdir -p /var/log/netscaler-tool 33 | sudo touch /var/log/netscaler-tool/netscaler-tool.log 34 | sudo chown : /var/log/netscaler-tool/netscaler-tool.log 35 | sudo chmod /var/log/netscaler-tool/netscaler-tool.log 36 | sudo wget -O /etc/netscalertool.conf https://github.com/tagged/netscaler-tool/blob/master/netscalertool.conf.example 37 | 38 | From RPM 39 | ~~~~~~~~ 40 | 41 | **Notes** 42 | 43 | - Please replace **** with the version you wish to use 44 | - The rpm will create: 45 | 46 | 1. A sample **/etc/netscalertool.conf** that needs to be modified 47 | 2. Directory **/var/log/netscaler-tool**. It is up to you to create 48 | **/var/log/netscaler-tool/netscaler-tool.log** with the correct 49 | permissions 50 | 51 | 1. Download tar.gz specific version of the repo 52 | 53 | - ``https://github.com/tagged/netscaler-tool/releases/tag/v.tar.gz`` 54 | 55 | 2. Use included rpm spec (python-netscalertool.spec) file and newly 56 | downloaded tar.gz file to build a rpm 57 | 58 | 1. ``tar xzvf netscaler-tool-\.tar.gz netscaler-tool-\/python-netscalertool.spec`` 59 | 2. http://wiki.centos.org/HowTos/SetupRpmBuildEnvironment 60 | 61 | From Source 62 | ~~~~~~~~~~~ 63 | 64 | 1. git clone https://github.com/tagged/netscaler-tool.git 65 | 2. cd netscaler-tool 66 | 3. sudo python setup.py install 67 | 4. sudo mkdir -p /var/log/netscaler-tool 68 | 5. sudo touch /var/log/netscaler-tool/netscaler-tool.log 69 | 6. sudo chown : /var/log/netscaler-tool/netscaler-tool.log 70 | 7. sudo chmod /var/log/netscaler-tool/netscaler-tool.log 71 | 8. sudo cp netscalertool.conf.example /etc/netscalertool.conf 72 | 9. Modify /etc/netscalertool.conf 73 | 74 | Configuration 75 | ------------- 76 | 77 | 1. Update **user** to a NetScaler system user 78 | 2. Update **passwd** for the NetScaler system user 79 | 3. (Optional) 80 | 81 | - Update **manage\_vservers** with a list of vserver you want to 82 | manage 83 | - Update **external\_nodes** with a script that returns a newline 84 | separated list of nodes that are allowed to be managed. If not 85 | set, all nodes are manageable 86 | 87 | Usage 88 | ----- 89 | 90 | The netscaler-tool is really just a wrapper around netscalerapi.py. If 91 | you would like to write your own tool, but not have to worry about 92 | interacting with the NetScaler Nitro API, you can use netscalerapi.py. 93 | 94 | The netscaler-tool can take -h or --help optional argument at anytime: 95 | 96 | :: 97 | 98 | ./netscalertool.py --help 99 | usage: netscalertool.py [-h] [--user USER] [--passwd PASSWD] [--nodns] 100 | [--debug] [--dryrun] 101 | NETSCALER {show,stat,compare,enable,disable,bounce} 102 | ... 103 | 104 | positional arguments: 105 | NETSCALER IP or name of NetScaler. 106 | {show,stat,compare,enable,disable,bounce} 107 | show sub-command for showing objects 108 | stat sub-command for showing object stats 109 | compare sub-command for comparing objects 110 | enable sub-command for enable objects 111 | disable sub-command for disabling objects 112 | bounce sub-command for bouncing objects 113 | 114 | optional arguments: 115 | -h, --help show this help message and exit 116 | --user USER NetScaler user account. 117 | --passwd PASSWD Password for user. Default is to fetch from 118 | /etc/netscalertool.conf 119 | --nodns Won't try to resolve any NetScaler objects 120 | --debug Shows what's going on 121 | --dryrun Dryrun 122 | 123 | ./netscalertool.py 192.168.1.10 show --help 124 | usage: netscalertool.py NETSCALER show [-h] 125 | 126 | {lb-vservers,lb-vserver,cs-vservers,server,servers,services,primary-node,ssl-certs,saved-config,running-config,system} 127 | ... 128 | 129 | positional arguments: 130 | {lb-vservers,lb-vserver,cs-vservers,server,servers,services,primary-node,ssl-certs,saved-config,running-config,system} 131 | lb-vservers Shows all lb vservers 132 | lb-vserver Shows stat(s) of a specified lb vserver 133 | cs-vservers Shows all cs vservers 134 | server Shows server info 135 | servers Shows all servers 136 | services Shows all services 137 | primary-node Shows which of the two nodes is primary 138 | ssl-certs Shows ssl certs and days until expiring 139 | saved-config Shows saved ns config 140 | running-config Shows running ns config 141 | system Shows system counters 142 | 143 | optional arguments: 144 | -h, --help show this help message and exit 145 | 146 | -------------------------------------------------------------------------------- /CLA.txt: -------------------------------------------------------------------------------- 1 | Tagged Inc. 2 | Contributor License Agreement, v1.0 3 | http://www.tagged.com 4 | 5 | Thank you for your interest in contributing to Tagged Inc ("Tagged"). 6 | Tagged is very interested in receiving Your Contribution (defined 7 | below). In order to participate, we need to confirm how the rights 8 | in Your Contribution will be handled. Following the practices of 9 | other open source communities, Tagged requests that you grant Tagged a 10 | license, as indicated below, to the intellectual property rights in 11 | Your Contributions. Tagged requires that you have an executed Agreement 12 | on file prior to using any of Your Contributions. This helps us 13 | ensure that the intellectual property embodied within Tagged products 14 | remains unencumbered for use by the whole community. 15 | 16 | Please review and submit this Agreement per the instructions: 17 | https://github.com/tagged/netscaler-tool/blob/master/CONTRIBUTE.md 18 | 19 | Please read the following document carefully before signing and keep 20 | a copy for your records. 21 | 22 | Full name: ______________________________________________________ 23 | 24 | GitHub ID: ______________________________________________________ 25 | 26 | Mailing Address: ________________________________________________ 27 | 28 | ________________________________________________ 29 | 30 | Country: ________________________________________________________ 31 | 32 | Telephone: ______________________________________________________ 33 | 34 | Email: __________________________________________________________ 35 | 36 | (optional) Notify Project: ______________________________________ 37 | 38 | 39 | Terms and Conditions 40 | 41 | You accept and agree to the following terms and conditions for Your 42 | present and future Contributions submitted to Tagged, in consideration 43 | for the potential inclusion of Your Contributions in Tagged products. 44 | Except for the license and rights granted herein to Tagged and 45 | recipients of software distributed or otherwise made available by 46 | Tagged, You reserve all right, title, and interest in and to Your 47 | Contributions. 48 | 49 | 1. Definitions 50 | 51 | 1.1 "You" (or "Your") shall mean the copyright owner or legal 52 | entity authorized by the copyright owner that is making this 53 | Agreement with Tagged. For legal entities, the entity making a 54 | Contribution and all other entities that control, are controlled by, 55 | or are under common control with that entity are considered to be a 56 | single Contributor. For the purposes of this definition, "control" 57 | means (a) the power, direct or indirect, to cause the direction or 58 | management of such entity, whether by contract or otherwise, or (b) 59 | ownership of fifty percent (50%) or more of the outstanding shares, 60 | or (c) beneficial ownership of such entity. 61 | 62 | 1.2 "Contribution" means any original work of authorship 63 | (including software, documentation, or other material), including 64 | any modifications or additions to an existing work, that is 65 | intentionally submitted by You to Tagged for inclusion in, or 66 | documentation of, any of the products owned or managed by Tagged (the 67 | "Work"). For the purposes of this definition, "submitted" means any 68 | form of electronic, verbal, or written communication sent to Tagged or 69 | its representatives, including but not limited to communication on 70 | electronic mailing lists, source code control systems, and issue 71 | tracking systems that are managed by, or on behalf of, Tagged for the 72 | purpose of discussing and improving the Work, but excluding 73 | communication that is conspicuously marked or otherwise designated in 74 | writing by You as "Not a Contribution." 75 | 76 | 2. Grant of Copyright License. 77 | 78 | Subject to the terms and conditions of this Agreement, You hereby 79 | grant to Tagged and to recipients of software distributed by Tagged a 80 | perpetual, worldwide, non-exclusive, no-charge, royalty-free, 81 | irrevocable copyright license to reproduce, prepare derivative works 82 | of, publicly display, publicly perform, sublicense, and distribute 83 | Your Contributions and such derivative works. 84 | 85 | 3. Grant of Patent License. 86 | 87 | Subject to the terms and conditions of this Agreement, You hereby 88 | grant to Tagged and to recipients of software distributed by Tagged a 89 | perpetual, worldwide, non-exclusive, no-charge, royalty-free, 90 | irrevocable patent license to make, have made, use, offer to sell, 91 | sell, import, and otherwise transfer the Work, where such license 92 | applies only to those patent claims licensable by You that are 93 | necessarily infringed by Your Contribution(s) alone or by 94 | combination of Your Contribution(s) with the Work to which such 95 | Contribution(s) was submitted. 96 | 97 | 4. Representations 98 | 99 | 4.1 You represent that you are legally entitled to grant the 100 | above licenses under this Agreement, whether on behalf of Yourself 101 | (if you are an individual person) or on behalf of the entity that You 102 | represent (if You are an entity). If You are an individual and Your 103 | employer(s) has rights to intellectual property that You create that 104 | includes Your Contributions, You represent that You have received 105 | permission to make Contributions on behalf of that employer, that 106 | Your employer has waived such rights for Your Contributions to Tagged, 107 | or that Your employer has executed a separate Agreement with Tagged. 108 | 109 | 4.2 You represent that each of Your Contributions is Your 110 | original creation (see section 6 for submissions on behalf of 111 | others). You represent that Your Contribution submissions include 112 | complete details of any third-party license or other restriction 113 | (including, but not limited to, related patents and trademarks) of 114 | which you are personally aware and which are associated with any part 115 | of Your Contributions. 116 | 117 | 5. Support 118 | 119 | You are not expected to provide support for Your Contributions, 120 | except to the extent You desire to provide support. You may provide 121 | support for free, for a fee, or not at all. Unless required by 122 | applicable law or agreed to in writing, except as set forth in the 123 | other sections herein, You provide Your Contributions on an "AS IS" 124 | BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 125 | or implied, including, without limitation, any warranties or 126 | conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS 127 | FOR A PARTICULAR PURPOSE. 128 | 129 | 6. Work from Others 130 | 131 | Should You wish to submit work that is not Your original creation, 132 | You may submit it to Tagged separately from any Contribution, 133 | identifying the complete details of its source and of any license or 134 | other restriction (including, but not limited to, related patents, 135 | trademarks, and license agreements) of which you are personally 136 | aware, and conspicuously marking the work as "Submitted on behalf of 137 | a third-party: [named here]". 138 | 139 | 7. Changes 140 | 141 | You agree to notify Tagged promptly of any facts or circumstances of 142 | which you become aware that would make these representations 143 | inaccurate in any respect. 144 | 145 | 146 | 147 | Please sign: ________________________________________________________ 148 | 149 | Date: ________________________________________________________ 150 | 151 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /netscalertool/netscalertool.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Copyright 2014 Tagged Inc. 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | """ 18 | 19 | import argparse 20 | import json 21 | import logging 22 | import os 23 | import re 24 | import socket 25 | import subprocess 26 | import sys 27 | import time 28 | import yaml 29 | 30 | import netscalerapi 31 | import utils 32 | 33 | 34 | class Base(object): 35 | def __init__(self, args): 36 | self.args = args 37 | 38 | try: 39 | self.config = self.fetch_config() 40 | except IOError: 41 | raise 42 | 43 | # If the operator doesn't specify a user, let's grab it from the 44 | # config 45 | if not self.args.user: 46 | self.args.user = self.config['user'] 47 | 48 | # If the operator doesn't specify a passwd, let's grab it from the 49 | # config 50 | if not self.args.passwd: 51 | self.args.passwd = self.config['passwd'] 52 | 53 | # Creating a client instance 54 | try: 55 | self.client = netscalerapi.Client(args) 56 | except RuntimeError as e: 57 | msg = "Problem creating client instance.\n%s" % e 58 | raise RuntimeError(msg) 59 | 60 | # Login using client instance 61 | try: 62 | self.client.login() 63 | except RuntimeError: 64 | raise 65 | 66 | def fetch_config(self): 67 | """Fetch configuration from file""" 68 | try: 69 | f = open(self.args.ns_config_file) 70 | except IOError: 71 | raise 72 | 73 | config = yaml.load(f) 74 | f.close() 75 | 76 | # Returning passwd 77 | return config 78 | 79 | def get_bound_services(self, vserver): 80 | ns_object = ["lbvserver_binding", vserver] 81 | list_of_bound_services = [] 82 | 83 | try: 84 | output = self.client.get_object(ns_object) 85 | except RuntimeError as e: 86 | raise RuntimeError(e) 87 | 88 | for service in \ 89 | output['lbvserver_binding'][0]['lbvserver_service_binding']: 90 | list_of_bound_services.append(service['servicename']) 91 | 92 | list_of_bound_services.sort() 93 | return list_of_bound_services 94 | 95 | def get_saved_config(self): 96 | ns_object = ["nssavedconfig"] 97 | 98 | try: 99 | output = self.client.get_object(ns_object) 100 | except RuntimeError as e: 101 | msg = "There was a problem getting the saved config: %s" % e 102 | raise RuntimeError(msg) 103 | 104 | return output['nssavedconfig']['textblob'] 105 | 106 | def get_running_config(self): 107 | ns_object = ["nsrunningconfig"] 108 | 109 | try: 110 | output = self.client.get_object(ns_object) 111 | except RuntimeError as e: 112 | msg = "There was a problem getting the running config: %s" % e 113 | raise RuntimeError(msg) 114 | 115 | return output['nsrunningconfig']['response'] 116 | 117 | def get_lbvserver_service_binding(self, vserver): 118 | services_ips = {} 119 | 120 | ns_object = ["lbvserver_service_binding", vserver] 121 | try: 122 | services = self.client.get_object(ns_object) 123 | except RuntimeError as e: 124 | msg = "Problem while trying to get info about LB vserver %s on " \ 125 | "%s.\n%s" % (vserver, self.args.host, e) 126 | raise RuntimeError(msg) 127 | 128 | try: 129 | for service in services[ns_object[0]]: 130 | services_ips[str(service['servicename'])] = str( 131 | service['ipv46']) 132 | except KeyError: 133 | msg = "%s does not have any services bound to it." % vserver 134 | raise RuntimeError(msg) 135 | 136 | return services_ips 137 | 138 | def get_lb(self): 139 | attr = self.args.attr 140 | vserver = self.args.vserver 141 | 142 | ns_object = ["lbvserver", vserver] 143 | try: 144 | output = self.client.get_object(ns_object) 145 | except RuntimeError as e: 146 | msg = "Problem while trying to get info about LB vserver %s on " \ 147 | "%s.\n%s" % (vserver, self.args.host, e) 148 | raise RuntimeError(msg) 149 | 150 | return output[ns_object[0]][0], attr 151 | 152 | def get_server_binding(self, server): 153 | services = [] 154 | ns_object = ["server_binding", server] 155 | try: 156 | output = self.client.get_object(ns_object) 157 | except RuntimeError as e: 158 | msg = "Problem while trying to get server binding for server %s" \ 159 | " on %s.\n%s" % ( 160 | server, self.args.host, e) 161 | raise RuntimeError(msg) 162 | 163 | for service in output[ns_object[0]][0]['server_service_binding']: 164 | services.append(service['servicename']) 165 | 166 | return services 167 | 168 | def get_server_binding_service_details(self, server): 169 | ns_object = ["server_binding", server] 170 | 171 | try: 172 | output = self.client.get_object(ns_object) 173 | except RuntimeError as e: 174 | msg = "Problem while trying to get server binding for server %s" \ 175 | "on %s.\n%s" % (server, self.args.host, e) 176 | raise RuntimeError(msg) 177 | 178 | return output[ns_object[0]][0]['server_service_binding'] 179 | 180 | def vserver(self): 181 | pass 182 | 183 | 184 | class Stat(Base): 185 | def lbvservers(self): 186 | stat = self.args.stat 187 | ns_object = ["lbvserver"] 188 | 189 | try: 190 | output = self.client.get_object(ns_object, "stats") 191 | except RuntimeError as e: 192 | msg = "Could not get stat: %s on %s" % (e, self.args.host) 193 | raise RuntimeError(msg) 194 | 195 | for entry in output['lbvserver']: 196 | try: 197 | print json.dumps({entry['name']: entry[stat]}) 198 | except KeyError: 199 | msg = "%s is not a valid stat for lb vservers" % stat 200 | raise KeyError(msg) 201 | 202 | def ns(self): 203 | stats = self.args.stats 204 | ns_object = ["ns"] 205 | 206 | try: 207 | output = self.client.get_object(ns_object, "stats") 208 | except RuntimeError as e: 209 | msg = "Could not get stat: %s on %s" % (e, self.args.host) 210 | raise RuntimeError(msg) 211 | 212 | if stats: 213 | specified_stats = {} 214 | for stat in stats: 215 | try: 216 | specified_stats[stat] = output['ns'][stat] 217 | except KeyError: 218 | msg = "%s is not a valid stat for ns" % stat 219 | raise KeyError(msg) 220 | 221 | output['ns'] = specified_stats 222 | 223 | print json.dumps(output['ns']) 224 | 225 | 226 | class Show(Base): 227 | def server(self): 228 | server = self.args.server 229 | 230 | if self.args.services: 231 | try: 232 | ns_list = self.get_server_binding_service_details(server) 233 | except RuntimeError as e: 234 | msg = "Problem while trying to get list of services bound " \ 235 | "to %s.\n%s" % (server, e) 236 | raise RuntimeError(msg) 237 | 238 | for entry in ns_list: 239 | print json.dumps(entry) 240 | else: 241 | ns_object = ["server", server] 242 | try: 243 | output = self.client.get_object(ns_object) 244 | except RuntimeError as e: 245 | msg = "Problem while trying to get list of servers " \ 246 | "on %s.\n%s" % (self.args.host, e) 247 | raise RuntimeError(msg) 248 | 249 | print json.dumps(output['server'][0]) 250 | 251 | def servers(self): 252 | ns_object = ["server"] 253 | list_of_servers = [] 254 | 255 | try: 256 | output = self.client.get_object(ns_object) 257 | except RuntimeError as e: 258 | msg = "Problem while trying to get list of servers " \ 259 | "on %s.\n%s" % (self.args.host, e) 260 | raise RuntimeError(msg) 261 | 262 | for server in output['server']: 263 | list_of_servers.append(server['name']) 264 | 265 | utils.print_list(sorted(list_of_servers)) 266 | 267 | def services(self): 268 | ns_object = ["service"] 269 | list_of_services = [] 270 | 271 | try: 272 | output = self.client.get_object(ns_object) 273 | except RuntimeError as e: 274 | msg = "Problem while trying to get list of services " \ 275 | "on %s.\n%s" % (self.args.host, e) 276 | raise RuntimeError(msg) 277 | 278 | for service in output['service']: 279 | list_of_services.append(service['name']) 280 | 281 | utils.print_list(sorted(list_of_services)) 282 | 283 | def lbvservers(self): 284 | ns_object = ["lbvserver"] 285 | list_of_lbvservers = [] 286 | 287 | try: 288 | output = self.client.get_object(ns_object) 289 | except RuntimeError as e: 290 | msg = "Problem while trying to get list of LB vservers " \ 291 | "on %s.\n%s" % (self.args.host, e) 292 | raise RuntimeError(msg) 293 | 294 | for vserver in output['lbvserver']: 295 | list_of_lbvservers.append(vserver['name']) 296 | 297 | utils.print_list(sorted(list_of_lbvservers)) 298 | 299 | def lbvserver(self): 300 | vserver = self.args.vserver 301 | attr = self.args.attr 302 | services = self.args.services 303 | servers = self.args.servers 304 | 305 | if services: 306 | output = self.get_lbvserver_service_binding(vserver) 307 | for service in sorted(output.keys()): 308 | print service 309 | elif servers: 310 | output = self.get_lbvserver_service_binding(vserver) 311 | for service in sorted(output.keys()): 312 | try: 313 | # Looking up IPs via DNS instead of asking the Netscaler 314 | # for its service-to-server binding, since it is slow. 315 | print socket.gethostbyaddr(output[service])[0].split( 316 | '.')[0] 317 | except socket.herror as e: 318 | raise RuntimeError(e) 319 | else: 320 | output, attrs = self.get_lb() 321 | if attrs: 322 | utils.print_items_json(output, attr) 323 | else: 324 | print json.dumps(output) 325 | 326 | def csvservers(self): 327 | ns_object = ["csvserver"] 328 | list_of_cs_vservers = [] 329 | 330 | try: 331 | output = self.client.get_object(ns_object) 332 | except RuntimeError as e: 333 | msg = "Problem while trying to get list of CS vservers " \ 334 | "on %s.\n%s" % (self.args.host, e) 335 | raise RuntimeError(msg) 336 | 337 | for vserver in output['csvserver']: 338 | list_of_cs_vservers.append(vserver['name']) 339 | 340 | utils.print_list(sorted(list_of_cs_vservers)) 341 | 342 | def primarynode(self): 343 | ns_object = ["hanode"] 344 | 345 | try: 346 | output = self.client.get_object(ns_object) 347 | except RuntimeError as e: 348 | msg = "Problem while trying to get IP of primary node " \ 349 | "of %s.\n%s" % (self.args.host, e) 350 | raise RuntimeError(msg) 351 | 352 | # Grabbing the IP of the current primary 353 | print output['hanode'][0]['routemonitor'] 354 | 355 | def savedconfig(self): 356 | print self.get_saved_config() 357 | 358 | def runningconfig(self): 359 | print self.get_running_config() 360 | 361 | def get_service_stats(self, service, *args): 362 | mode = 'stats' 363 | ns_object = ["service", service] 364 | dict_of_service_stats = {} 365 | 366 | if args: 367 | ns_object.extend(args) 368 | 369 | try: 370 | output = self.client.get_object(ns_object, mode) 371 | except RuntimeError: 372 | raise 373 | 374 | for stat in args: 375 | try: 376 | dict_of_service_stats[stat] = output['service'][0][stat] 377 | except KeyError: 378 | msg = "%s is not a valid stat." % stat 379 | raise KeyError(msg) 380 | 381 | return dict_of_service_stats 382 | 383 | def sslcerts(self): 384 | ns_object = ["sslcertkey"] 385 | try: 386 | output = self.client.get_object(ns_object) 387 | except RuntimeError: 388 | raise 389 | 390 | if self.args.debug: 391 | print "\n:" 392 | for cert in output['sslcertkey']: 393 | print "%s:%s" % (cert['certkey'], cert['daystoexpiration']) 394 | 395 | def system(self): 396 | mode = 'stats' 397 | ns_object = ["system"] 398 | 399 | try: 400 | output = self.client.get_object(ns_object, mode) 401 | except RuntimeError: 402 | raise 403 | print json.dumps(output['system']) 404 | 405 | 406 | def cleanup_config(config, ignore_res): 407 | new_config = [] 408 | for line in config: 409 | if not re.match(ignore_res, line): 410 | new_config.append(line) 411 | 412 | return new_config 413 | 414 | 415 | class Compare(Base): 416 | def configs(self): 417 | # Regex that will be used to ignore lines we know are only in saved or 418 | # running configs, which will always show up in a diff. 419 | ignore_res = "^# Last modified|^set appfw|^set lb monitor https? HTTP" 420 | 421 | # Parsing configs and creating new lists that exclude any lines that 422 | # much ignore_res. 423 | saved = cleanup_config(self.get_saved_config().split('\n'), 424 | ignore_res) 425 | running = cleanup_config(self.get_running_config().split('\n'), 426 | ignore_res) 427 | 428 | # If the configs have differences, why have a problem 429 | if saved != running: 430 | # Converted lists to sets so we can find differences 431 | diff = set(saved) ^ set(running) 432 | 433 | # Returned the sets to lists for formatting purposes 434 | msg = "Saved and running configs are different:\n%s" \ 435 | % ('\n'.join(list(diff))) 436 | raise RuntimeError(msg) 437 | 438 | def lbvservers(self): 439 | vserver1 = self.args.vserver1 440 | vserver2 = self.args.vserver2 441 | 442 | # If the user tries to compare the same vservers 443 | if vserver1 == vserver2: 444 | msg = "%s and %s are the same vserver. Please pick two " \ 445 | "different vservers." % (vserver1, vserver2) 446 | raise RuntimeError(msg) 447 | 448 | # Getting a list of bound services to each vserver so that we 449 | # can compare. 450 | list_of_services1 = self.get_lbvserver_service_binding(vserver1) 451 | list_of_services2 = self.get_lbvserver_service_binding(vserver2) 452 | 453 | # If we get a diff, we will let the user know 454 | diff = set(list_of_services1) ^ set(list_of_services2) 455 | if diff: 456 | msg = "The following services are either bound to %s or %s but " \ 457 | "not both:\n%s" % (vserver1, vserver2, 458 | '\n'.join(sorted(list(diff)))) 459 | raise RuntimeError(msg) 460 | 461 | 462 | class Enable(Base): 463 | def server(self): 464 | server = self.args.server 465 | services = self.get_server_binding(server) 466 | 467 | if self.args.debug: 468 | print "\nServices bound to %s: %s" % (server, services) 469 | 470 | for service in services: 471 | properties = { 472 | 'service': {'name': str(service)}, 473 | } 474 | 475 | try: 476 | if self.args.debug: 477 | print "\nAttempting to enable service %s" % service 478 | self.client.enable_object('service', properties) 479 | except RuntimeError: 480 | raise 481 | 482 | def vserver(self): 483 | debug = self.args.debug 484 | sleep = self.args.sleep 485 | vserver = self.args.vserver 486 | 487 | properties = { 488 | 'vserver': {'name': str(vserver)}, 489 | } 490 | 491 | try: 492 | if debug: 493 | print "\nAttempting to enable vserver %s" % vserver 494 | if sleep: 495 | if debug: 496 | print "Sleeping %d seconds before enabling %s" % (sleep, 497 | vserver) 498 | time.sleep(sleep) 499 | self.client.enable_object('vserver', properties) 500 | except RuntimeError: 501 | raise 502 | 503 | super(Enable, self).vserver() 504 | 505 | 506 | class Disable(Base): 507 | def server(self): 508 | delay = self.args.delay 509 | server = self.args.server 510 | services = self.get_server_binding(server) 511 | 512 | if self.args.debug: 513 | print "\nServices bound to %s: %s" % (server, services) 514 | 515 | for service in services: 516 | properties = { 517 | 'service': { 518 | 'name': str(service), 519 | 'delay': delay, 520 | 'graceful': 'YES', 521 | }, 522 | } 523 | 524 | try: 525 | if self.args.debug: 526 | print "\nAttempting to disable service %s" % service 527 | self.client.disable_object('service', properties) 528 | except RuntimeError: 529 | raise 530 | 531 | def vserver(self): 532 | vserver = self.args.vserver 533 | 534 | properties = { 535 | 'vserver': {'name': str(vserver)}, 536 | } 537 | 538 | try: 539 | if self.args.debug: 540 | print "\nAttempting to disable vserver %s" % vserver 541 | self.client.disable_object('vserver', properties) 542 | except RuntimeError: 543 | raise 544 | 545 | super(Disable, self).vserver() 546 | 547 | 548 | class Bounce(Disable, Enable): 549 | def vserver(self): 550 | super(Bounce, self).vserver() 551 | 552 | 553 | # noinspection PyBroadException 554 | def main(): 555 | ns_config_file = "/etc/netscalertool.conf" 556 | log_file = "/var/log/netscaler-tool/netscaler-tool.log" 557 | 558 | ##### Setting up logging ##### 559 | # Grabbing the user that is running this script for logging purposes 560 | if os.getenv('SUDO_USER'): 561 | user = os.getenv('SUDO_USER') 562 | else: 563 | user = os.getenv('USER') 564 | 565 | try: 566 | local_host = socket.gethostname().split('.')[0] 567 | except (socket.herror, socket.gaierror): 568 | local_host = 'localhost' 569 | logger = logging.getLogger(local_host) 570 | logger.setLevel(logging.DEBUG) 571 | 572 | try: 573 | ch = logging.FileHandler(log_file) 574 | except IOError as e: 575 | print >> sys.stderr, e 576 | sys.exit(1) 577 | 578 | ch.setLevel(logging.DEBUG) 579 | formatter = logging.Formatter( 580 | '%(asctime)s %(name)s - %(levelname)s - %(message)s', 581 | datefmt='%b %d %H:%M:%S' 582 | ) 583 | ch.setFormatter(formatter) 584 | logger.addHandler(ch) 585 | ##### Setting up logging ##### 586 | 587 | class IsPingableAction(argparse.Action): 588 | """ 589 | Used by argparse to check if the NetScaler specified is pingable 590 | """ 591 | 592 | def __call__(self, parser, namespace, values, option_string=None): 593 | ping_cmd = "ping -c 1 -W 2 %s" % values 594 | process = subprocess.call( 595 | ping_cmd.split(), stdout=subprocess.PIPE, 596 | stderr=subprocess.PIPE 597 | ) 598 | 599 | setattr(namespace, self.dest, values) 600 | 601 | class AllowedToManage(argparse.Action): 602 | """ 603 | Used by argparse to checks if NetScaler object is allowed to be managed 604 | """ 605 | 606 | def __call__(self, parser, namespace, values, option_string=None): 607 | ns_config_file = namespace.ns_config_file 608 | 609 | try: 610 | f = open(ns_config_file, 'r') 611 | ns_config = yaml.load(f) 612 | f.close() 613 | except IOError as e: 614 | msg = "Problem with %s: %s" % (ns_config_file, e) 615 | print >> sys.stderr, msg 616 | sys.exit(1) 617 | 618 | if namespace.subparser_name == "server": 619 | # Checking if specified server is allowed to be managed 620 | try: 621 | cmd = ns_config["external_nodes"] 622 | try: 623 | msg = "Running \"%s\" to get a list of manageable " \ 624 | "servers" % cmd 625 | logger.info(msg) 626 | manageable_servers = subprocess.check_output( 627 | cmd.split() 628 | ) 629 | except (OSError, subprocess.CalledProcessError) as e: 630 | msg = "Problem running %s:\n%s" % (cmd, e) 631 | print >> sys.stderr, msg 632 | logger.critical(msg) 633 | sys.exit(1) 634 | 635 | if values not in manageable_servers.split('\n'): 636 | msg = "%s is not a manageable server. If you would " \ 637 | "like to change this, please update " \ 638 | "external_nodes in %s" % (values, ns_config_file) 639 | print >> sys.stderr, msg 640 | logger.error(msg) 641 | sys.exit(1) 642 | except KeyError: 643 | msg = "external_nodes not set in %s. All servers are " \ 644 | "allowed to be managed" % ns_config_file 645 | logger.info(msg) 646 | 647 | # Checking if specified vserver is allowed to be managed 648 | elif namespace.subparser_name == "vserver": 649 | if values not in ns_config["manage_vservers"]: 650 | msg = "%s is a vserver that is not allowed to be " \ 651 | "managed. If you would like to change this, " \ 652 | "please update %s." % ( 653 | values, ns_config_file) 654 | print >> sys.stderr, msg 655 | logger.info(msg) 656 | sys.exit(1) 657 | 658 | setattr(namespace, self.dest, values) 659 | 660 | # Create parser 661 | parser = argparse.ArgumentParser() 662 | 663 | # Setting some defaults 664 | parser.set_defaults(ns_config_file=ns_config_file) 665 | parser.set_defaults(log_file=log_file) 666 | 667 | parser.add_argument( 668 | "host", metavar='NETSCALER', action=IsPingableAction, help="IP or \ 669 | DNS name of NetScaler" 670 | ) 671 | parser.add_argument( 672 | "--api-timeout", help="HTTP API Timeout (seconds)", type=float, default=10, 673 | ) 674 | parser.add_argument("--user", help="NetScaler user account") 675 | parser.add_argument( 676 | "--passwd", dest="passwd", help="Password for user. Default is to \ 677 | fetch from /etc/netscalertool.conf" 678 | ) 679 | parser.add_argument( 680 | "--nodns", action="store_true", help="Won't try to resolve any " 681 | "NetScaler objects", default=False 682 | ) 683 | parser.add_argument( 684 | "--debug", action="store_true", help="Shows what's \ 685 | going on", default=False 686 | ) 687 | parser.add_argument( 688 | "--dryrun", action="store_true", help="Dryrun", default=False) 689 | 690 | # Creating subparser. 691 | subparser = parser.add_subparsers(dest='top_subparser_name') 692 | 693 | # Creating show subparser. 694 | parser_show = subparser.add_parser( 695 | 'show', help='sub-command for showing objects' 696 | ) 697 | subparser_show = parser_show.add_subparsers(dest='subparser_name') 698 | subparser_show.add_parser('lb-vservers', help='Shows all lb vservers') 699 | parser_show_lbvserver = subparser_show.add_parser( 700 | 'lb-vserver', help='Shows stat(s) of a specified lb vserver' 701 | ) 702 | parser_show_lbvserver.add_argument( 703 | 'vserver', help='Shows stats for specified vserver' 704 | ) 705 | parser_show_lbvserver_group = parser_show_lbvserver \ 706 | .add_mutually_exclusive_group() 707 | parser_show_lbvserver_group.add_argument( 708 | '--attr', dest='attr', nargs='*', help='Shows only the specified \ 709 | attribute(s)' 710 | ) 711 | parser_show_lbvserver_group.add_argument( 712 | '--services', action='store_true', help='Shows services bound to \ 713 | specified lb vserver' 714 | ) 715 | parser_show_lbvserver_group.add_argument( 716 | '--servers', action='store_true', help='Shows servers bound to \ 717 | specified lb vserver' 718 | ) 719 | subparser_show.add_parser('cs-vservers', help='Shows all cs vservers') 720 | parser_show_server = subparser_show.add_parser( 721 | 'server', help='Shows server info' 722 | ) 723 | parser_show_server.add_argument('server', help='Shows server details') 724 | parser_show_server.add_argument( 725 | '--services', action='store_true', help='Shows services bound to \ 726 | server and their status' 727 | ) 728 | subparser_show.add_parser('servers', help='Shows all servers') 729 | subparser_show.add_parser('services', help='Shows all services') 730 | subparser_show.add_parser( 731 | 'primary-node', help='Shows which of the two nodes is primary' 732 | ) 733 | subparser_show.add_parser( 734 | 'ssl-certs', help='Shows ssl certs and days until expiring' 735 | ) 736 | subparser_show.add_parser('saved-config', help='Shows saved ns config') 737 | subparser_show.add_parser('running-config', 738 | help='Shows running ns config') 739 | subparser_show.add_parser('system', help='Shows system counters') 740 | 741 | # Creating stat subparser 742 | parser_stat = subparser.add_parser( 743 | 'stat', help='sub-command for showing ns_object stats' 744 | ) 745 | subparser_stat = parser_stat.add_subparsers(dest='subparser_name') 746 | parser_stat_lb_vservers = subparser_stat.add_parser( 747 | 'lb-vservers', help='Show one statistic of all lbvservers' 748 | ) 749 | parser_stat_lb_vservers.add_argument( 750 | 'stat', help='Select specific stat to display' 751 | ) 752 | parser_stat_ns = subparser_stat.add_parser( 753 | 'ns', help='Shows statistics for NetScaler' 754 | ) 755 | parser_stat_ns.add_argument( 756 | '--stats', nargs='*', help='Select NetScaler statistics to show' 757 | ) 758 | 759 | # Creating compare subparser. 760 | parser_cmp = subparser.add_parser( 761 | 'compare', help='sub-command for comparing objects' 762 | ) 763 | subparser_cmp = parser_cmp.add_subparsers(dest='subparser_name') 764 | subparser_cmp.add_parser( 765 | 'configs', help='Compares running and saved ns configs' 766 | ) 767 | parser_cmp_lbvservers = subparser_cmp.add_parser( 768 | 'lb-vservers', help='Compares configs between two vservers' 769 | ) 770 | parser_cmp_lbvservers.add_argument('vserver1', metavar='VSERVER1') 771 | parser_cmp_lbvservers.add_argument('vserver2', metavar='VSERVER2') 772 | 773 | # Creating enable subparser. 774 | parser_enable = subparser.add_parser( 775 | 'enable', help='sub-command for enable objects' 776 | ) 777 | subparser_enable = parser_enable.add_subparsers(dest='subparser_name') 778 | parser_enable_server = subparser_enable.add_parser( 779 | 'server', 780 | help='Enable server. Will actually enable all services bound to ' 781 | 'server' 782 | ) 783 | parser_enable_server.add_argument( 784 | 'server', action=AllowedToManage, help='Server to enable' 785 | ) 786 | parser_enable_vserver = subparser_enable.add_parser( 787 | 'vserver', help='Enable vserver' 788 | ) 789 | parser_enable_vserver.add_argument( 790 | 'vserver', action=AllowedToManage, help='Vserver to enable' 791 | ) 792 | 793 | # Creating disable subparser. 794 | parser_disable = subparser.add_parser( 795 | 'disable', help='sub-command for disabling objects' 796 | ) 797 | subparser_disable = parser_disable.add_subparsers(dest='subparser_name') 798 | parser_disable_server = subparser_disable.add_parser( 799 | 'server', help='Disable server' 800 | ) 801 | parser_disable_server.add_argument( 802 | 'server', action=AllowedToManage, help='Server to disable. actually ' 803 | 'disable all services bound to server, to utilize the graceful delay' 804 | ) 805 | parser_disable_server.add_argument( 806 | '--delay', type=int, help='The time allowed (in seconds) for a \ 807 | graceful shutdown. Defaults to 3 seconds', default=3 808 | ) 809 | parser_disable_vserver = subparser_disable.add_parser( 810 | 'vserver', help='Disable vserver' 811 | ) 812 | parser_disable_vserver.add_argument( 813 | 'vserver', action=AllowedToManage, help='Vserver to disable' 814 | ) 815 | 816 | # Creating bounce subparser 817 | parser_bounce = subparser.add_parser( 818 | 'bounce', help='sub-command for bouncing objects' 819 | ) 820 | subparser_bounce = parser_bounce.add_subparsers(dest='subparser_name') 821 | parser_bounce_vserver = subparser_bounce.add_parser( 822 | 'vserver', help='Bounce vserver' 823 | ) 824 | parser_bounce_vserver.add_argument( 825 | 'vserver', action=AllowedToManage, help='Vserver to bounce' 826 | ) 827 | parser_bounce_vserver.add_argument('--sleep', type=int, help='Amount of ' 828 | 'time to sleep between disabling and ' 829 | 'enabling vserver') 830 | 831 | # Getting arguments 832 | args = parser.parse_args() 833 | 834 | # Initialize exit return value to 0 835 | retval = 0 836 | 837 | # Showing user flags and their values 838 | if args.debug: 839 | print "Using the following args:" 840 | for arg in dir(args): 841 | regex = "(^_{1,2}|^read_file|^read_module|^ensure_value)" 842 | if re.match(regex, arg): 843 | continue 844 | else: 845 | print "\t%s: %s" % (arg, getattr(args, arg)) 846 | print 847 | 848 | # Getting method, based on subparser called from argparse. 849 | method = args.subparser_name.replace('-', '') 850 | 851 | # Getting class, based on subparser called from argparse. 852 | try: 853 | klass = globals()[args.top_subparser_name.capitalize()] 854 | except KeyError: 855 | msg = "%s, %s is not a valid subparser." % (user, 856 | args.top_subparser_name) 857 | print >> sys.stderr, msg 858 | logger.critical(msg) 859 | return 1 860 | 861 | # Remove password entry, since this info will be sent to a log 862 | modified_args = vars(args).copy() 863 | modified_args['passwd'] = "*****" 864 | msg = "%s will try to execute \'%s\' on %s" % ( 865 | user, modified_args, modified_args['host']) 866 | logger.info(msg) 867 | 868 | try: 869 | netscaler_tool = klass(args) 870 | except: 871 | print >> sys.stderr, sys.exc_info()[1] 872 | logger.critical(sys.exc_info()[1]) 873 | return 1 874 | 875 | try: 876 | try: 877 | getattr(netscaler_tool, method)() 878 | except (AttributeError, RuntimeError, KeyError, IOError): 879 | msg = "%s, %s" % (user, sys.exc_info()[1]) 880 | print >> sys.stderr, msg 881 | logger.critical(msg) 882 | retval = 1 883 | finally: 884 | # Saving config if we run a enable or disable command 885 | if args.top_subparser_name in ["bounce", "disable", "enable"]: 886 | try: 887 | netscaler_tool.client.save_config() 888 | logger.info("Saving NetScaler config") 889 | except RuntimeError as e: 890 | print >> sys.stderr, e 891 | logger.critical(e) 892 | retval = 1 893 | 894 | # Logging out of NetScaler. 895 | try: 896 | netscaler_tool.client.logout() 897 | if args.debug: 898 | msg = "Logging out of NetScaler %s" % args.host 899 | logger.debug(msg) 900 | print "\n", msg 901 | except RuntimeError as e: 902 | msg = "%s, %s" % (user, e) 903 | print >> sys.stderr, msg 904 | logger.warn(msg) 905 | retval = 1 906 | 907 | # Exiting program 908 | return retval 909 | 910 | 911 | # Run the script only if the script itself is called directly. 912 | if __name__ == '__main__': 913 | sys.exit(main()) 914 | --------------------------------------------------------------------------------