def runCommand(user,
               password,
               address,
               port,
               commands,
               output="json",
               protocol="https"):
    """ Function to connect to EAPI interface on a switch and send commands to it, the routine will return
        the output of each command in JSON format by default.
        user - username to access switch with, requires correct privledge level to run the required commands
        password - password for above user
        address - ip or url for target switch
        port - tcp port to access the EAPI interface, normally 443
        commands - list of commands to pass to the switch
        option - protocol to use for EAPI session http, https, or local (unix sockets)
        output - output format to be return by the EAPI options are txt or json """

    # Work arround for ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)
    # import ssl

    ssl._create_default_https_context = ssl._create_unverified_context

    if protocol == "http":
        #Connect to Switch via HTTP eAPI
        switch = Server("http://" + user + ":" + password + "@" + address +
                        ":" + str(port) + "/command-api")
    elif protocol == "https":
        #Connect to Switch via HTTPS eAPI
        switch = Server("https://" + user + ":" + password + "@" + address +
                        ":" + str(port) + "/command-api")
    elif protocol == "local":
        # Connect to Switch via Unix Socket
        EAPI_SOCKET = 'unix:/var/run/command-api.sock'
        switch = Server(EAPI_SOCKET)
    # capture Connection problem messages:
    try:
        response = switch.runCmds(1, commands, output)
        jsonrpclib.history.clear()
    except socket.error, error:
        error_code = error[0]
        if error_code == errno.ECONNREFUSED:  # Raise exception if connection is refused by switch
            con_error = str("[Error:" + str(error_code) +
                            "] Connection Refused!(eAPI not configured?)")
        elif error_code == errno.EHOSTUNREACH:  # Raise exception if switch is unreachable from host
            con_error = str("[Error:" + str(error_code) +
                            "] No Route to Host(Switch powered off?)")
        elif error_code == errno.ECONNRESET:  # Raise exception if connection is refset by the switch
            con_error = str("[Error:" + str(error_code) +
                            "] Connection RST by peer (Restart eAPI)")
        elif error_code == 8:  # Raise exception if switch hostname cannot be resolved in DNS
            con_error = str(
                "[Error:" + str(error_code) +
                "] Host/Server name not resolved (Check DNS or Host File)")
        else:
            # Unknown error - report error number and error string (should capture all)
            con_error = str("[Error:" + str(error_code) + "] " + error[1])
        return con_error
Пример #2
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()
Пример #3
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)
Пример #4
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
Пример #5
0
def xbmcGetMovies():
    server = Server(xbmcMakeUrl() + '/jsonrpc')
    data = server.VideoLibrary.GetMovies(properties=[
        'title', 'year', 'plot', 'thumbnail', 'file', 'fanart', 'studio',
        'trailer'
    ])
    return dumps(data)
Пример #6
0
def xbmcNowPlaying():
    server = Server(xbmcMakeUrl() + '/jsonrpc')
    player = server.Player.GetActivePlayers()
    application = server.Application.GetProperties(
        properties=['muted', 'volume', 'version'])
    if player:
        player = player[0]
        if player[u'type'] == 'video':
            try:
                playerInfo = server.Player.GetProperties(
                    playerid=player[u'playerid'],
                    properties=[
                        'speed', 'position', 'totaltime', 'time', 'percentage'
                    ])
            except:
                return
            if playerInfo:
                try:
                    itemInfo = server.Player.GetItem(
                        playerid=player[u'playerid'],
                        properties=[
                            'thumbnail', 'showtitle', 'year', 'episode',
                            'season', 'fanart'
                        ])
                    return dumps({
                        'playerInfo': playerInfo,
                        'itemInfo': itemInfo,
                        'app': application
                    })
                except:
                    return
Пример #7
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']))
Пример #8
0
def socket_recovery():
    while True:
        sleep(interval)
        if os.path.exists('/var/run/command-api.sock'):
            Logging.log(VRRP_ROUTE_TRACK,
                        "Socket has recovered to recover from socket error")
            return Server("unix:/var/run//command-api.sock")
Пример #9
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")
Пример #10
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)
Пример #11
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 = {}
Пример #12
0
 def ControlPlayer(self, action, value=''):
     """ Various commands to control XBMC Player """
     self.logger.debug("Sending control to XBMC %s", action)
     try:
         xbmc = Server(self.url('/jsonrpc', True))
         if action == 'seek':
             player = xbmc.Player.GetActivePlayers()[0]
             return xbmc.Player.Seek(playerid=player[u'playerid'],
                                     value=float(value))
         elif action == 'jump':
             player = xbmc.Player.GetActivePlayers()[0]
             return xbmc.Player.GoTo(playerid=player[u'playerid'],
                                     to=int(value))
         elif action == 'party':
             return xbmc.Player.Open(item={'partymode': 'audio'})
         elif action == 'getsub':
             return xbmc.Addons.ExecuteAddon(
                 addonid='script.xbmc.subtitles')
         elif action == 'volume':
             return xbmc.Application.SetVolume(volume=int(value))
         else:
             return xbmc.Input.ExecuteAction(action=action)
     except Exception, e:
         self.logger.exception(e)
         self.logger.error("Unable to control XBMC with action: %s", action)
         return 'error'
