Beispiel #1
0
def Main():
    try:
        global device, user, password, grpc_port,request_id
        parser = argparse.ArgumentParser()
        parser.add_argument('-device', help='Input host name or ip ', type=str)
        parser.add_argument('-user', help='Input username for host', type=str)
        parser.add_argument('-password', help='Input password for host', type=str)
        parser.add_argument('-grpc_port', help='Input grpc port',type=str)
        parser.add_argument('-request_id', help='Input client request id',type=str)
        args, unknown = parser.parse_known_args()
        
        device = args.device or device
        user =  args.user or user
        password = args.password or password
        grpc_port = args.grpc_port or grpc_port
        request_id = args.request_id or request_id

        channel = grpc.insecure_channel(device+':'+grpc_port)
        stub = authentication_service_pb2.LoginStub(channel)
        try: 
            login_response = stub.LoginCheck(authentication_service_pb2.LoginRequest(user_name=user,password=password, client_id=request_id), timeout)
        except Exception as e:
            print('request id given is in use, using new one')  
            login_response = stub.LoginCheck(authentication_service_pb2.LoginRequest(user_name=user,password=password, client_id='new'), timeout) 

        if login_response.result :
            print "[INFO] Connected to gRPC Server:",+login_response.result
        else:
            print "[ERROR] gRPC Server Connection failed!!!",+login_response.result

        mgd = management_service_pb2.ManagementRpcApiStub(channel)

        op_command = "show version"
        op = ExecuteOpCommandRequest(cli_command = op_command, out_format = 2, request_id = 1000)
        result = mgd.ExecuteOpCommand(op, timeout)
        response ='' 
        for i in result:
            response += i.data
        if i.status == 0:
            print 'Invoked ExecuteOpCommand API return code = ', i.status
            print 'Invoked ExecuteOpCommand API return code = ', i.data 
        else:
            print 'Something Went Wrong !!! Data not received'
    except AbortionError as ex: 
        print ('The application got closed abruptly!!!')
        print ('Got exception: %s' % ex.message)
        print (traceback.print_exc())
        print (ex.code)
        print (ex.details)
    except Exception as ex:
        print (ex.message)
        print (traceback.print_exc())
    return
def EstablishChannel(address, port, client_id, user, password):
    # Open a grpc channel to the device
    # creds = implementations.ssl_channel_credentials(open('/tmp/host.pem').read(), None, None)
    # channel = implementations.secure_channel(address, port, creds)

    try:
        channel = grpc.insecure_channel('%s:%d' % (address, port))

        auth_stub = authentication_service_pb2.LoginStub(channel)

        login_response = auth_stub.LoginCheck(
            authentication_service_pb2.LoginRequest(user_name=user,
                                                    password=password,
                                                    client_id=client_id),
            _TIMEOUT_SECONDS)

        if login_response.result == 1:
            print("Login successful")
            return channel
        else:
            print("Login failed")
            sys.exit(1)

    except Exception as tx:
        print(tx)
Beispiel #3
0
def Main():

    # Connect and Authenticate
    conn = grpc.insecure_channel('%s:%d' % (options.HOST, int(options.PORT)))
    auth_stub = authentication_service_pb2_grpc.LoginStub(conn)
    login = auth_stub.LoginCheck(
            auth_svc.LoginRequest(user_name=options.USER,
                                  password=options.PASSWORD,
                                  client_id=options.CLIENT_ID), 
            TIMEOUT)
    if login:
        print ("Successfully connected to server %s:%s as %s" % (
            options.HOST, options.PORT, options.USER))
    else:
        print ("ERROR: Login to server server %s:%s as %s FAILED" % (
            options.HOST, options.b, routes_req))
        sys.exit(1)

    # Create the RIB service stub
    rib = rib_service_pb2_grpc.RibStub(conn)

    # Read routes
    print ('Reading JSON input file...')
    f = open(options.FILE, "rb")
    routes_req = jsonf.Parse(f.read(), rib_svc.RouteUpdateRequest())
    print (routes_req)

    # Do stuff
    if options.OPER == 'add':
            add_routes(rib, routes_req)
    elif options.OPER == 'del':
            del_routes(rib, routes_req)
    else:
            print ('Invalid operation')
