Пример #1
0
 def ControlPlayer(self, action='', percent=''):
     xbmc = Server(self.url('/jsonrpc', True))
     player = xbmc.Player.GetActivePlayers()
     if action == 'SetMute':
         return xbmc.Application.SetMute(mute='toggle')
     elif action == 'Back':
         return xbmc.Input.Back()
     elif action == 'Down':
         return xbmc.Input.Down()
     elif action == 'Home':
         return xbmc.Input.Home()
     elif action == 'Left':
         return xbmc.Input.Left()
     elif action == 'Right':
         return xbmc.Input.Right()
     elif action == 'Select':
         return xbmc.Input.Select()
     elif action == 'Up':
         return xbmc.Input.Up()
     elif action == 'MoveLeft':
         return xbmc.Input.Left()
     elif action == 'MoveRight':
         return xbmc.Input.Right()
     elif action == 'Seek':
         try:
             percent = float(percent)
             return xbmc.Player.Seek(playerid=player[0][u'playerid'], value=percent)
         except:
             return
     elif action:
         try:
             method = 'Player.'+action
             return xbmc._request(methodname=method, params={'playerid' : player[0][u'playerid']})
         except:
             return
Пример #2
0
    def __init__(self, scheme, ip, user, password, ports, egress_ports, logger,
                 two_tuple_hosts):
        self.uri = "%s://%s:%s@%s/command-api" % (scheme, user, password, ip)
        self.ports = ports
        self.egress_ports = egress_ports
        self.two_tuple_hosts = two_tuple_hosts or set()

        # Enable V6
        self.acls = {}
        self.acls_by_family = {"ip": [], "ipv6": []}

        # Build acls list from names in config and family list.
        for family in self.acls_by_family:
            for name in ports.values():
                new_acl = ACL(name, family)
                if new_acl not in self.acls:
                    self.acls[new_acl] = []
                    self.acls_by_family[family].append(new_acl)

        self.logger = logger
        self.min = 500
        self.max = 100000
        self.seq = self.min + 1
        self.switch = Server(self.uri)

        self.acl_hitcounts = {}
Пример #3
0
def update_claim(user,
                 password,
                 claim_name,
                 claim_id,
                 txid,
                 nout,
                 metadata,
                 content_type,
                 source_hash,
                 currency,
                 amount,
                 bid,
                 address=None,
                 tx_fee=None,
                 callback=None):

    server = Server(configs.get('wallet_rpc'))
    tp = Timekeeping()
    res = server.update_claim(user, password, claim_name, claim_id, txid, nout,
                              metadata, content_type, source_hash, currency,
                              amount, bid, address, tx_fee)
    tp.print_interval('update_claim')
    if callback is not None:
        return callback(res)

    return res
Пример #4
0
def main():
  
    argument_spec = dict( 
        vlan_id=dict(required=True), 
        vlan_name=dict(),
        host=dict(),
        username=dict(required=True),
        password=dict(required=True), 
        port=dict(required=False),
        transport=dict(choices=['http', 'https'],required=False)
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
    
    vlan_id = module.params['vlan_id']
    vlan_name = module.params['vlan_name']
    host = str(module.params['host'])
    username = module.params['username']
    password = module.params['password']
    port = int(module.params['port'])
    transport = module.params['transport']

    conn = Server("https://%s:%s@%s/command-api" %(username, password, host))
    
    list_cmds = [ "enable", "configure" ] 

    list_cmds.append("vlan %s" %(vlan_id))
    list_cmds.append("name %s" %(vlan_name))

    conn.runCmds(1, list_cmds, "json")

    module.exit_json(msg="Vlan created successfully")
Пример #5
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
     "-u", "--user", type=str, default="",
     help="specify a username", required=True)
  parser.add_argument(
     "-s", "--session", type=str, default="",
     help="specify config session name", required=True)
  parser.add_argument(
      "-f", "--file", type=str, default="",
      help="specify a file with static MACs to apply", required=True)
  parser.add_argument(
      "-d", "--device", type=str, default="",
      help="specify an EOS device which static MACs are to applied", required=True)
  parser.add_argument(
      "-p", "--passwd", type=str, default="",
      help="for passing password interactively", required=False)
  parser.add_argument(
      "-r", "--remove", action='store_true',
      help="to remove applied static mac addresses", required=False)
  args = parser.parse_args()
  n = 4 
  rand = ''.join(random.choices(string.ascii_uppercase +
                             string.digits, k = n))
  session = args.session + "-" + rand
  file = args.file
  hostname = args.device
  remove = args.remove
  user = args.user

  if len(args.passwd) > 0:
    passwd = args.passwd
  else:
    passwd = '***REMOVED***'

  _create_unverified_https_context = ssl._create_unverified_context
  ssl._create_default_https_context = _create_unverified_https_context

  with open(file, "r") as current_file:
    macaddresses = current_file.readlines()

  device = Server('https://{}:{}@{}/command-api'.format(user, passwd, hostname))

  try:
    for mac in macaddresses:
      #mac addresses in file should have format aa:aa:aa:aa:aa:aa.vlan#.interface#
      #
      bits = mac.split(".")
      macaddr = bits[0]
      vlan = bits[1]
      intf = bits[2]
    
      if remove == True:
        result = device.runCmds(1, ['enable', 'configure session {0}'.format(session), 'no mac address-table static {0}'.format(macaddr) + ' vlan {0}'.format(vlan) + ' interface {0}'.format(intf)])
      else:
        result = device.runCmds(1, ['enable', 'configure session {0}'.format(session), 'mac address-table static {0}'.format(macaddr) + ' vlan {0}'.format(vlan) + ' interface {0}'.format(intf)])
  
    result2 = device.runCmds(1, ['enable', 'configure session {0}'.format(session) + ' commit'])
  except: 
    print("something went wrong, check password\n\n")
