示例#1
0
def	Login(nsip,name='nsroot',passwd='nsroot',timeout=500) :
        print 'Login {}'.format(nsip)
        try :
                ns = NITROSVC.nitro_service(nsip)
                ns.timeout = timeout
                ns.set_credential(name,passwd)
                ns.login()

                DUT.SESSION = ns
                if not GetIPS(ns) :
                        return None

                if not DUT.NSIP :
                        raise TestException(103)
                elif not DUT.SNIP :
                        raise TestException(101)
                elif not DUT.VIP :
                        raise TestException(102)
                
        except requests.ConnectionError as e :
                print 'e.message'
                ns = None
        except nitro_exception as e :
                print 'e.message'
                ns = None
        except TestException as e:
                print 'e.message'
                ns = None
        except ValueError as e:
                print 'e.message'
                ns = None
        return ns
示例#2
0
def ns_session_login_handler():
    """ This method creates Nitro session and returns its handle """
    try:
        ip_port = '127.0.0.1' + ':' + '9080'
        logging.info(
            "Processing request to establish Nitro session for NS IP {}".
            format(ip_port))
        ns_session = nitro_service(ip_port, 'http')
        ns_session.certvalidation = False
        ns_session.hostnameverification = False
        ns_session.set_credential('nsroot', 'nsroot')
        ns_session.timeout = 600
        ns_session.login()
        call_nitro_commands(ns_session)
        logging.info('Configuration completed')
        logging.info(
            "Finished processing request to establish Nitro session for NS IP {}"
            .format(ip_port))
        return ns_session
    except nitro_exception as nitroe:
        logging.error("Nitro Exception::login_logout::errorcode=" +
                      str(nitroe.errorcode) + ",message=" + nitroe.message)
        return None
    except requests.exceptions.ConnectionError as e:
        logging.error(
            "Received requests.exceptions.ConnectionError Exception: {}".
            format(e))
        logging.error("Exception: %s" % e.message)
        return None
    except Exception as e:
        logging.error("Exception: %s" % e.message)
        return None
示例#3
0
    def __init__(self, ns, username, password):
        '''Initializes a session and stores it as self._sess for future use for all other functions.
		
		@param ns - Netscaler IP or FQDN
		@param username
		@param password
		'''

        #Create an instance of the nitro_service class to connect to the appliance
        self._sess = nitro_service(ns, 'HTTPS')
        self._sess.certvalidation = False  # docs say false but that'd fail
        # self._sess.hostnameverification = False # debating

        self._sess.set_credential(username, password)
        # For bulk operations we want to rollback
        self._sess.onerror = 'ROLLBACK'
        self._sess.timeout = 1800  # Default but it doesn't get set so we do it explicitly

        try:
            self._sess.login()
        except nitro_exception as e:
            print('Exception::errorcode=' + str(e.errorcode) + ',message=' +
                  e.message)
        except Exception as e:
            print('Exception::message=' + str(e.args))
        return
示例#4
0
def get_nitro_client(module):
    from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service

    if module.params['mas_proxy_call']:

        try:
            from nssrc.com.citrix.netscaler.nitro.service.MasContext import MasContext
        except ImportError as e:
            module.fail_json(
                msg=
                'The currently installed nitro python SDK does not support MAS proxied calls'
            )

        if module.params['mas_auth_token'] is None:
            module.fail_json(
                msg=
                'You must provide a mas authentication token to proxy a call trough MAS'
            )
        if module.params['instance_ip'] is None:
            module.fail_json(
                msg=
                'You must provide  the target NS instance ip to proxy a call trough MAS'
            )

        masCtx = MasContext(
            module.params['mas_ip'],
            module.params['mas_auth_token'],
            module.params['instance_ip'],
        )

        client = nitro_service(masCtx, module.params['nitro_protocol'])
    else:
        if module.params['nitro_user'] is None:
            module.fail_json(msg='You must provide a valid nitro user name')

        if module.params['nitro_pass'] is None:
            module.fail_json(msg='You must provide a valid nitro password')

        client = nitro_service(module.params['nsip'],
                               module.params['nitro_protocol'])
        client.set_credential(module.params['nitro_user'],
                              module.params['nitro_pass'])

    client.timeout = float(module.params['nitro_timeout'])
    client.certvalidation = module.params['validate_certs']

    return client
示例#5
0
def get_nitro_client(module):
    from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service

    client = nitro_service(module.params['nsip'], module.params['nitro_protocol'])
    client.set_credential(module.params['nitro_user'], module.params['nitro_pass'])
    client.timeout = float(module.params['nitro_timeout'])
    client.certvalidation = module.params['validate_certs']
    return client
def get_nitro_client(module):
    from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service

    client = nitro_service(module.params['nsip'], module.params['nitro_protocol'])
    client.set_credential(module.params['nitro_user'], module.params['nitro_pass'])
    client.timeout = float(module.params['nitro_timeout'])
    client.certvalidation = module.params['validate_certs']
    return client