Beispiel #4
0
def _authenticateChannel(channel, user, passw, client_id):
    """
    This method authenticates the provided grpc channel.
    """
    sec_stub = authentication_service_pb2.LoginStub(channel)
    try:
        login_response = stub.LoginCheck(
            authentication_service_pb2.LoginRequest(user_name=user,
                                                    password=password,
                                                    client_id=request_id),
            timeout)
    except Exception as e:
        print('request id given is in use, using new one')
        res = sec_stub.LoginCheck(authentication_service_pb2.LoginRequest(
            user_name=user, password=password, client_id='request'),
                                  timeout=60)
    return res
def _authenticateChannel(channel, user, passw, client_id):
    """
    This method authenticates the provided grpc channel.
    """
    sec_stub = authentication_service_pb2.LoginStub(channel)
    cred = authentication_service_pb2.LoginRequest(user_name=user,
                                                   password=passw,
                                                   client_id=client_id)
    res = sec_stub.LoginCheck(cred)
    return res
def Main():

    # Connect and Authenticate
    conn = grpc.insecure_channel('%s:%d' % (options.HOST, int(options.PORT)))
    auth_stub = authentication_service_pb2_grpc.LoginStub(conn)
    login = auth_stub.LoginCheck(
        auth_svc.LoginRequest(user_name=options.USER,
                              password=options.PASSWORD,
                              client_id=options.CLIENT_ID), TIMEOUT)
    if login:
        print "Successfully connected to server %s:%s as %s" % (
            options.HOST, options.PORT, options.USER)
    else:
        print "ERROR: Login to server server %s:%s as %s FAILED" % (
            options.HOST, options.PORT, options.USER)
        sys.exit(1)

    # Create the RIB service stub
    rib = rib_service_pb2_grpc.RibStub(conn)

    # Open the output file
    f = open(options.FILE, "wb")

    # Make the request for all IPv4 routes in the given table

    match = rib_svc.RouteMatchFields(
        dest_prefix=prpd.NetworkAddress(inet=jnx_addr.IpAddress(
            addr_string="0.0.0.0")),
        dest_prefix_len=0,
        table=prpd.RouteTable(rtt_name=prpd.RouteTableName(
            name=options.TABLE)))
    if (options.TAG):
        match_tags = {}
        match_tags[0] = rib_svc.RouteAttributeUint32(value=int(options.TAG))
        ext_match = rib_svc.RouteExtendedMatchFields(tags=match_tags)
    else:
        ext_match = None
    this_req = rib_svc.RouteGetRequest(key=match,
                                       extended_match=ext_match,
                                       match_type=rib_svc.EXACT_OR_LONGER,
                                       route_count=1000)
    getStream = rib.RouteGet(this_req, TIMEOUT)

    rt_count = 0
    cummulative_reply = rib_svc.RouteGetReply()
    for i in getStream:
        #print "Read reply with %d routes" % len(i.routes)
        #print i
        cummulative_reply.status = i.status
        cummulative_reply.routes.extend(i.routes)
        rt_count += len(i.routes)

    f.write(jsonf.MessageToJson(cummulative_reply))
    f.close()
    print "Wrote %d JSON routes to %s" % (rt_count, options.FILE)
