Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified getHostname, getFQDN and getCPU to utilize regEX #27

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
*.swp
*.pyc
*.py[cod]
eapiLib.py
eapiCalls.py
*.DS_Store
*.swap
*.pyo
*__pycache__
*.sublime-project
*.sublime-workspace
*.project
*.settings
.pydevproject
15 changes: 11 additions & 4 deletions core/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ def createDevice(p_args):

# sets dev_name if -n is used, otherwise generic 'dev' is used
dev_name = p_args['name'] if p_args['name'] else 'dev'

dev = device(dev_name, p_args['manufacturer'], p_args['ip_address'])

if p_args['username'] and p_args['password']:
Expand Down Expand Up @@ -207,8 +208,7 @@ def display():

parser = argparse.ArgumentParser(description='\
input -f [function] -i [ip_address] \
-u [username] -p [password] -m [manufacturer]'\
)
-u [username] -p [password] -m [manufacturer]')

parser.add_argument('-f', '--function', help='i.e. -f IntfStatus, show version')
parser.add_argument('-c', '--cli', help='i.e. same as -f, for redundancy')
Expand All @@ -221,11 +221,18 @@ def display():

args = vars(parser.parse_args())

#print args
if args['display'] or args['ip_address'] == None or args['manufacturer'] == None:
display()
elif args['function'] == None and args['cli'] == None:
display()
else:
createDevice(args)


# Added by Yandy:
# For test running by passing args to __init__
# instead of command line arguments
# method_args = {'name': 'sw1', 'username': 'arista', 'password': 'arista',
# 'cli': 'getHostname', 'manufacturer': 'arista', 'ip_address': 'veos-03',
# 'function': ''}
# createDevice(method_args)

101 changes: 40 additions & 61 deletions vendors/arista/apis/eapi/eapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@
# ------------------------------------------------------------------
# Arista eAPI CPAL Integration
#
# Written by:
# Written by:
# Jason Edelman
# Updated by:
# Updated by:
# Yandy Ramirez, @IP_Yandy
# ------------------------------------------------------------------


from jsonrpclib import Server
from configobj import ConfigObj
from cpal.scripts.utils import convertSize
# from datetime import datetime
from datetime import datetime
import re


class arista():

Expand All @@ -28,13 +30,14 @@ def __init__(self, address, obj):

# self.version = self.getVersionInfo() must be place here
# after call to jconnect() and before getFacts()
#self.version_info = self.getVersionInfo()
# self.version_info = self.getVersionInfo()

#self.facts = self.refreshFacts()
# self.facts = self.refreshFacts()

def jconnect(self):

connect_string = "https://" + self.username + ":" + self.password + "@" + self.address + "/command-api"
connect_string = "https://" + self.username + ":" + self.password + "@" +\
self.address + "/command-api"

switch = 'DNE'
try:
Expand All @@ -49,18 +52,18 @@ def setLogin(self, username, password):
self.username = username
self.password = password

def getCmd(self,cmd):
return self.native.runCmds( 1, [cmd] )
def getCmd(self, cmd):
return self.native.runCmds(1, [cmd])

def getPlatform(self):
#output = self.getCmd('show version')
# output = self.getCmd('show version')
if not self.version_info:
self.getVersionInfo()

return self.version_info[0]["modelName"]

def getserialNumber(self):
#output = self.getCmd('show version')
# output = self.getCmd('show version')

if not self.version_info:
self.getVersionInfo()
Expand All @@ -70,19 +73,18 @@ def getserialNumber(self):
return self.version_info[0]["serialNumber"]

def getUptime(self):
output = self.native.runCmds( 1, ["show uptime"],"text")
c = output[0]['output']
up_time = c[13:].split(',')[0]
return up_time
output = self.native.runCmds(1, ["show uptime"], "text")[0]['output']
# gets uptime if output is in H:M or (|) in "number Mins|Days"
up_split = re.split(r"up\s+?", output)

uptime = re.match(r'(^(\d{1,3}:\d{1,3})|^(\d{1,3})\s\w+)', up_split[1]).group(0)
return uptime

def getCPU(self):
output = self.native.runCmds(1, ['show processes top once'], 'text')
# cpu = index 0 of returned list split by new-lines
# grabs the 3rd line which contains Cpu values at index [2]
cpu_line = output[0]['output'].split('\n')[2]
output = self.native.runCmds(1, ['show processes top once'], 'text')[0]
regex_cpu = re.search(r"\d+\.\d*%(?=us)", output['output'])
cpu = regex_cpu.group(0)

# cpu is then narrowed down to the actual usage, up to the first instance of a comma ','
cpu = cpu_line[0:cpu_line.find(',')]
return cpu