示例#7
0
    def main(cls, args_):
        if (len(args_) < 3):
            print("Usage: run.bat <ip> <username> <password>")
            return

        config = MyFirstNitroApplication()
        config.ip = args_[1]
        config.username = args_[2]
        config.password = args_[3]

        try:

            #Create an instance of the nitro_service class to connect to the appliance
            ns_session = nitro_service(config.ip, "HTTP")

            ns_session.set_credential(
                config.username,
                config.password)  #to make arguments more generic
            ns_session.timeout = 310
            #Log on to the appliance using your credentials
            ns_session.login()

            #Enable the load balancing feature.
            features_to_be_enabled = "lb"
            ns_session.enable_features(features_to_be_enabled)

            #Create an instance of the virtual server class
            new_lbvserver_obj = lbvserver()

            #Create a new virtual server
            new_lbvserver_obj.name = "MyFirstLbVServer"
            new_lbvserver_obj.ipv46 = "10.102.29.88"
            new_lbvserver_obj.servicetype = "HTTP"
            new_lbvserver_obj.port = 80
            new_lbvserver_obj.lbmethod = "ROUNDROBIN"
            lbvserver.add(ns_session, new_lbvserver_obj)

            #Retrieve the details of the virtual server
            new_lbvserver_obj = lbvserver.get(ns_session,
                                              new_lbvserver_obj.name)
            print("Name : " + new_lbvserver_obj.name + "\n" + "Protocol : " +
                  new_lbvserver_obj.servicetype)

            #Delete the virtual server
            lbvserver.delete(ns_session, new_lbvserver_obj.name)

            #Save the configurations
            ns_session.save_config()

            #Logout from the NetScaler appliance
            ns_session.logout()

        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
示例#8
0
	def main(cls, args_):
		if(len(args_) < 4):
			print("Usage: run.bat <ip> <username> <password> <pattern-set-name>")
			return

		config = NitroApp()
		config.ip = args_[1]
		config.username = args_[2]
		config.password = args_[3]
		config.patset = args_[4]
		
		try :
			
			#Create an instance of the nitro_service class to connect to the appliance
			ns_session = nitro_service(config.ip,"HTTP")
			
			ns_session.set_credential(config.username,config.password) #to make arguments more generic
			ns_session.timeout = 500
			#Log on to the appliance using your credentials

			print("Logging into NetScaler at " + config.ip + " with userid " + config.username)

			
			ns_session.login()
			
                        print("Looking for a pattern named " + config.patset)


			patset_list = policypatset.get(ns_session)


                        for patset_obj in patset_list :
                           if patset_obj.name == config.patset :
			      print("Deleting patset named " + patset_obj.name)
                              policypatset.delete(ns_session, patset_obj)
			      
                              #Uncomment the lines below to save the configurations
			      # print("Saving the configuration.")
			      # ns_session.save_config()

                              # Comment the line below if you choose to save the configuration.
			      print("The running configuration was NOT saved.")

                              break
                        else: 
                           print("patset " + config.patset + " was not found in the configuration.")
                        print ("Logging out")
			
			
			
			#Logout from the NetScaler appliance
			ns_session.logout()
			
		except nitro_exception as  e:
			print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
		except Exception as e:         
			print("Exception::message="+str(e.args))
		return
示例#9
0
  def NSlogin(nsip, username, password):
    # Create an instance of the nitro_service class to connect to the appliance
    ns_session = nitro_service(nsip,"HTTP")
    ns_session.set_credential(username, password)
    ns_session.timeout = 310

    # Log on to the appliance using your credentials
    ns_session.login()
    return ns_session
示例#10
0
def get_nitro_client():
    from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service

    client = nitro_service(nitro_dict['nsip'], 'HTTP')
    client.set_credential(nitro_dict['nitro_user'], nitro_dict['nitro_pass'])
    client.timeout = 320.0
    client.certvalidation = False
    client.login()
    return client
示例#11
0
 def login_logout(self, *args, **kwargs):
     self.ns_session = nitro_service(self.nsip, 'HTTP')
     self.ns_session.set_credential(self.nslogin, self.nspasswd)
     self.ns_session.timeout = 600
     self.ns_session.login()
     result = func(self, *args, **kwargs)
     self.ns_session.logout()
     self.ns_session = None
     return result
示例#12
0
 def login_logout(self, *args, **kwargs):
     self.ns_session = nitro_service(self.nsip, 'HTTP')
     self.ns_session.set_credential(self.nslogin, self.nspasswd)
     self.ns_session.timeout = 600
     self.ns_session.login()
     result = func(self, *args, **kwargs)
     self.ns_session.logout()
     self.ns_session = None
     return result
    def NSlogin(nsip, username, password):
        # Create an instance of the nitro_service class to connect to the
        # appliance
        ns_session = nitro_service(nsip, "HTTP")
        ns_session.set_credential(username, password)
        ns_session.timeout = 310

        # Log on to the appliance using your credentials
        ns_session.login()
        return ns_session