def show_vlans():
    for switch in switches:
        urlString = "http://{}:{}@{}/command-api".format(switchusername, switchpassword, switch)
        switchReq = Server( urlString )
        response = switchReq.runCmds( 1, ["show vlan"] )
        print "Showing the vlans on %s" % (switch)
        print json.dumps(response, indent=4)
Пример #7
0
def main():
	#Disable SSL self-signed verification
	ssl._create_default_https_context = ssl._create_unverified_context

	parser = argparse.ArgumentParser()
	parser.add_argument('--user', default='admin', dest='user')
	parser.add_argument('--password', dest='passwd')
	parser.add_argument('--csvinfile', dest='csvinfile')
	parser.add_argument('--method', default='https', dest='method', choices=['http', 'https'])
	args = parser.parse_args()

	user = args.user
	passwd = args.passwd
	method = args.method
	csvinfile = args.csvinfile

	if len(sys.argv[1:]) == 0:
		parser.print_help()
		parser.exit()

	with open (csvinfile, 'r') as rf:
		reader = csv.DictReader(rf)
		for row in reader:
			sw = row['switch']
			cmdapi = Server("{}://{}:{}@{}/command-api".format(method,user,passwd,sw))
			cmdapi.runCmds(1,["enable", "configure", "no daemon TerminAttr"])
			shdaemon = cmdapi.runCmds(1,["show daemon"])

			#Verify daemon has been removed from each switch
			print(shdaemon[0]['daemons'])
Пример #8
0
def get_hostname(ip_list):
    ip_to_hostname = {}
    for ip in ip_list:
        switch_cli = Server( "http://*****:*****@"+ip+"/command-api" )
        response_hostname = switch_cli.runCmds( 1, ["show hostname"])
        ip_to_hostname[ip] = response_hostname[0]["hostname"]
    return ip_to_hostname
Пример #9
0
 def execute(self, cleanup=True):
     """
     Execute the bugger
     :return:
     """
     res = None
     try:
         res = self._server.execute(self._pdict, cleanup)
     except KeyboardInterrupt:
         self.monitor.stop()
         server2 = Server(self.url)
         server2.kill()
     except socket.error:
         self.log.error("Server was interrupted")
         exit(1)
     finally:
         self.monitor.stop()
     if res is None:
         raise ValueError("Run failed")
     resstr = "%s\t%s\t %s\t %s\t %s\t %s\t %s" % (str(datetime.datetime.utcnow()), self.message, 
                                                   self._pdict["cpuRangeVal"], self._pdict["outputDir"],
                                                   res["Wallclock"], res["peak"]/1024.**3, res["avg"]/1024**3)
     self.log.info("date \t\t\t message \t\t cpu \t outputdir \t time \t peak_mem \t avg_mem")
     self.log.info(resstr)
     with open(os.path.expanduser("~/result.dat"), "a") as out:
         out.write(resstr+"\n")
Пример #10
0
def GetVersion(x):
    verLoc = 19
    IP = "10.0.0." + str(x)
    switch = Server("https://" + ScriptUser + ":" + ScriptPass + "@" + IP +
                    "/command-api")
    # Results in Host Unreach never happening, but [ . ] means same thing
    #         without waiting
    socket.setdefaulttimeout(3)
    try:
        response = switch.runCmds(1, ["show version"])
    except socket.error, ERR:
        ErrorCode = ERR[0]
        if ErrorCode == errno.ECONNREFUSED:
            win.addstr(
                x, verLoc - 6,
                "        [ Err " + str(ErrorCode) + ": No eAPI ]          ")
            refresh()
        elif ErrorCode == errno.EHOSTUNREACH:
            # Never hit with lower socket timeout
            win.addstr(
                x, verLoc,
                "Err " + str(ErrorCode) + ": Pwr off or Aboot ]          ")
            refresh()
        elif ErrorCode == errno.ECONNRESET:
            win.addstr(x, verLoc,
                       "Err " + str(ErrorCode) + ": Con RST ]          ")
            refresh()
Пример #11
0
Файл: 5-1.py Проект: sfromm/pyn
def main(args):
    ''' main '''
    parser = OptionParser()
    parser.add_option('-u', '--username', default='eapi', help='username')
    parser.add_option('-p', '--password', default='', help='password')
    parser.add_option('-P', '--port', default='8543', help='port')
    parser.add_option('-D', '--debug', action='store_true', help='debug')
    options, args = parser.parse_args()

    for switch in args:
        url = "https://{0}:{1}@{2}:{3}/command-api".format(
            options.username, options.password, switch, options.port
        )
        request = Server(url)
        response = request.runCmds(1, ["show interfaces"] )
        if options.debug:
            print json.dumps(response, indent=4, sort_keys=True)
        interfaces = sorted(response[0]['interfaces'].keys())
        print "Switch {0} interfaces:".format(switch)
        print "{:20} {:<20} {:<20}".format("Interface", "inOctets", "outOctets")
        for inf in interfaces:
            data = response[0]['interfaces'][inf]
            if 'interfaceCounters' in data:
                print "{:20} {:<20} {:<20}".format(
                    inf, data['interfaceCounters']['inOctets'], data['interfaceCounters']['outOctets']
                )
        print