def getHostname(self):
Expand All @@ -94,31 +96,17 @@ def getHostname(self):
output = self.getCmd("show hostname")
hostname = output[0]['hostname']
else:
# begins a breakdown of finding the hostname inside a string
# could probably be more efficient, but works for now
output = self.native.runCmds(1, ['show lldp local-info'], 'text')

# gets the 4th line of output which contains the hostname in FQDN format
host_line = output[0]['output'].split('\n')[3]

# splits the line into a list at the delimeter and assigns the 2nd indext to fqdn
# 2nd index contains the hostname
host_fqdn = host_line.split(':')[1]

# assignes the first index of fqdn after splitting at the delimeter (.)
# this splits the fqdn into three parts, the [hostname, domain, suffix]
hostname = host_fqdn.split('.')[0]

# indexing removes the " from the begining of the hostname
return hostname[2:]
output = self.native.runCmds(1, ['show lldp local-info'], 'text')[0]

regex_host = re.search(r"(?<=System Name: \").*?(?=\.)", output['output'])
hostname = regex_host.group(0)

return hostname

def getFQDN(self):
'''
'''
Returns the device's FQDN hostname.domain.suffix
has not been added to main.py yet, waiting to make sure
has not been added to main.py yet, waiting to make sure
their's support accross platforms
'''

Expand All @@ -129,25 +117,15 @@ def getFQDN(self):
hostname = output[0]['fqdn']

else:
# begins a breakdown of finding the hostname inside a string
# could probably be more efficient, but works for now
output = self.native.runCmds(1, ['show lldp local-info'], 'text')

# gets the 4th line of output which contains the hostname in FQDN format
host_line = output[0]['output'].split('\n')[3]

# splits the line into a list at the delimeter and assigns the 2nd indext to fqdn
# 2nd index contains the hostname
hostname = host_line.split(':')[1]

# indexing removes the quotes (") from the begining and end of the hostname
return hostname[2:-1]
output = self.native.runCmds(1, ['show lldp local-info'], 'text')[0]

regex_fqdn = re.search(r"(?<=System Name: \").*?(?=\")", output['output'])
hostname = regex_fqdn.group(0)

return hostname

def getfreeMemory(self):
#output = self.getCmd('show version')
# output = self.getCmd('show version')

# checks if self.version_info is not empy
if not self.version_info:
Expand All @@ -156,7 +134,7 @@ def getfreeMemory(self):
return self.version_info[0]['memFree']

def gettotalMemory(self):
#output = self.getCmd('show version')
# output = self.getCmd('show version')

# checks if self.version_info is not empy
if not self.version_info:
Expand All @@ -169,12 +147,12 @@ def gettotalMemory(self):
# speeds up the process and makes it more efficient.
def getVersionInfo(self):
''' returns a 'show version' output as a dictionary '''

self.version_info = self.getCmd('show version')
return self.version_info

def _versionList(self):
'''
'''
Gets version and converts to a list of Ivalues
this allows comparisons between software versions
by calling int(on an index)
Expand All @@ -188,7 +166,7 @@ def getVersion(self):
# checks if self.version_info is not empy
if not self.version_info:
self.getVersionInfo()

return self.version_info[0]['version']

def getFacts(self):
Expand All @@ -198,7 +176,7 @@ def getFacts(self):
self.getVersionInfo()

sh_ver = self.getVersion()
#sh_lldp_localinfo = self.native.runCmds( 1, ["show lldp local-info"],"text")
# sh_lldp_localinfo = self.native.runCmds( 1, ["show lldp local-info"],"text")
cpu_utilization = self.getCPU()
free_memory = self.getfreeMemory()
total_memory = self.gettotalMemory()
Expand All @@ -210,9 +188,10 @@ def getFacts(self):

var_name = self.obj

self.facts = {'hostname': hostname, 'connect_ip': connect_ip, 'platform':platform, 'version':sh_ver,\
'serial_number':serial_number, 'system_uptime':uptime, 'cpu_utilization':cpu_utilization, \
'free_system_memory': free_memory, 'total_sytem_memory': total_memory, 'vendor':'arista', 'var_name':var_name}
self.facts = {'hostname': hostname, 'connect_ip': connect_ip, 'platform': platform,
'version': sh_ver, 'serial_number': serial_number, 'system_uptime': uptime,
'cpu_utilization': cpu_utilization, 'free_system_memory': free_memory,
'total_sytem_memory': total_memory, 'vendor': 'arista', 'var_name': var_name}

config = ConfigObj('/home/cisco/apps/cpal/core/device_tags.ini').dict()
for key in config.keys():
Expand Down