示例#14
0
 def login_logout(self, *args, **kwargs):
     logger.info("Logging into nitro api")
     self.ns_session = nitro_service(self.nsip, 'HTTP')
     self.ns_session.set_credential(self.nslogin, self.nspasswd)
     self.ns_session.timeout = 60
     self.ns_session.login()
     result = func(self, *args, **kwargs)
     self.ns_session.logout()
     self.ns_session = None
     logger.info("Request complete against nitro api")
     return result
	def main(cls, args_):
		if(len(args_) < 3):
			print("Usage: run.bat <ip> <username> <password>")
			return

		config = MyFirstNitroApplication()
		config.ip = args_[1]
		config.username = args_[2]
		config.password = args_[3] 
		
		try :
			
			#Create an instance of the nitro_service class to connect to the appliance
			ns_session = nitro_service(config.ip,"HTTP")
			
			ns_session.set_credential("nsroot", "nsroot")
			ns_session.timeout = 310
			#Log on to the appliance using your credentials
			ns_session.login()
			
			#Enable the load balancing feature.
			features_to_be_enabled = "lb"			
			ns_session.enable_features(features_to_be_enabled)
			
			#Create an instance of the virtual server class
			new_lbvserver_obj = lbvserver()
			
			#Create a new virtual server
			new_lbvserver_obj.name = "MyFirstLbVServer"
			new_lbvserver_obj.ipv46 = "10.102.29.88"
			new_lbvserver_obj.servicetype = "HTTP"
			new_lbvserver_obj.port = 80
			new_lbvserver_obj.lbmethod = "ROUNDROBIN"
			lbvserver.add(ns_session, new_lbvserver_obj)
					
			#Retrieve the details of the virtual server
			new_lbvserver_obj = lbvserver.get(ns_session,new_lbvserver_obj.name)
			print("Name : " +new_lbvserver_obj.name +"\n" +"Protocol : " +new_lbvserver_obj.servicetype)

			#Delete the virtual server
			lbvserver.delete(ns_session, new_lbvserver_obj.name)
			
			#Save the configurations
			ns_session.save_config()
			
			#Logout from the NetScaler appliance
			ns_session.logout()
			
		except nitro_exception as  e:
			print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
		except Exception as e:         
			print("Exception::message="+str(e.args))
		return
示例#16
0
    def csvserver_method(cls, args_):

        #config = get_state()
        # config.ip = IPAddress
        # config.username = UserName
        # config.password = PassWord
        # if(len(args_) < 3):
        # 	print("Usage:run.bat <ip> <username> <password>")
        # 	return

        config = cs_get_stat()
        config.ip = args_[0]
        config.username = args_[1]
        config.password = args_[2]
        client = None

        try:
            client = nitro_service(config.ip, "http")
            client.set_credential(config.username, config.password)
            client.timeout = 500
            print("Input an parament:")
            print(
                "  name  <-------> Name of the content switching virtual server"
            )
            print("  state <-------> The state of the server")
            print(
                "  ip    <-------> The IP address on which the service is running"
            )
            print("  port  <-------> The port on which the service is running")
            print("  hits  <-------> The total vserver hits")
            print(
                "  all   <-------> The whole information of the content switching virtual server"
            )
            parament1 = raw_input("Your input is:")
            print("****************************************")
            config.run_state(client, parament1)
            print("****************************************")
            #print("Input the csvserver name:")
            parament2 = raw_input("Input the csvserver name:")
            print("<<------------------------------------->>")
            config.run_csvserver_name(client, parament2)

            #print("sessionID=" + client.sessionid)			#get sessionid, used for login
            # if client.isLogin():
            # 	config.run_sample2(client)
            client.logout()

        except nitro_exception as e:
            print("Exception:: errorcode=" + str(e.errorcode) + ",message+" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
示例#17
0
def connect(ip,user,passwd):
  ns_session = nitro_service(ip,"HTTPS")
  ns_session.set_credential(user,passwd)

  ns_session.timeout=30

  try:
    ns_session.login()
  except nitro_exception as  e:
    print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)

  print("Connected to: %s as %s" %(ip,user))
  return ns_session
示例#18
0
def login_nitro(host, user, password):

    try :
        client = nitro_service(host,"http")
        client.set_credential(user,password)
        client.timeout = 500
        logging.debug("nitro login complete")
    except nitro_exception as  e:
        logging.error("Exception::login_nitro::errorcode="+str(e.errorcode)+",message="+ e.message)
    except Exception as e:         
        logging.error("Exception::loing_nitro::message="+str(e.args))

    return client
    def main(cls):

        config = set_vip()
        #Define IP of Netscaler
        config.ip = "xx.xx.xx.xx"
        #Username and Password
        config.username = "******"
        config.password = "******"

        try :
            client = nitro_service(config.ip,"http")
            client.set_credential(config.username,config.password)
            client.timeout = 500
            
            ###### Arguments of respective fields ######

            #Name of Server
            SRVS="prdtestlb00"
            #IP of server
            IP="192.168.1.1"
            #Port of service
            port=80
            #Name of Service
            svc_name="svc-"+str(port)
            #Number of Servers
            j=3
            #Name of LB
            lb_vserver_name="lb-testlb"
            #Name of Cs Vserver
            csvserverhttp= "cs-80-testlb"
            csvserverssl= "cs-443-testlb"
            #IP of CS Vserver
            cs_ip="9.1.2.3"
            ###### END Arguments of respective fields ######

            device = raw_input('Select if you want to create a VIP or Delete a VIP - [addvip] or  [rmvip]:')

            if (device == 'addvip' or device == 'ADDVIP'):
                #Create a new VIP
                config.run_newvip(client, SRVS , IP , svc_name , port , lb_vserver_name,csvserverhttp,csvserverssl,cs_ip,j)

            elif (device == 'rmvip' or device == 'RMVIP'):
                #Delete a new VIP
                config.run_rmvip(client, SRVS , IP , svc_name , port , lb_vserver_name,csvserverhttp,csvserverssl,j)

            client.logout()
        except nitro_exception as  e:
            print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
        except Exception as e:
            print("Exception::message="+str(e.args))
        return