Пример #12
0
    def getEAPIData(self, ip):
        if self.__options.verbosity > 1:
            print("trying to fetch {} via eapi".format(ip), flush=True)
        try:
            uri = "https://{}:{}@{}:443/command-api".format(
                self.__options.eapiUser, self.__options.eapiPassword, ip)
            switch = Server(uri, transport=self.transport)
            try:
                response = switch.runCmds(
                    1,
                    ['enable', 'show hostname', 'show snmp mib ifmib ifindex'])
                hBase = 1
                iBase = 2
            except:
                response = switch.runCmds(
                    1, ['show hostname', 'show snmp mib ifmib ifindex'])
                hBase = 0
                iBase = 1
            host = {'hostname': response[hBase]['hostname'], 'interfaces': {}}
            # for the cache to work right in need to re-index the result set inverted
            for iface, index in response[iBase]['ifIndex'].items():
                host['interfaces'][str(index)] = iface

            # save the cache
            self.__cache[ip] = host
        except Exception as e:
            if self.__options.verbosity > 1:
                print("getEAPIData had a failure fetching from {}".format(ip))
            return (False, None)
        return (True, host)
Пример #13
0
def setHostname(host_ip):
    hostname = "veos-oci-" + host_ip.replace('.', '-')
    print("Setting hostname to " + hostname)
    switch = Server("https://*****:*****@" + host_ip + "/command-api")
    success = False
    try:
        response = switch.runCmds(1, [
            "enable", "configure", "hostname " + hostname,
            "ip name-server vrf default 8.8.8.8", "daemon TerminAttr" +
            "exec /usr/bin/TerminAttr -ingestgrpcurl=162.210.129.23:9910 -taillogs -ingestauth=key,"
            + "management api http-commands", "protocol http",
            "interface loopback 0", "ip address " + host_ip + "/32",
            "no shutdown"
        ])
        print("configuration successful")
        success = true
    except:
        print("Did not connect, waiting 5 seconds")
        sleep(5)
        response = switch.runCmds(1, [
            "enable", "configure", "hostname " + hostname,
            "ip name-server vrf default 8.8.8.8", "interface loopback 0",
            "ip address " + host_ip + "/32", "no shutdown"
        ])
    return hostname
Пример #14
0
def eApiShowInterfaces():
    switch = Server(commandApiUrl)
    response = switch.runCmds( 1, ["show interfaces"])
    if (request.query.callback):
        return directFlowJsonp(request)
    else:
        return json.dumps(eApiDirectFlow(), indent=4, sort_keys=True)
Пример #15
0
    def test_get_device_status_good(self):
        """ Test get_device_status happy path
        """
        from mock import MagicMock
        from jsonrpclib import Server
        device = dict(self.device)
        sh_ver = dict(self.sh_ver)

        # Arbitrary test valuse
        model = "Monkey-bot"
        timestamp = 1408034881.09

        sh_ver['modelName'] = model
        sh_ver['bootupTimestamp'] = timestamp
        response = []
        response.append(sh_ver)

        device['eapi_obj'] = Server(
            'https://*****:*****@10.10.10.11:443/command-api')
        device['eapi_obj'].runCmds = MagicMock(return_value=response)

        #response = []
        #response.append({})
        #response[0][u'interfaceStatuses'] = self.int_status

        app.get_device_status(device)
        self.assertEqual(device['modelName'], model)
        self.assertEqual(device['bootupTimestamp'], timestamp)
Пример #16
0
def main():
    #SESSION SETUP FOR eAPI TO DEVICE
    url = "https://%s:%s@%s/command-api" % (user, passwd, switch)
    ss = Server(url)
    #CONNECT TO DEVICE
    hostname = ss.runCmds( 1, ['enable', 'show hostname' ])[1]['hostname']
    print 'Hostname is '+hostname
Пример #17
0
def main():
    parser = argparse.ArgumentParser(description='Location,Ipaddress')
    parser.add_argument('-location', choices=['dc1','dc2'],
    help='Enter the colo location dc1|dc2')
    parser.add_argument('-ip', help='Enter switch ip address')
    args = parser.parse_args()
    if args.location == 'dc1':
         hostlist = arista_devices_dc1()
    elif args.location == 'dc2':
         hostlist = arista_devices_dc2()
    disable_https_cert()
    #----------------------------------------------------------------
    # Configuration section
    #----------------------------------------------------------------
    #-------------------Configuration - MUST Set ------------------------
    EAPI_USERNAME = os.getenv("USER")
    EAPI_PASSWORD = get_user_info()
    # http or https method
    EAPI_METHOD = 'https'

    for host in hostlist:
        switch = Server( '%s://%s:%s@%s/command-api' %
                       ( EAPI_METHOD, EAPI_USERNAME, EAPI_PASSWORD, host ) )
        rc = switch.runCmds( 1, [ 'enable',
                        'configure',
                        'interface Vxlan1',
                        'vxlan flood vtep add %s' % args.ip  ] )
        print( 'Host configured: %s' % ( host ) )