Beispiel #7
0
def add_firewall_filter(intf):
    channel = grpc.insecure_channel('vqfx:32767')
    auth_stub = authentication_service_pb2_grpc.LoginStub(channel)
    response = auth_stub.LoginCheck(
        auth.LoginRequest(
            user_name='antidote',
            password='******',
            client_id='jet',
        ))

    fw_stub = firewall_service_pb2_grpc.AclServiceStub(channel)
    filter = fw.AccessList(
        acl_name='filter-by-jet',
        acl_type=fw.ACL_TYPE_CLASSIC,
        acl_family=fw.ACL_FAMILY_INET,
        acl_flag=fw.ACL_FLAGS_NONE,
        ace_list=[
            fw.AclEntry(inet_entry=fw.AclInetEntry(
                ace_name='t1',
                ace_op=fw.ACL_ENTRY_OPERATION_ADD,
                adjacency=fw.AclAdjacency(type=fw.ACL_ADJACENCY_AFTER),
                matches=fw.AclEntryMatchInet(match_protocols=[
                    fw.AclMatchProtocol(
                        min=1, max=1, match_op=fw.ACL_MATCH_OP_EQUAL)
                ]),
                actions=fw.AclEntryInetAction(
                    action_t=fw.AclEntryInetTerminatingAction(action_accept=1),
                    actions_nt=fw.AclEntryInetNonTerminatingAction(
                        action_log=1)))),
            fw.AclEntry(inet_entry=fw.AclInetEntry(
                ace_name='t2',
                ace_op=fw.ACL_ENTRY_OPERATION_ADD,
                adjacency=fw.AclAdjacency(type=fw.ACL_ADJACENCY_AFTER),
                actions=fw.AclEntryInetAction(
                    action_t=fw.AclEntryInetTerminatingAction(
                        action_discard=1),
                    actions_nt=fw.AclEntryInetNonTerminatingAction(
                        action_log=1)),
            ))
        ])
    fw_stub.AccessListAdd(filter)

    fw_stub.AccessListBindAdd(
        fw.AccessListObjBind(acl=filter,
                             obj_type=fw.ACL_BIND_OBJ_TYPE_INTERFACE,
                             bind_object=fw.AccessListBindObjPoint(intf=intf),
                             bind_direction=fw.ACL_BIND_DIRECTION_INPUT,
                             bind_family=fw.ACL_FAMILY_INET))
Beispiel #8
0
def EstablishChannel(address, port, client_id, user, password):
    # Open a grpc channel to the device
    #creds = implementations.ssl_channel_credentials(open('/tmp/host.pem').read(), None, None)
    channel = implementations.insecure_channel(address, port)

    # Create stub for authentication
    login_stub = authentication_service_pb2.beta_create_Login_stub(channel)

    # Fill the login request message structure
    login_request = authentication_service_pb2.LoginRequest(
        user_name=user, password=password, client_id=client_id)

    # Invoke the login check API
    login_response = login_stub.LoginCheck(login_request, _TIMEOUT_SECONDS)

    return channel
Beispiel #9
0
def stubAuth(DEFAULT_JSD_HOST, DEFAULT_JSD_PORT, USER, PASSWORD, DEFAULT_CLIENT_ID, JET_TIMEOUT):
    channel = grpc.insecure_channel('%s:%d' %(DEFAULT_JSD_HOST,DEFAULT_JSD_PORT))
    stub = authentication_service_pb2_grpc.LoginStub(channel)
    login_response = stub.LoginCheck(authentication_service_pb2.LoginRequest(
                                                                user_name=USER, 
                                                                password=PASSWORD,
                                                                client_id=DEFAULT_CLIENT_ID
                                                                ),
                                     JET_TIMEOUT
                                    )
    print(login_response.result)
    bfd = bfd_service_pb2_grpc.BFDStub(channel)
    try:
        result = bfd.Initialize(InitializeRequest())
        print(result.status)
        logging.info(result.status)
    except:
        print("Initialization Failed: ")
        logging.error("BFD JET Initialization failed")
    return bfd, channel