示例#20
0
 def __connect(self, config: List[NitroConfig]):
     """Connect to all the clients"""
     clients = []
     for c in config:
         try:
             logging.debug('Connecting to nitro client %s://%s' %
                           (c.protocol, c.host))
             client = nitro_service(c.host, c.protocol)
             client.certvalidation = c.cert_validation
             client.login(c.username, c.password)
             clients.append(client)
         except nitro_exception as e:
             logging.warning('Could not connect to nitro client: %s (%s)' %
                             (e.message, e.errorcode))
     self.clients = clients
示例#21
0
    def initConnection(self):
        """Create the NetScaler session using HTTP, passing in the credentials
        to the NSIP"""
        try:
            self.ns_session = nitro_service(self.cfg['config']['nsip'], "HTTP")
            self.ns_session.set_credential(self.cfg['config']['username'],
                                           self.cfg['config']['password'])
            self.ns_session.timeout = 300
            self.ns_session.login()

        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))

        return
示例#22
0
 def wait_for_ready(self):
     """When the container boots up, the NS container may just have
        booted up as well and therefore not ready to serve the API.
        Poll the API until we can login
     """
     ip = self.nsip + ":" + self.nsport
     ready = False
     while not ready:
         ns_session = nitro_service(ip, 'HTTP')
         ns_session.set_credential(self.nslogin, self.nspasswd)
         ns_session.timeout = 600
         try:
             ns_session.login()
             ready = True
             logger.info("NetScaler is ready at %s" % ip)
             ns_session.logout()
         except Exception:
             logger.info("NetScaler API is not ready")
             time.sleep(5)
示例#23
0
	def main(cls, args_):
		if(len(args_) < 3):
			print("Usage: run.bat <ip> <username> <password>")
			return

		config = stat_config()
		config.ip = args_[1]
		config.username = args_[2]
		config.password = args_[3] 
		try :
			client = nitro_service(config.ip,"http")
			client.set_credential(config.username,config.password)
			client.timeout = 500
			config.run_sample(client)
			client.logout()
		except nitro_exception as  e:
			print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
		except Exception as e:         
			print("Exception::message="+str(e.args))
		return
示例#24
0
    def initConnection(self):
        """Create the NetScaler session using HTTP, passing in the credentials
        to the NSIP"""
        try:
            self.ns_session = nitro_service(self.cfg['config']['nsip'],
                                            "HTTP")

            self.ns_session.set_credential(self.cfg['config']['username'],
                                           self.cfg['config']['password'])
            self.ns_session.timeout = 300

            self.ns_session.login()

        except nitro_exception as e:
            print("Exception::errorcode=" +
                  str(e.errorcode) + ",message=" + e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))

        return
示例#25
0
    def connect(self, nsc):
        try:
            # Get Netscaler User/Pass
            client = hvac.Client(url=self.vault_url)  # supports verify=false
            data = client.write('auth/approle/login',
                                role_id=self.vault_role_id,
                                secret_id=self.vault_secret_id)
            client.token = data['auth']['client_token']
            secret = client.read(self.vault_secret_path)
            self.nsc_user = str(secret['data']['username'])
            self.nsc_passwd = str(secret['data']['password'])

            # Create connection to redis
            self.redis = redis.StrictRedis(host=self.redis_host,
                                           port=self.redis_port,
                                           db=self.redis_db)

            # Create instance of nitro_service for netscaler connection
            self.session = nitro_service(nsc + self.domain, self.protocol)
            user = self.nsc_user
            #if 'dmz' in nsc.lower():
            #user += '1'
            self.session.set_credential(user, self.nsc_passwd)
            self.session.timeout = 300

            # Log into netscaler using credentials
            self.session.login()

            return True

        except nitro_exception as e:
            traceback.print_stack()
            print(sys.exc_info()[0])
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
            return False
        except Exception as e:
            traceback.print_stack()
            print(sys.exc_info()[0])
            print("Exception::message=" + str(e.args))
            return False
示例#26
0
    def main(cls, args_):
        if (len(args_) < 3):
            print("Usage: run.bat <ip> <username> <password>")
            return

        config = stat_config()
        config.ip = args_[1]
        config.username = args_[2]
        config.password = args_[3]
        try:
            client = nitro_service(config.ip, "http")
            client.set_credential(config.username, config.password)
            client.timeout = 500
            config.run_sample(client)
            client.logout()
        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
示例#27
0
                    dest='username',
                    type=str,
                    required=True,
                    help='api user')
PARSER.add_argument('--password',
                    dest='password',
                    type=str,
                    required=True,
                    help='password..duh?')
ARGS = PARSER.parse_args()

# Disable warnings about unverified HTTPS
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# login to netscaler
NS_SESSION = nitro_service(ARGS.netscaler, 'https')
NS_SESSION.certvalidation = False
NS_SESSION.hostnameverification = False
NS_SESSION.login(ARGS.username, ARGS.password, 3600)

# Find all SSL virtual servers for load balancing and content switching
LBRESULT = lbvserver.get_filtered(NS_SESSION, 'servicetype:SSL')
CSRESULT = csvserver.get_filtered(NS_SESSION, 'servicetype:SSL')
for vserver in LBRESULT:
    print vserver.name
    # query ciphers for each vserver
    CIPHERS = sslvserver_sslciphersuite_binding.get(NS_SESSION, vserver.name)
    for cipher in CIPHERS:
        print cipher.ciphername
    print