Пример #18
0
def ta_shut5():
    ip = '192.168.11.5'
    url = 'http://%s:%s@%s/command-api' % (user, passwd, ip)
    ss = Server(url)
    ss.runCmds(
        1, ['enable', 'configure terminal', 'daemon TerminAttr', 'shutdown'])
    pp(ss.runCmds(1, ['enable', 'show daemon TerminAttr']))
Пример #19
0
def openconnexion(device, username, password, cde):
    global commandesAfterError
    switch = Server("http://%s:%s@%s/command-api" %
                    (username, password, device))
    try:
        # result = switch.runCmds(version = 1, cmds = cde)
        result = switch.runCmds(version="latest", cmds=cde)
        # Format the result if result is not empty
        if result != None:
            data = {}
            for index in range(0, len(result)):
                data.update({cde[index].replace(" ", ""): result[index]})
            writeData('devices/' + device, data)

    except AppError as err:
        code = err.args[0][0]
        error = err.args[0][1]
        if code == 1000:
            erreurCde = error.split("'")[1]
            commandesAfterError.remove(erreurCde)
            openconnexion(device, username, password, commandesAfterError)
    except:
        deviceNotConnected.append(device)
        data = {}
        writeData('devices/' + device, data)
def add_vlans():
    for switch in switches:
    	for vlanlist in vlans:
    		urlString = "http://{}:{}@{}/command-api".format(switchusername, switchpassword, switch)
    		switchReq = Server( urlString )
    		response = switchReq.runCmds( 1, ["enable", "configure", "vlan" +" "+ str(vlanlist)] )
    		print "adding vlans %s" % (vlanlist)
Пример #21
0
def main(args):
    '''Do Stuff.
    '''

    log("Entering {0}.".format(sys._getframe().f_code.co_name), level='DEBUG')

    log("Started up successfully. Entering main loop...")

    switch = Server("{0}://{1}:{2}@{3}:{4}/command-api"\
        .format(PROTOCOL, USERNAME, PASSWORD, HOSTNAME, PORT))
    interfaces = {}
    while True:
        interfaces = get_interfaces(switch)
        response = switch.runCmds(1, [
            "show interfaces {0} transceiver".format(', '.join(
                interfaces.keys())), "show version"
        ])
        dominfo = response[0][u'interfaces']
        uptime = int(response[1][u'bootupTimestamp'])

        for interface in interfaces.keys():
            check_interfaces(uptime, str(interface), interfaces[interface],
                             dominfo[interface])

        log("---sleeping for {0} seconds.".format(args.poll_interval),
            level='DEBUG')
        time.sleep(args.poll_interval)
Пример #22
0
 def execute(self, cleanup=True):
     """
     Execute the bugger
     :return:
     """
     res = None
     try:
         res = self._server.execute(self._pdict, cleanup)
     except KeyboardInterrupt:
         self.monitor.stop()
         server2 = Server(self.url)
         server2.kill()
     except socket.error:
         self.log.error("Server was interrupted")
         exit(1)
     finally:
         self.monitor.stop()
     if res is None:
         raise ValueError("Run failed")
     resstr = "%s\t%s\t %s\t %s\t %s\t %s\t %s" % (
         str(datetime.datetime.utcnow()), self.message,
         self._pdict["cpuRangeVal"], self._pdict["outputDir"],
         res["Wallclock"], res["peak"] / 1024.**3, res["avg"] / 1024**3)
     self.log.info(
         "date \t\t\t message \t\t cpu \t outputdir \t time \t peak_mem \t avg_mem"
     )
     self.log.info(resstr)
     with open(os.path.expanduser("~/result.dat"), "a") as out:
         out.write(resstr + "\n")
Пример #23
0
def nlp_parse(text):
    """
    pass the text to the stanford NLP core server and get the parsed data
    """
    server = Server("http://localhost:8080")
    parsed_data = loads(server.parse(text))
    return parsed_data
Пример #24
0
    def test_get_device_status_good(self):
        """ Test get_device_status happy path
        """
        from mock import MagicMock
        from jsonrpclib import Server
        device = dict(self.device)
        sh_ver = dict(self.sh_ver)

        # Arbitrary test valuse
        model = "Monkey-bot"
        timestamp = 1408034881.09

        sh_ver['modelName'] = model
        sh_ver['bootupTimestamp'] = timestamp
        response = []
        response.append(sh_ver)

        device['eapi_obj'] = Server('https://*****:*****@10.10.10.11:443/command-api')
        device['eapi_obj'].runCmds = MagicMock(return_value=response)

        #response = []
        #response.append({})
        #response[0][u'interfaceStatuses'] = self.int_status

        app.get_device_status(device)
        self.assertEqual(device['modelName'], model)
        self.assertEqual(device['bootupTimestamp'], timestamp)
Пример #25
0
def main():
    conn = Server('http://localhost:12000')
    parameters = sys.argv[1:]
    function = parameters[0]
    number1 = parameters[1]
    number2 = parameters[2]
    print("calling: " + function + '(' + number1 + ', ' + number2 + ')')
    print(conn.execute(function, number1, number2))
def show_vlans():
    for switch in switches:
        urlString = "http://{}:{}@{}/command-api".format(
            switchusername, switchpassword, switch)
        switchReq = Server(urlString)
        response = switchReq.runCmds(1, ["show vlan"])
        print "Showing the vlans on %s" % (switch)
        print json.dumps(response, indent=4)