def Main():

    # Connect and Authenticate
    conn = grpc.insecure_channel('%s:%d' % (options.HOST, int(options.PORT)))
    auth_stub = authentication_service_pb2_grpc.LoginStub(conn)
    login = auth_stub.LoginCheck(
        auth_svc.LoginRequest(user_name=options.USER,
                              password=options.PASSWORD,
                              client_id=options.CLIENT_ID), TIMEOUT)
    if login:
        print "Successfully connected to server %s:%s as %s" % (
            options.HOST, options.PORT, options.USER)
    else:
        print "ERROR: Login to server server %s:%s as %s FAILED" % (
            options.HOST, options.PORT, options.USER)
        sys.exit(1)

    # Create the RIB service stub
    ft = flexible_tunnel_service_pb2_grpc.FlexibleTunnelStub(conn)

    # Read routes
    print 'Reading JSON input file...'
    f = open(options.FILE, "rb")

    # Do stuff
    if options.OPER == 'add':
        ft_req = jsonf.Parse(f.read(), ft_svc.FlexibleTunnelAddRequest())
        add_profiles(ft, ft_req)
    elif options.OPER == 'upd':
        ft_req = jsonf.Parse(f.read(), ft_svc.FlexibleTunnelUpdateRequest())
        add_profiles(ft, ft_req)
    elif options.OPER == 'del':
        ft_req = jsonf.Parse(f.read(), ft_svc.FlexibleTunnelDeleteRequest())
        del_profiles(ft, ft_req)
    elif options.OPER == 'sample':
        show_sample()
Beispiel #11
0
args = parser.parse_args()




client_id = '1'
#device1 = "10.216.66.148"
device1 = args.device
APP_USER = '******'
APP_PASSWORD = '******'
port = 15000


channel = implementations.insecure_channel(host=device1, port=port)
stub = authentication_service_pb2.beta_create_Login_stub(channel)
login_response = stub.LoginCheck(authentication_service_pb2.LoginRequest(user_name=APP_USER,password=APP_PASSWORD, client_id=client_id),1)
cos = cosd_service_pb2.beta_create_CosService_stub(channel)

if (login_response.result == 1):
            print "Login to device successful"
else:
            print "Login to  device failed"
            raise SystemExit()




def pause():
    programPause = raw_input("Enter to continue...")

try:
Beispiel #12
0
def Main():
    try:
        parser = argparse.ArgumentParser()

        parser.add_argument('-d',
                            '--device',
                            help='Input hostname',
                            required=True)
        parser.add_argument('-t',
                            '--timeout',
                            help='Input time_out value',
                            required=True,
                            type=int)
        parser.add_argument('-u',
                            '--user',
                            help='Input username',
                            required=True)
        parser.add_argument('-pw',
                            '--password',
                            help='Input password',
                            required=True)

        args = parser.parse_args()

        #Establish grpc channel to jet router
        creds = grpc.ssl_channel_credentials(
            open('/tmp/RSA2048.pem').read(), None, None)
        channel = grpc.secure_channel(args.device + ":32767",
                                      creds,
                                      options=((
                                          'grpc.ssl_target_name_override',
                                          _HOST_OVERRIDE,
                                      ), ))

        #create stub for authentication services
        stub = authentication_service_pb2.LoginStub(channel)
        #Authenticate
        login_request = authentication_service_pb2.LoginRequest(
            user_name=args.user, password=args.password, client_id="SampleApp")
        login_response = stub.LoginCheck(login_request, args.timeout)

        #Check if authentication is successful
        if login_response.result == True:
            print "[INFO] Connected to gRPC Server:"
            print login_response.result
        else:
            print "[ERROR] gRPC Server Connection failed!!!"
            print login_response.result

        #Create stub for management services
        stub = management_service_pb2.ManagementRpcApiStub(channel)
        print "[INFO] Connected to JSD and created handle to mgd services"

        for i in range(1):
            #Provide API request details
            op_xml_command = "<get-system-uptime-information>" \
            "</get-system-uptime-information>"
            op = management_service_pb2.ExecuteOpCommandRequest(
                xml_command=op_xml_command, out_format=2, request_id=1000)
            # Invoke API
            result = stub.ExecuteOpCommand(op, 100)
            # Check API response like status and output
            for i in result:
                print "[INFO] Invoked ExecuteOpCommand API return code = "
                print i.status
                print "[INFO] Return output in CLI format = "
                print i.data
    except Exception as ex:
        print ex