for vserver in CSRESULT:
    parser.add_argument("--user", metavar="USERNAME", default="nagios", help="Netscaler username")
    parser.add_argument("--password", metavar="PASSWORD", default="api_user", help="Netscaler password")
    parser.add_argument("--ssl", action="store_true", help="turn ssl on")
    parser.add_argument("-w", "--warning", metavar="WARNING", help="warning")
    parser.add_argument("-c", "--critical", metavar="CRITICAL", help="critcal")

    parser.add_argument("--dargs", action="store_true", help="show service")

    args = parser.parse_args()
    if args.dargs:
        print(args)
        sys.exit(3)

    # 	nitro = NSNitro(args.host, args.user, args.password, args.ssl)
    if args.ssl:
        nitro_session = nitro_service(args.host, "HTTPS")
        nitro_session.certvalidation = False
        nitro_session.hostnameverification = False
    else:
        nitro_session = nitro_service(args.host, "HTTP")

    nitro_session.set_credential(args.user, args.password)
    nitro_session.timeout = 310

    try:
        nitro_session.login()
        try:
            obj = ns_stats.get(nitro_session)
            for i in range(len(obj)):
                if args.warning and args.critical:
                    if (float(obj[i].disk0perusage) >= float(args.critical)) or (
示例#29
0
class CreateCluster:
    @staticmethod
    def main(cls, args_):
        if (len(args_) < 3):
            print("Usage: run.bat <ip> <username> <password>")
            return

    try:
        #UPDATE THESE VARIABLES AS NEEDED
        nsipAddress0 = "10.102.201.11"
        nsipAddress1 = "10.102.201.12"
        clipAddress = "10.102.201.17"
        protocol = "http"
        uName = "nsroot"
        password = "******"
        timeout = 20  # The time to wait before connecting to the cluster IP address

        #Connect to the first appliance that you want to add to the cluster
        nonClipSession0 = nitro_service(nsipAddress0, protocol)
        nonClipSession0.login(uName, password)

        #Create a cluster instance
        newClusterInstance = clusterinstance()
        newClusterInstance.clid = 1
        clusterinstance.add(nonClipSession0, newClusterInstance)

        #Add the appliance to the cluster
        ClusterNode0 = clusternode()
        ClusterNode0.nodeid = 0
        ClusterNode0.ipaddress = nsipAddress0
        ClusterNode0.state = "ACTIVE"
        ClusterNode0.backplane = "0/1/1"
        clusternode.add(nonClipSession0, ClusterNode0)

        #Add the cluster IP address
        newNSIPAddress = nsip()
        newNSIPAddress.ipaddress = clipAddress
        newNSIPAddress.netmask = "255.255.255.255"
        newNSIPAddress.type = "CLIP"
        nsip.add(nonClipSession0, newNSIPAddress)

        #Enable the cluster instance
        clusterinstance.enable(nonClipSession0, newClusterInstance)

        #Save the configurations
        nonClipSession0.save_config()

        #Warm reboot the appliance
        nonClipSession0.reboot(True)

        #Wait for while for the cluster IP address to be available
        time.sleep(timeout)

        #The cluster is created and the first node is added to the cluster.
        #This node becomes the initial configuration coordinator of the cluster.

        #Log on to the cluster IP address and add the other nodes to the cluster

        #Connect to the cluster IP address
        clipSession = nitro_service(clipAddress, protocol)
        clipSession.login(uName, password)

        #Add the node to the cluster
        ClusterNode1 = clusternode()
        ClusterNode1.nodeid = 1
        ClusterNode1.ipaddress = nsipAddress1
        ClusterNode1.state = "ACTIVE"
        ClusterNode1.backplane = "1/1/1"
        clusternode.add(clipSession, ClusterNode1)

        #Save the configurations
        clipSession.save_config()

        #The second node is added to the cluster.
        #You must now log on to the node that you have just added and join it to the cluster

        #Connect to the node that you have just added to the cluster
        nonClipSession1 = nitro_service(nsipAddress1, protocol)
        nonClipSession1.login(uName, password)

        #Join the node to the cluster
        newCluster = cluster()
        newCluster.clip = clipAddress
        newCluster.password = password
        cluster.join(nonClipSession1, newCluster)

        #Save the configurations
        nonClipSession1.save_config()

        #Warm reboot the appliance
        nonClipSession1.reboot(True)

        #Wait for while for the node to reboot
        time.sleep(timeout)

        #Retrieving the cluster node details
        id = 0  # node id
        node = clusternode.get(clipSession, id)
        print("Node ID: " + node.nodeid + " | Admin state: " + node.state +
              " | Backplane interface: " + node.backplane)

        #Retrieving the cluster instance details
        id1 = 0  # instance id
        instance = clusterinstance.get(clipSession, id1)
        print("Cluster instance ID: " + instance.clid +
              " | Operational state: " + instance.operationalstate)

    except nitro_exception as e:
        print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
              e.message)
    except Exception as e:
        print("Exception::message=" + str(e.args))
示例#30
0
                    help='api user')
PARSER.add_argument('--password', dest='password', type=str, required=True,
                    help='password..duh?')
ARGS = PARSER.parse_args()

# Disable warnings about unverified HTTPS
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

SDX01IPS = '####IP ADDRESSES####'
SDX02IPS = '####IP ADDRESSES####'