Пример #27
0
def getCurrentImage(switchuser, switchpass, ssh_host):
    command_string = "show boot-config"
    urlString = "https://{}:{}@{}/command-api".format(switchuser, switchpass, ssh_host)
    switchReq = Server(urlString)
    response = switchReq.runCmds( 1, ["enable", command_string] )
    responsePr = response [1]["softwareImage"]
    currentimage=responsePr.split('/')[1]
    return currentimage
Пример #28
0
def push(item, remote_addr, trg_queue, protocol=u'jsonrpc'):
    ''' Enqueue an FSQWorkItem at a remote queue '''
    if protocol == u'jsonrpc':
        try:
            server = Server(remote_addr, encoding=_c.FSQ_CHARSET)
            return server.enqueue(item.id, trg_queue, item.item.read())
        except Exception, e:
            raise FSQPushError(e)
Пример #29
0
def push(item, remote_addr, trg_queue, protocol=u'jsonrpc'):
    ''' Enqueue an FSQWorkItem at a remote queue '''
    if protocol == u'jsonrpc':
        try:
            server = Server(remote_addr, encoding=_c.FSQ_CHARSET)
            return server.enqueue(item.id, trg_queue, item.item.read())
        except Exception, e:
            raise FSQPushError(e)
Пример #30
0
def ta_shut():
    for ip in ips:
        url = urls(ip)
        ss = Server(url)
        ss.runCmds(1, [
            'enable', 'configure terminal', 'daemon TerminAttr', 'no shutdown'
        ])
        pp(ss.runCmds(1, ['enable', 'show daemon TerminAttr']))
Пример #31
0
def acl(user, passwd, ip):
    url = 'http://%s:%s@%s/command-api' % (user, passwd, ip)
    ss = Server(url)
    ss.runCmds(1, [
        'enable', 'configure terminal', 'ip access-list jason',
        '10 permit ip 192.168.0.0/24 any', '20 permit ip 172.16.0.0/12 any',
        '30 permit ip 0.0.0.0/0 any', '40 permit ip any any'
    ])