Пример #13
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)
Пример #14
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'])
Пример #15
0
def main():
    option, host, filename, devices, skip = arguments()
    creds = get_creds(filename)
    user = creds["user"]
    password = creds["password"]

    url = 'https://' + user + ':' + password + host + '/command-api'
    switch = Server(url)

    if option == "dumbno":
        exit(check_dumbno(switch, skip))
    elif option == "traffic_status":
        exit(check_traffic_status(switch, skip))
    elif option == "link_status":
        exit(check_link_status(switch, skip))
    elif option in status_checks:
        option = STATUS_MAP[option]
        exit(check_status(switch, option, devices, skip))
    elif option in rate_checks:
        direction = DIRECTION_MAP[option]
        interfaces = INTERFACE_MAP[option]
        exit(max(check_rate(switch, direction, interfaces, skip)))
    else:
        print "Invalid option"
        exit(NAGIOS_UNKNOWN)
Пример #16
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
Пример #17
0
    def NowPlaying(self):
        """ Get information about current playing item """
        self.logger.debug("Fetching currently playing information")
        try:
            kodi = Server(self.url('/jsonrpc', True))
            player = kodi.Player.GetActivePlayers()[0]
            playerid = player['playerid']

            if player['type'] == 'video':
                playerprop = ['speed', 'position', 'time', 'totaltime',
                              'percentage', 'subtitleenabled', 'currentsubtitle',
                              'subtitles', 'currentaudiostream', 'audiostreams']

                itemprop = ['title', 'season', 'episode', 'duration', 'showtitle',
                            'fanart', 'tvshowid', 'plot', 'thumbnail', 'year']

            elif player['type'] == 'audio':
                playerprop = ['speed', 'position', 'time', 'totaltime', 'percentage']
                itemprop = ['title', 'duration', 'fanart', 'artist', 'albumartist', 'album', 'track', 'artistid', 'albumid', 'thumbnail', 'year']

            app = kodi.Application.GetProperties(properties=['muted', 'volume'])
            player = kodi.Player.GetProperties(playerid=playerid, properties=playerprop)
            item = kodi.Player.GetItem(playerid=playerid, properties=itemprop)

            return {'playerInfo': player, 'itemInfo': item, 'app': app}
        except IndexError:
            return
        except Exception, e:
            self.logger.exception(e)
            self.logger.error("Unable to fetch currently playing information!")
            return
Пример #18
0
 def ControlPlayer(self, action, value=''):
     """ Various commands to control kodi Player """
     self.logger.debug("Sending control to kodi %s", action)
     try:
         kodi = Server(self.url('/jsonrpc', True))
         if action == 'seek':
             player = kodi.Player.GetActivePlayers()[0]
             return kodi.Player.Seek(playerid=player[u'playerid'], value=float(value))
         elif action == 'jump':
             player = kodi.Player.GetActivePlayers()[0]
             return kodi.Player.GoTo(playerid=player[u'playerid'], to=int(value))
         elif action == 'party':
             return kodi.Player.Open(item={'partymode': 'audio'})
         elif action == 'getsub':
             try:
                 # Frodo
                 return kodi.Addons.ExecuteAddon(addonid='script.kodi.subtitles')
             except:
                 pass
             try:
                 # Gotham
                 return kodi.GUI.ActivateWindow(window='subtitlesearch')
             except:
                 pass
         elif action == 'volume':
             return kodi.Application.SetVolume(volume=int(value))
         else:
             return kodi.Input.ExecuteAction(action=action)
     except Exception, e:
         self.logger.exception(e)
         self.logger.error("Unable to control kodi with action: %s", action)
         return 'error'
Пример #19
0
 def __connectToSwitch(self):
     try:
         return Server('https://{0}:{1}@{2}/command-api\
             '.format(self._username, self._password, self._host))
     except:
         print ('There was an error trying to connect')
         raise
Пример #20
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")
Пример #21
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
Пример #22
0
 def GetArtists(self,
                start=0,
                end=0,
                sortmethod='artist',
                sortorder='ascending',
                filter=''):
     """ Get a list of all artists """
     self.logger.debug("Fetching all artists in the music database")
     try:
         xbmc = Server(self.url('/jsonrpc', True))
         sort = {
             'order': sortorder,
             'method': sortmethod,
             'ignorearticle': True
         }
         properties = ['thumbnail', 'fanart']
         limits = {'start': int(start), 'end': int(end)}
         filter = {
             'field': 'artist',
             'operator': 'contains',
             'value': filter
         }
         return xbmc.AudioLibrary.GetArtists(properties=properties,
                                             limits=limits,
                                             sort=sort,
                                             filter=filter)
     except Exception, e:
         self.logger.exception(e)
         self.logger.error("Unable to fetch artists!")
         return
Пример #23
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)
Пример #24
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))
Пример #25
0
    def Playlist(self, type='audio'):
        """ Get a playlist from kodi """
        self.logger.debug("Loading Playlist of type %s", type)
        kodi = Server(self.url('/jsonrpc', True))
        if type == 'video':
            return kodi.Playlist.GetItems(playlistid=1, properties=['year', 'showtitle', 'season', 'episode', 'runtime'])

        return kodi.Playlist.GetItems(playlistid=0, properties=['artist', 'title', 'album', 'duration'])
Пример #26
0
def initer():
    global switch
    for h in hosts:
        switch[h] = Server("https://%s:%s@%s/command-api" %
                           (username, password, h))
        response = switch[h].runCmds(1, ["show version"])
        collectd.error("Switch %s system MAC addess is %s" %
                       (h, response[0]["systemMacAddress"]))
Пример #27
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)
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)
Пример #29
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
Пример #30
0
 def Notify(self, text):
     """ Create popup in XBMC """
     self.logger.debug("Sending notification to XBMC: %s", text)
     xbmc = Server(self.url('/jsonrpc', True))
     image = 'https://raw.github.com/styxit/HTPC-Manager/master/interfaces/default/img/xbmc-logo.png'
     return xbmc.GUI.ShowNotification(title='HTPC manager',
                                      message=text,
                                      image=image)