# login to each netscaler
print 'Lehi SDX 01 High Availability Status'
print
for ip in SDX01IPS:
    NS_SESSION = nitro_service(ip, 'https')
    NS_SESSION.certvalidation = False
    NS_SESSION.hostnameverification = False
    NS_SESSION.login(ARGS.username, ARGS.password, 3600)
    HASTATUS = hanode.get_filtered(NS_SESSION, 'id:0')
    info = {'name': HASTATUS[0].name, 'ip': HASTATUS[0].ipaddress, 'status':
            HASTATUS[0].hastatus, 'state': HASTATUS[0].state}
    print '{i[name]:20} IP: {i[ip]:15} STATUS: {i[status]:14} STATE: {i[state]}'.format(i=info)

    NS_SESSION.logout()

print
print 'Lehi SDX 02 High Availability Status'
print
for ip in SDX02IPS:
    NS_SESSION = nitro_service(ip, 'https')
示例#31
0
	def main(cls, args_):
		if(len(args_) < 3):
			print("Usage: run.bat <ip> <username> <password>")
			return

		config = basic_lbvServer()
		config.ip = args_[1]
		config.username = args_[2]
		config.password = args_[3] 
		
		try :
			
			#Create an instance of the nitro_service class to connect to the appliance
			ns_session = nitro_service("10.217.242.90","HTTP")
			
			ns_session.set_credential("nsroot", config.password)
			ns_session.timeout = 310
			#Log on to the appliance using your credentials
			ns_session.login()
			
			#Enable the load balancing feature.
			features_to_be_enabled = "lb"			
			ns_session.enable_features(features_to_be_enabled)
			
			#Create an instance of the server class
			server_obj = server()

			#Create an instance of the service class
			service_obj = service()

			#Create an instance of the virtual server class
			new_lbvserver_obj = lbvserver()

			#Create a new virtual server
			new_lbvserver_obj.name = "MyFirstLbVServer"
			new_lbvserver_obj.ipv46 = "10.102.29.88"
			new_lbvserver_obj.servicetype = "HTTP"
			new_lbvserver_obj.port = 80
			new_lbvserver_obj.lbmethod = "ROUNDROBIN"
			#lbvserver.delete(ns_session, new_lbvserver_obj.name)
			#lbvserver.add(ns_session, new_lbvserver_obj)
					
			#Retrieve the details of the virtual server
			new_lbvserver_obj = lbvserver.get(ns_session,new_lbvserver_obj.name)
			print("Name : " +new_lbvserver_obj.name +"\n" +"Protocol : " +new_lbvserver_obj.servicetype)

			#Retrieve state of a lbvserver
			obj_lbv = lbvserver_stats.get(ns_session, "MyFirstLbVServer")
			print("statlbvserver_byname result::name="+obj_lbv.name+", servicetype="+obj_lbv.type +",state="+obj_lbv.state)

			#Retrieve state of a servicegroup
			obj_svcg = servicegroup.get(ns_session, "http_svcg")
			print("statsvcg_byname result::name="+obj_svcg.servicegroupname+", servicetype="+obj_svcg.servicetype +",state="+obj_svcg.servicegroupeffectivestate)

			#Delete the virtual server
			#lbvserver.delete(ns_session, new_lbvserver_obj.name)
			
			#Save the configurations
			ns_session.save_config()
			
			#Logout from the NetScaler appliance
			ns_session.logout()
			
		except nitro_exception as  e:
			print("Exception::errorcode="+str(e.errorcode)+",message="+ e.message)
		except Exception as e:         
			print("Exception::message="+str(e.args))
		return
    def main(cls, args_):
        if (len(args_) < 4):
            print(
                "Usage: run.bat <ip> <username> <password> <pattern-set-datafilename>"
            )
            return

        config = NitroApp()
        config.ip = args_[1]
        config.username = args_[2]
        config.password = args_[3]
        config.pfile = args_[4]

        try:

            #Create an instance of the nitro_service class to connect to the appliance
            ns_session = nitro_service(config.ip, "HTTP")

            ns_session.set_credential(
                config.username,
                config.password)  #to make arguments more generic
            ns_session.timeout = 500
            #Log on to the appliance using your credentials

            print("Logging into NetScaler at " + config.ip + " with userid " +
                  config.username)

            ns_session.login()

            print("Reading input file " + config.pfile)

            with open(config.pfile, 'r') as jfile:
                jdata = json.load(jfile)
            jfile.closed

            #
            #                      Strip the leading tag - we don't need it any more
            #

            pattern_sets = jdata['patsets']

            for psname, bindings in pattern_sets.iteritems():
                patset_obj = policypatset()
                patset_obj.name = psname
                print("Attempting to add patset " + patset_obj.name)
                try:
                    policypatset.add(ns_session, patset_obj)
                except nitro_exception as e:
                    if e.errorcode == 273:
                        print(
                            "Pattern set " + patset_obj.name +
                            " is already defined.   Will attempt to add bindings anyway."
                        )
                    else:
                        print("Exception::errorcode=" + str(e.errorcode) +
                              ",message=" + e.message)
                        print(
                            "Running configuration was NOT saved.  Logging out."
                        )
                        ns_session.logout()
                        return

                for b in bindings:
                    ppbinding_obj = policypatset_pattern_binding()
                    ppbinding_obj.name = patset_obj.name
                    ppbinding_obj.String = b['String']
                    ppbinding_obj.index = b['index']
                    ppbinding_obj.charset = b['charset']
                    try:
                        print("Attempting to add  " + ppbinding_obj.name +
                              "/" + ppbinding_obj.String)
                        policypatset_pattern_binding.add(
                            ns_session, ppbinding_obj)
                        print(ppbinding_obj.name + "/" + ppbinding_obj.String +
                              " added.")
                    except nitro_exception as e:
                        if e.errorcode in [2830, 2883]:
                            print(
                                "This pattern or index is already defined.   Overwriting current definition with new values."
                            )
                            ppbinding_delete_obj = policypatset_pattern_binding(
                            )
                            ppbinding_delete_obj.name = ppbinding_obj.name
                            ppbinding_delete_obj.String = ppbinding_obj.String
                            policypatset_pattern_binding.delete(
                                ns_session, ppbinding_delete_obj)
                            policypatset_pattern_binding.add(
                                ns_session, ppbinding_obj)
                        else:
                            print("Exception::errorcode=" + str(e.errorcode) +
                                  ",message=" + e.message)
                            print(
                                "Running configuration was NOT saved.  Logging out."
                            )
                            ns_session.logout()
                            return

            # Uncomment the line below and indent properly to save the configurations
            # ns_session.save_config()

            print("Running configuration was NOT saved.  Logging out")

            #Logout from the NetScaler appliance
            ns_session.logout()

        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