Beispiel #13
0
    def open(self):
        """
        Opens a grpc channel

        :return: True, upon successful creation & authentication of channel,
                 False, in case of failure

        """

        timeout = self.timeout

        import grpc  # pylint: disable=import-error
        import authentication_service_pb2  # pylint: disable=import-error
        import authentication_service_pb2_grpc  # pylint: disable=import-error
        from grpc.beta import implementations  # pylint: disable=import-error

        try:
            host_port = self.host + ':' + str(self.port)

            if self.bypass_jsd is True:
                logging.info('Using implementations.insecure_channel on %s',
                             self.host)

                channel = implementations.insecure_channel(host=self.host,
                                                           port=self.port)
            else:
                #                 channel = grpc.insecure_channel(
                #                     target=host_port,
                #                 )
                # use_local_subchannel_pool is supported from grpcio=1.19.0
                # Helps retain the multi channel functionality of gRPC
                # Automatically ignored for unsupported versions by gRPC (backwards compatible)

                channel = grpc.insecure_channel(
                    host_port, options=[('grpc.use_local_subchannel_pool', 1)])

            # Generate random client id
            client_id_list = []
            #client_id = str(random.randint(100000, 1000000))
            #Making the client_id same as channel_id

            client_id = self.channel_id
            client_id_list.append(client_id)
            self.client_id = client_id
            # while True:
            #     if client_id not in client_id_list:
            #         client_id_list.append(client_id)
            #         self.client_id = client_id
            #         break
            #     else:
            #         client_id = str(random.randint(100000, 1000000))
            if self.bypass_jsd is not True:
                stub = authentication_service_pb2_grpc.LoginStub(channel)
                logging.info("Channel created via JSD")

                try:
                    login_response = \
                        stub.LoginCheck(
                            authentication_service_pb2.LoginRequest(
                                user_name=self.user,
                                password=self.password,
                                client_id=client_id
                            ),
                            timeout
                        )

                    if login_response.result:
                        logging.info(
                            'GRPC client-server connect is successful')
                    else:
                        logging.error('GRPC client-server connect has failed')
                        return False

                except Exception as exp:
                    logging.error(exp)
                    return False

            self.channel = channel
            logging.info('GRPC channel created successfully for %s', self.host)
            return True

        except Exception as exp:
            logging.error(exp)
            return False
Beispiel #14
0
    # open gRPC channel
    print("")
    print(__file__)
    print("Trying to Login to",
          args.target,
          "port",
          args.port,
          "as user",
          args.username,
          "... ",
          end='')
    channel = grpc.insecure_channel('%s:%d' % (args.target, args.port))
    auth_stub = authentication_service_pb2.LoginStub(channel)
    login_response = auth_stub.LoginCheck(
        authentication_service_pb2.LoginRequest(user_name=args.username,
                                                password=args.password,
                                                client_id=clientid),
        _JET_TIMEOUT)

    if login_response.result == 1:
        print("Login successful")
    else:
        print("Login failed")
        sys.exit(1)

except Exception as tx:
    print(tx)