Пример #32
0
def csvout():
    today = datetime.date.today()
    ssl._create_default_https_context = ssl._create_unverified_context

    input = str(
        raw_input(
            "What switch, or switches, would you like to connect to separated by a comma: "
        ))
    host = input.split(",")

    while True:
        try:
            prot = str(
                raw_input(
                    "Which eAPI protocol do you want to use [http or https]? ")
            )
            break
        except ValueError:
            print("Please enter http or https")
            continue

    user = str(raw_input("Username: "******"%s://%s:%s@%s/command-api" %
                                (prot, user, passwd, a))
                bgpsumm = cmdapi.runCmds(1, ["show ip bgp summary"])

                for b in bgpsumm[0]['vrfs']['default']['peers']:
                    state = bgpsumm[0]['vrfs']['default']['peers'][b][
                        'peerState']
                    prfxrcvd = bgpsumm[0]['vrfs']['default']['peers'][b][
                        'prefixReceived']
                    asnum = bgpsumm[0]['vrfs']['default']['peers'][b]['asn']
                    updown = bgpsumm[0]['vrfs']['default']['peers'][b][
                        'upDownTime']

                    # Write to CSV File
                    writer.writerow({
                        'Switch ID': a,
                        'Peers': b,
                        'BGP State': state,
                        'Prefix(es) Received': prfxrcvd,
                        'AS Number': asnum,
                        'Up/Down Status': updown
                    })
    except:
        sys.exit(2)
Пример #33
0
def shutdown_port(m, n):
    try:
        switch = Server("https://*****:*****@" + n + "/command-api")
        response = switch.runCmds(1, [
            "enable", "configure", "interface " + m, "shutdown",
            "switchport access vlan 999", "switchport mode access"
        ])
    except:
        print("Could not connect to {} to shutdown ports".format(n))
Пример #34
0
def interfaceProvisioned( switchName, interfaceName ):
	mySwitch = Server( "unix:/var/run/command-api.sock" )
	result = mySwitch.runCmds(1, [	"enable",
									"show interfaces " + interfaceName] )
	if result[1]["interfaces"][interfaceName]["description"] == "":
		exists = 0
	else:
		exists = 1
	return exists
Пример #35
0
def get_asn():
    if (not os.environ.get('PYTHONHTTPSVERIFY', '')
            and getattr(ssl, '_create_unverified_context', None)):
        ssl._create_default_https_context = ssl._create_unverified_context
    switch = Server("https://<username>:<password>@127.0.0.1/command-api")
    get_asn = switch.runCmds(1, ["show ip bgp summary"])
    for asn in get_asn:
        local_asn = asn['vrfs']['default']['asn']
        return local_asn
Пример #36
0
def add_vlans():
    for switch in switches:
        for vlanlist in vlans:
            urlString = "http://{}:{}@{}/command-api".format(
                switchusername, switchpassword, switch)
            switchReq = Server(urlString)
            response = switchReq.runCmds(
                1, ["enable", "configure", "vlan" + " " + str(vlanlist)])
            print "adding vlans %s" % (vlanlist)
Пример #37
0
 def ControlPlayer(self, action='', percent=''):
     """ Various commands to control XBMC Player """
     self.logger.debug("Sending control to XBMC: " + action)
     xbmc = Server(self.url('/jsonrpc', True))
     player = xbmc.Player.GetActivePlayers()
     if action == 'SetMute':
         return xbmc.Application.SetMute(mute='toggle')
     elif action == 'Back':
         return xbmc.Input.Back()
     elif action == 'Down':
         return xbmc.Input.Down()
     elif action == 'Home':
         return xbmc.Input.Home()
     elif action == 'Left':
         return xbmc.Input.Left()
     elif action == 'Right':
         return xbmc.Input.Right()
     elif action == 'Select':
         return xbmc.Input.Select()
     elif action == 'Up':
         return xbmc.Input.Up()
     elif action == 'MoveLeft':
         return xbmc.Input.Left()
     elif action == 'MoveRight':
         return xbmc.Input.Right()
     elif action == 'PlayNext':
         try:
             return xbmc.Player.GoTo(playerid=player[0][u'playerid'], to='next')
         except:
             self.logger.error("Unable to control XBMC with action: " + action)
             return
     elif action == 'PlayPrev':
         try:
             return xbmc.Player.GoTo(playerid=player[0][u'playerid'], to='previous')
         except:
             self.logger.error("Unable to control XBMC with action: " + action)
             return
     elif action == 'JumpItem':
         try:
             return xbmc.Player.GoTo(playerid=player[0][u'playerid'], to=int(percent))
         except:
             self.logger.error("Unable to control XBMC with action: " + action)
             return
     elif action == 'Seek':
         try:
             percent = float(percent)
             return xbmc.Player.Seek(playerid=player[0][u'playerid'], value=percent)
         except:
             self.logger.error("Unable to control XBMC with action: " + action)
             return
     elif action:
         try:
             method = 'Player.' + action
             return xbmc._request(methodname=method, params={'playerid': player[0][u'playerid']})
         except:
             self.logger.error("Unable to control XBMC with action: " + action)
             return
Пример #38
0
def handle(addr, operate, key, value, idnum):
    client = Server("http://" + addr)
    #    while True:
    print("the client has linked to the server" + '\n')
    fout.write(
        str(datetime.datetime.now()) + ' ' +
        "the client has linked to the server:" + addr + ' ' + '\n')
    idnum = idnum + 1
    #write the log
    fout.write(
        str(datetime.datetime.now()) + ' ' + "the client's id is " +
        str(idnum) + ' ' + '\n')
    #wait for input
    if operate == "DELETE":
        #        key = raw_input("please input key> ")
        #        value = "null"
        rec = client.Delete(key)
        print(rec['code'])
        fout.write(
            str(datetime.datetime.now()) + ' ' + "the server's response is: " +
            " code:" + str(rec['code']) + " message:" + rec['message'] + ' ' +
            '\n')
        print("the server's response is: " + " code:" + str(rec['code']) +
              " message:" + rec['message'] + ' ' + '\n')
    if operate == "GET":
        #        key = raw_input("please input key> ")
        #        value = "null"
        rec = client.Get(key)
        print(rec)
        if rec['code'] == 0:
            fout.write(
                str(datetime.datetime.now()) + ' ' +
                "the server's response is: " + "value:" + str(rec['value']) +
                " code:" + str(rec['code']) + " message:" + rec['message'] +
                ' ' + '\n')
            print("the server's response is: " + "value:" + str(rec['value']) +
                  " code:" + str(rec['code']) + " message:" + rec['message'] +
                  ' ' + '\n')
        else:
            fout.write(
                str(datetime.datetime.now()) + ' ' +
                "the server's response is: " + " code:" + str(rec['code']) +
                " message:" + rec['message'] + ' ' + '\n')
            print("the server's response is: " + " code:" + str(rec['code']) +
                  " message:" + rec['message'] + ' ' + '\n')
    if operate == "PUT":
        #        key = raw_input("please input key> ")
        #        value = raw_input("please input value> ")
        rec = client.Put(key, value)
        print(rec)
        fout.write(
            str(datetime.datetime.now()) + ' ' + "the server's response is: " +
            " code:" + str(rec['code']) + " message:" + rec['message'] + ' ' +
            '\n')
        print("the server's response is: " + " code:" + str(rec['code']) +
              " message:" + rec['message'] + ' ' + '\n')
Пример #39
0
def main():
    args = parser.parse_args()
    config = get_rpc_string(os.path.expanduser('~/.namecoin/namecoin.conf'))
    rpc = Server(config)

    try:
        entry = rpc.name_filter('^%s/%s$' % (PREFIX, args.key), 0)[0]
        print(entry['value'])
    except IndexError:
        print('Key not found', file=sys.stderr)
Пример #40
0
def remove_acl(ip_list):
    adjacency_list = find_topology(ip_list)
    for ip in adjacency_list.keys():
        switch_cli = Server( "http://*****:*****@"+ip+"/command-api" )
        configure_acl_response = switch_cli.runCmds( 1, ["enable","configure terminal","no ip access-list trace",])
        for interface in adjacency_list[ip].values():
            configure_acl_interface_response = switch_cli.runCmds( 1, ["enable","configure terminal",
            "interface "+interface,
            "no ip access-group trace in",
            "end"])
Пример #41
0
def nlp_parse_multi(split_article):
    """
    Parse each sentence of the article separately.
    """
    server = Server("http://localhost:8080")
    re = []
    for sentence in split_article:
        result = loads(server.parse(sentence))
        re.append(result)
    return re
Пример #42
0
    def open(self):
        """
        Opens the connection with the device.
        """
        if self.use_ssl:
            url = 'https://%s:%s@%s/command-api' % (self.username, self.password, self.hostname)
        else:
            url = 'http://%s:%s@%s/command-api' % (self.username, self.password, self.hostname)

        self.device = Server(url)
Пример #43
0
def viewACL(ipaddr):
    # show all acls
    commandsToRun = ["enable", "show ip access-lists"]
    urlString = "https://{}:{}@{}/command-api".format(username, password,
                                                      ipaddr)  # 1
    switchReq = Server(urlString)  # 2
    response = switchReq.runCmds(1, commandsToRun)  # 3
    for acl in response[1]['aclList']:
        if acl["readonly"] == False:
            pprint.pprint(acl)
Пример #44
0
def addACL(ipaddr, name, rules):
    # add new acl
    commandsToRun = ["enable", "configure"]
    aclname = "ip access-list " + name
    commandsToRun += [aclname]
    commandsToRun += rules
    urlString = "https://{}:{}@{}/command-api".format(username, password,
                                                      ipaddr)  # 1
    switchReq = Server(urlString)  # 2
    switchReq.runCmds(1, commandsToRun)  # 3
Пример #45
0
def main():
    for switch in switches:
        #SESSION SETUP FOR eAPI TO DEVICE
        url = "https://%s:%s@%s/command-api" % (user, passwd, switch)
        ss = Server(url)
        #CONNECT TO DEVICE
        hostname = ss.runCmds(1, ['enable', 'show hostname'])[1]['hostname']
        running_config = ss.runCmds(1, ['enable', 'show running-config'],
                                    'text')[1]['output']
        with open(hostname, 'w') as f:
            f.write(running_config)
Пример #46
0
def deleteACL(ipaddr, name):
    #remove acl
    commandsToRun = ["enable", "configure"]
    aclname = "no ip access-list " + name
    commandsToRun += [aclname]
    urlString = "https://{}:{}@{}/command-api".format(username, password,
                                                      ipaddr)  # 1
    switchReq = Server(urlString)  # 2
    response = switchReq.runCmds(1, commandsToRun)  # 3
    print("Removed ACL: ", name)
    pprint.pprint(response)  # 4
Пример #47
0
def remote_trigger_pull(remote_addr, trg_queue, ignore_listener=False,
                        protocol=u'jsonrpc'):
    '''Write a non-blocking byte to a remote trigger fifo, to cause a triggered
       scan'''
    if protocol == u'jsonrpc':
        try:
            server = Server(remote_addr, encoding=_c.FSQ_CHARSET)
            return server.trigger_pull(queue=trg_queue,
                                       ignore_listener=ignore_listener,
                                       trigger=_c.FSQ_TRIGGER)
        except Exception, e:
            raise FSQRemoteTriggerError(e)
def find_neighbors(): #Function makes sure that each and every API is actually running on each switches and can pull with the current password.
    for switch in switches:
        urlString = "http://%s:%s@%s/command-api" % (switchusername, switchpassword, switch)
        switchReq = Server( urlString )
        response = switchReq.runCmds( 1, ["show lldp neighbors"] )
        neighborresponse = response[0]["lldpNeighbors"]
        nodes = neighborresponse
        neighborlist = []
        for neighbors in nodes:
            iterateneighbors =  neighbors['neighborDevice']
            neighborlist.append(iterateneighbors)
        print neighborlist
Пример #49
0
class Rpc(object):
    def __init__(self, config):
        self.rpc = Server(config)

    def get_blocks(self):
        return self.rpc.getinfo()['blocks']

    def get_names_as_dict(self):
        return self.rpc.name_filter('^d/[a-z0-9_-]+$', 0)

    def get_names(self):
        return [Name(x) for x in self.get_names_as_dict()]
Пример #50
0
def main():
    parser = argparse.ArgumentParser(description='Location,')
    parser.add_argument('-location', choices=['dc1','dc2'],
    help='Enter the colo location dc1|dc2')
    parser.add_argument('-new_extension',
    help='Enter name of extension to be added')
    parser.add_argument('-old_extension',
    help='Enter name of extension to be removed')
    parser.add_argument('--scp', action='store_true',
    help='SCP new extension to arista device.  System exit once finished')
    args = parser.parse_args()
    if args.location == 'dc1':
         hostlist = arista_devices_dc1()
    elif args.location == 'dc2':
         hostlist = arista_devices_dc2()
    #----------------------------------------------------------------
    # Configuration section
    #----------------------------------------------------------------
    EAPI_USERNAME = os.getenv("USER")
    EAPI_PASSWORD = get_user_info()
    EAPI_METHOD = 'https'
    # Disable ssh HTTPS certificates checking by default
    disable_https_cert()
    if args.scp:
        scp(hostlist,EAPI_USERNAME,EAPI_PASSWORD,args.new_extension)
    # configuration loop
    for host in hostlist:
        switch = Server( '%s://%s:%s@%s/command-api' %
                       ( EAPI_METHOD, EAPI_USERNAME, EAPI_PASSWORD, host ) )
        # uninstall extension
        try:
            rc = switch.runCmds( 1, [
                           'no extension %s' %args.old_extension ])
            print( 'Host configured: %s extension removed' % ( host ) )
        except:
            print "Extension %s not installed on %s" %(args.old_extension, host)
        # Pause 1 second between extension being uninstalled and removed
        time.sleep(1)
        # remove uninstalled extension from extension namespace
        try:
            rc = switch.runCmds( 1, [
                           'delete extension:%s' %args.old_extension ])
        except:
            print "Extension %s couldn't be deleted" %args.old_extension
        # New extension logic
        try:
            rc = switch.runCmds( 1, [
                           'copy flash:%s extension:%s' %(args.new_extension,args.new_extension),
                           'extension %s' %args.new_extension ])
            print( 'Host configured: %s extension added' % ( host ) )
        except:
            print "Extension %s already installed on %s" %(args.new_extension, host)
            next
Пример #51
0
    def test_get_interfaces_good(self):
        """ Test get_interfaces happy path
        """
        from mock import MagicMock
        from jsonrpclib import Server
        switch = Server('https://*****:*****@10.10.10.11:443/command-api')
        response = []
        response.append({})
        response[0][u'interfaceStatuses'] = self.int_status
        switch.runCmds = MagicMock(return_value=response)

        interfaces = app.get_interfaces(switch)
        self.assertEqual(interfaces, self.int_status)
Пример #52
0
def get_statistics(ip_list):
    switch_acl_counters = {}
    ip_to_hostname = get_hostname(ip_list)
    for ip in ip_list:
        switch_cli = Server( "http://*****:*****@"+ip+"/command-api" )
        response = switch_cli.runCmds( 1, ["enable","show ip access-lists trace"])
        switch_acl_counters[ip] = []
        for items in response[1]["aclList"][0]["sequence"]:
            if "packetCount" in items["counterData"]:
                switch_acl_counters[ip].append(int(items["counterData"]["packetCount"]))
            else:
                switch_acl_counters[ip].append(0)
    return switch_acl_counters
Пример #53
0
    def test_should_convert_header_values_to_basestring(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1,
                        headers={'X-Test' : 123})

        # when
        with self.captured_headers() as headers:
            response = client.ping()
            self.assertTrue(response)

        # then
        self.assertTrue('x-test' in headers)
        self.assertEqual(headers['x-test'], '123')
Пример #54
0
    def test_should_not_override_content_length(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1,
                        headers={'Content-Length' : 'invalid value'})

        # when
        with self.captured_headers() as headers:
            response = client.ping()
            self.assertTrue(response)

        # then
        self.assertTrue('content-length' in headers)
        self.assertNotEqual(headers['content-length'], 'invalid value')
Пример #55
0
    def test_should_add_additional_headers(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1,
                        headers={'X-My-Header' : 'Test'})

        # when
        with self.captured_headers() as headers:
            response = client.ping()
            self.assertTrue(response)

        # then
        self.assertTrue('x-my-header' in headers)
        self.assertEqual(headers['x-my-header'], 'Test')
Пример #56
0
    def test_should_extract_headers(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1)

        # when
        with self.captured_headers() as headers:
            response = client.ping()
            self.assertTrue(response)

        # then
        self.assertTrue(len(headers) > 0)
        self.assertTrue('content-type' in headers)
        self.assertEqual(headers['content-type'], 'application/json-rpc')
Пример #57
0
    def test_get_intf_counters_default(self):
        """ Test get_intf_counters with no interface specified
        """
        from mock import MagicMock
        from jsonrpclib import Server
        switch = Server('https://*****:*****@10.10.10.11:443/command-api')
        response = []
        response.append({})
        response[0][u'interfaces'] = self.reference

        switch.runCmds = MagicMock(return_value=response)
        (propername, counters) = app.get_intf_counters(switch)
        self.assertDictEqual(counters, self.reference['Management1'])
Пример #58
0
    def test_should_override_global_headers(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1,
                        headers={'X-Test' : 'Global'})

        # when
        with self.captured_headers() as headers:
            with client._additional_headers({'X-Test' : 'Method'}) as cl:
                response = cl.ping()
                self.assertTrue(response)

        # then
        self.assertTrue('x-test' in headers)
        self.assertEqual(headers['x-test'], 'Method')
Пример #59
0
    def test_should_add_custom_headers_to_methods(self):
        # given
        client = Server('http://localhost:{0}'.format(self.port), verbose=1)

        # when
        with self.captured_headers() as headers:
            with client._additional_headers({'X-Method' : 'Method'}) as cl:
                response = cl.ping()

            self.assertTrue(response)

        # then
        self.assertTrue('x-method' in headers)
        self.assertEqual(headers['x-method'], 'Method')
Пример #60
0
def find_source_switch(unsorted_switch_list,source_switch,adjacency_list,source_ip):
    for i in range(len(unsorted_switch_list)):
        for switch in unsorted_switch_list:
            #print switch 
            switch_cli = Server( "http://*****:*****@"+switch+"/command-api" )
            response_arp = switch_cli.runCmds( 1, ["enable","show ip arp"])
            arp_list = response_arp[1]["ipV4Neighbors"]
            interface_name = ""
            for num in range(len(arp_list)):
                if arp_list[num]["address"] == source_ip:
                    interface_name = arp_list[num]["interface"].split(' ')[1]
                    break
            nei = find_neighbor(switch,interface_name,adjacency_list)
            if nei == source_switch :
                return switch