示例#33
0
#!/usr/bin/env python
# Nitro Imports
from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service

if __name__ == '__main__':
    """Create the NetScaler session using HTTP, passing in the credentials to
    the NSIP"""
    try:  # Error Handling
        ns_session = nitro_service("192.168.1.50", "HTTP")  # Create session

        ns_session.set_credential("nsroot", "nsroot")  # Set the session creds
        ns_session.timeout = 300  # Set Timeout in seconds

        ns_session.login()  # Preform login

        newSVC = service()  # Create new Service instance
        newSVC.name = "service1"  # Define a name
        newSVC.ip = "8.8.8.8"  # Define the service IP
        newSVC.port = "80"  # Define the service port
        newSVC.servicetype = "HTTP"  # Define the service type

        #Add the new service
        service.add(ns_session, newSVC)  # Add the service to the NetScaler

    except nitro_exception as e:  # Error Handling
        print("Exception::errorcode=" +
              str(e.errorcode) + ",message=" + e.message)
    except Exception as e:
        print("Exception::message=" + str(e.args))
    def main(cls, args_):
        if (len(args_) < 3):
            print("Usage: run.bat <ip> <username> <password>")
            return

        config = MyFirstNitroApplication()
        config.ip = args_[1]
        config.username = args_[2]
        config.password = args_[3]

        try:

            #Create an instance of the nitro_service class to connect to the appliance
            ns_session = nitro_service(config.ip, "HTTP")

            ns_session.set_credential(
                config.username,
                config.password)  #to make arguments more generic
            ns_session.timeout = 310
            # To skip invalid arguments for Add/Update/Delete Operations (HTTP POST/PUT/DELETE Request)
            # Set this argument to True when newer version of SDK is used with older version of Netscaler
            ns_session.skipinvalidarg = True
            # By setting this argument to True, add operation will take care of adding or updating the entity without throwing any error
            ns_session.idempotent = True
            # By setting this argument to True HTTP Basic Auth will be used and there is no need for login() and logout() calls
            ns_session.basic_auth = False
            #Log on to the appliance using your credentials
            ns_session.login()

            #Enable the load balancing feature.
            features_to_be_enabled = "lb"
            ns_session.enable_features(features_to_be_enabled)

            #Create an instance of the virtual server class
            new_lbvserver_obj = lbvserver()

            #Create a new virtual server
            new_lbvserver_obj.name = "MyFirstLbVServer"
            new_lbvserver_obj.ipv46 = "10.102.29.88"
            new_lbvserver_obj.servicetype = "HTTP"
            new_lbvserver_obj.port = 80
            new_lbvserver_obj.lbmethod = "ROUNDROBIN"
            lbvserver.add(ns_session, new_lbvserver_obj)

            #Retrieve the details of the virtual server
            new_lbvserver_obj = lbvserver.get(ns_session,
                                              new_lbvserver_obj.name)
            print("Name : " + new_lbvserver_obj.name + "\n" + "Protocol : " +
                  new_lbvserver_obj.servicetype)

            #Delete the virtual server
            lbvserver.delete(ns_session, new_lbvserver_obj.name)

            #Save the configurations
            ns_session.save_config()

            #Logout from the NetScaler appliance
            ns_session.logout()

        except nitro_exception as e:
            print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
                  e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return
    parser.add_argument('--nosslverify',
                        action="store_true",
                        help='turn ssl verify off')
    parser.add_argument('-w', '--warning', metavar='WARNING', help='warning')
    parser.add_argument('-c', '--critical', metavar='CRITICAL', help='critcal')

    parser.add_argument('--dargs', action='store_true', help='show service')

    args = parser.parse_args()
    if args.dargs:
        print(args)
        sys.exit(3)

#	nitro = NSNitro(args.host, args.user, args.password, args.ssl)
    if args.ssl:
        nitro_session = nitro_service(args.host, "HTTPS")
        if args.nosslverify:
            nitro_session.certvalidation = False
            nitro_session.hostnameverification = False
    else:
        nitro_session = nitro_service(args.host, "HTTP")

    nitro_session.set_credential(args.user, args.password)
    nitro_session.timeout = 310

    try:
        nitro_session.login()
        try:
            obj = ns_stats.get(nitro_session)
            for i in range(len(obj)):
                if args.warning and args.critical:
示例#36
0
#!/usr/bin/env python
# Nitro Imports
from nssrc.com.citrix.netscaler.nitro.service.nitro_service import nitro_service
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception
from nssrc.com.citrix.netscaler.nitro.resource.config.basic.service import service

if __name__ == '__main__':
    """Create the NetScaler session using HTTP, passing in the credentials to
    the NSIP"""
    try:  # Error Handling
        ns_session = nitro_service("192.168.1.50", "HTTP")  # Create session

        ns_session.set_credential("nsroot", "nsroot")  # Set the session creds
        ns_session.timeout = 300  # Set Timeout in seconds

        ns_session.login()  # Preform login

        newSVC = service()  # Create new Service instance
        newSVC.name = "service1"  # Define a name
        newSVC.ip = "8.8.8.8"  # Define the service IP
        newSVC.port = "80"  # Define the service port
        newSVC.servicetype = "HTTP"  # Define the service type

        #Add the new service
        service.add(ns_session, newSVC)  # Add the service to the NetScaler

    except nitro_exception as e:  # Error Handling
        print("Exception::errorcode=" + str(e.errorcode) + ",message=" +
              e.message)
    except Exception as e:
        print("Exception::message=" + str(e.args))
示例#37
0
    def main(cls, args_):
        
        
        debug = False

        print '\n'
        print "*************************************"
        print "*** CTX139319 Implementation Script *"
        print "*************************************"
        print '\n'

        config = set_config()
        config.ip = raw_input('What is the NSIP? (e.g. 192.168.100.1):  ')
        
        # Assume a default value when pressing Enter
        if config.ip == '':
            config.ip = '172.16.231.10'
        config.username = raw_input('NetScaler Username:  '******'':
            config.username = '******'
        config.password = raw_input('NetScaler Password:  '******'':
            config.password = '******'
        
        try:
            client = nitro_service(config.ip,"http")
            client.set_credential(config.username,config.password)
            client.timeout = 900

            mySSODomain = raw_input('What is the NT/AD Domain for Single Sign On to Citrix components?   ')
            if mySSODomain == '':
                mySSODomain = 'demo.lab'
            myAppCURL = raw_input('What is the URL for the AppController? (e.g. https://ac.domain.com)  ')
            if myAppCURL == '':
                myAppCURL = 'https://ac.demo.lab'
            myStoreFrontURL = raw_input('What is the base URL for StoreFront? (e.g. https://storefront.domain.com)   ')
            if myStoreFrontURL == '':
                myStoreFrontURL = 'https://sf.demo.lab'
            myReceiverWebPath = raw_input('What is the path to Receiver Web on ' + myStoreFrontURL + '? (e.g. /Citrix/StoreWeb)   ')
            if myReceiverWebPath == '':
                myReceiverWebPath = '/Citrix/StoreWeb'

            if debug:
                print 'SSO Domain %s', mySSODomain
                print 'APP Cntrol %s', myAppCURL
                print 'Storefront %s', myStoreFrontURL
                print 'Rcvr Web   %s', myReceiverWebPath

            #worker(client,myGateway, myAppCURL)
            
            
            if debug:
                print '\n*** Gateway Selection ***\n'

            myGateway = gatewaySelection(client,debug)
            if debug:
                print '\n*** Gateway Selection ***\n'
            else:     
                print 'Gateway: %s\n' % myGateway

            clientlessAccessPoliciesReceiver(client, myGateway, debug)
            if debug:
                print '\n*** Receiver Web Clientless Configuration ***\n'
            else:
                print '         \--- Receiver Clientless'

            clientlessAccessPoliciesReceiverWeb(client,myGateway, debug)
            if debug:
                print '\n*** Session Configuration for WorxHome ***\n'
            else:
                print '         \--- Receiver Web Clientless'

            sessionWorxHome(client,myGateway,mySSODomain,myAppCURL, debug)
            if debug:
                print '\n*** Session Configuration for Receiver ***\n'
            else:
                print '         \--- WorxHome Session'
            
            sessionReceiverWindows(client, myGateway, mySSODomain, myStoreFrontURL, myAppCURL, debug)
            if debug:
                print '\n*** Session Configuration for Web ***\n'
            else:
                print '         \--- Receiver Windows Session'

            sessionWeb(client,myGateway,mySSODomain,myStoreFrontURL+myReceiverWebPath, myAppCURL, debug)
            if debug:
                print '\n*** Session Web Configuration for Web ***\n'
            else:
                print '         \--- Mobile Web Session'

            sessionInternalWeb(client,myGateway,mySSODomain,myStoreFrontURL+myReceiverWebPath, debug)
            if debug:
                print '\n*** Session PC Configuration for Web ***\n'
            else:
                print '         \--- PC Web Session'

            staBinding(client,myGateway,myAppCURL,debug)
            if debug:
                print '\n*** AppController added to STA binding ***\n'
            else:
                print '         \--- AC STA'
            
            client.logout()
            if debug:
                print '\n*** Logging off ***\n'                        
        
        except nitro_exception as e:  # Error Handling
            print("Exception::errorcode=" +
                  str(e.errorcode) + ",message=" + e.message)
        except Exception as e:
            print("Exception::message=" + str(e.args))
        return