# Create the BGP service stub
bgp = bgp_route_service_pb2.BgpRouteStub(channel)
strBgpReq = bgp_route_service_pb2.BgpRouteInitializeRequest()
Beispiel #15
0
try:
    CONNECTION_LIST = list()
    for i in range(1):
        t = Thread(target=allRouteApis)
        t.setDaemon(True)
        t.start()
    dispatch_thread = Thread(target=sendtoPS)
    dispatch_thread.setDaemon(True)
    dispatch_thread.start()

    channel = implementations.insecure_channel(host=HOST, port=GRPC_PORT)
    stub = authentication_service_pb2.beta_create_Login_stub(channel)
    login_response = stub.LoginCheck(
        authentication_service_pb2.LoginRequest(user_name=USER,
                                                password=PASSWORD,
                                                client_id=CLIENT_ID), TIMEOUT)
    LOG.info("Connected to the JET GRPC request response server")

    bgp = bgp_route_service_pb2.beta_create_BgpRoute_stub(channel)
    prpd = prpd_service_pb2.beta_create_Base_stub(channel)

    purgeTime = 30
    # Variables for RouteGet Operation
    eod = 0
    count = 0
    getroutelist = []
    getwaitflag = 0

    # Dictionary of sockets waiting on incomplete data for requests
    sockdict = {}
Beispiel #16
0
port = 9999
client_id = '101'


def pause():
    programPause = raw_input("Enter to continue...")


print "Executing Python app"

try:
    channel = implementations.insecure_channel(host=device1, port=port)
    stub = authentication_service_pb2.beta_create_Login_stub(channel)
    login_response = stub.LoginCheck(
        authentication_service_pb2.LoginRequest(user_name=APP_USER,
                                                password=APP_PASSWORD,
                                                client_id=client_id), 100)
    if (login_response.result == 1):
        print "Login to ", device1, "successful"
    else:
        print "Login to ", device1, "failed"
        raise SystemExit()
    fw = firewall_service_pb2.beta_create_AclService_stub(channel)
    pause()
    flag = 0
    res = []

    match1 = AclMatchPort(min=0, max=120, match_op=ACL_MATCH_OP_EQUAL)
    match2 = AclMatchPort(min=10, max=20, match_op=ACL_MATCH_OP_EQUAL)

    term1match1 = AclEntryMatchInet6(match_dst_ports=[match2],
Beispiel #17
0
def Main():
    try:
        parser = argparse.ArgumentParser()

        parser.add_argument('-d',
                            '--device',
                            help='Input hostname',
                            required=True)
        parser.add_argument('-t',
                            '--timeout',
                            help='Input time_out value',
                            required=True,
                            type=int)
        parser.add_argument('-u',
                            '--user',
                            help='Input username',
                            required=True)
        parser.add_argument('-pw',
                            '--password',
                            help='Input password',
                            required=True)

        args = parser.parse_args()

        #Establish grpc channel to jet router
        creds = grpc.ssl_channel_credentials(
            open('/tmp/RSA2048.pem').read(), None, None)
        channel = grpc.secure_channel(args.device + ":32767",
                                      creds,
                                      options=((
                                          'grpc.ssl_target_name_override',
                                          _HOST_OVERRIDE,
                                      ), ))

        #create stub for authentication services
        stub = authentication_service_pb2.LoginStub(channel)
        #Authenticate
        login_request = authentication_service_pb2.LoginRequest(
            user_name=args.user, password=args.password, client_id="SampleApp")
        login_response = stub.LoginCheck(login_request, args.timeout)

        #Check if authentication is successful
        if login_response.result == True:
            print "[INFO] Connected to gRPC Server:"
            print login_response.result
        else:
            print "[ERROR] gRPC Server Connection failed!!!"
            print login_response.result

        #Create stub for management services
        mgd_stub = management_service_pb2.ManagementRpcApiStub(channel)
        print "[INFO] Connected to JSD and created handle to mgd services"
        set_config = """<configuration-set>
                     set system location building bldg-name
                     set system location floor 4
                     </configuration-set>"""
        cfg_req = ExecuteCfgCommandRequest(request_id=1,
                                           text_config=set_config,
                                           load_type=4,
                                           commit=ConfigCommit(commit_type=1))
        CONFIG_RESULT = mgd_stub.ExecuteCfgCommand(cfg_req, timeout=60)
        print "Configuration Status", CONFIG_RESULT

    except Exception as ex:
        print ex