Can I save the results of a script to file?


I need to login to a switch, run a 'show' command, then save the output to a file. I need to do this for 30+ switches, and would preferably like to save the output of each switch's show command to a filename matching it's hostname (SwitchA output to switcha.txt).
I know how to write a script to run the show command, but I don't know how to save it to a file.
Any ideas?
Thank you!

6 replies

If you run it as a task you can have it email you the results.
Userlevel 2
You could save the configuration as a script (give it a name) then copy the files from your switch stack, say tftp off. It saves it as an .xsf file if that would work for you. Then you could copy the file off the switch stack to a centralized location. If you have netsight you can automate backups of your stacks.

Slot-1 SwitchA # save configuration as-script SwitchA
Do you want to save configuration to script SwitchA.xsf? (y/N) Yes
Saving configuration to script SwitchA.xsf on master .... done!
Synchronizing script to backup ... done!
Saving script on Standbys (Slots: 3,4).

Script saved on Standby (Slot-4): done!
Script saved on Standby (Slot-3): done!
Userlevel 5
Depending on the EXOS release, you may have python available. A python script can do this for you.
Userlevel 6
easiest would be using Netsight, create a script and run it on all your switches.

Next easiest would be run below python script on a PC that connects to each switch and run the commands you need.
#!/usr/bin/env python
# This script connect to one or more switches and execute the commands

__version__ = '0.80'

import telnetlib
import re
import argparse
import sys
import paramiko
import time

class ExosClass:
def __init__(self, host, user='admin',password=''):
self.host=host
self.user=user
self.password=password
self.prompt=re.compile(r'\S+\d+\s[#>]\s')
self.loginprompt=r"login"
self.passwordprompt=r"assword"
self.failedlogin = r"Login incorrect"
self.connected = True
try:
self._tn = telnetlib.Telnet(self.host)
self._tn.set_debuglevel(0)
self._tn.read_until(self.loginprompt,10)
self._tn.write(self.user + "\n")
self._tn.expect([self.passwordprompt],10)
self._tn.write(self.password + "\n")
loginresponse = self._tn.expect([self.prompt,self.failedlogin])
if loginresponse[0] == 1:
print "Login failed"
self.connected = False
self._tn.close()
else:
self._tn.write("disable clipaging\n")
self._tn.expect([self.prompt])
except:
print "Could not connect to switch "+host
self.connected = False

def exit(self):
self._tn.close()

def isConnected(self):
if self.connected:
return True
else:
return False

def cmd(self,cmd,timeout=30):
self._tn.write(cmd + "\n")
s=self._tn.expect([self.prompt],timeout)[2].lstrip(cmd).lstrip('\n\r')
if s.count('\n')>1:
return s[:s.rfind('\n')]
else:
return "OK"

def cmdFast(self,cmd,timeout=30):
self._tn.write(cmd+"\n")
output=""
go = True
while go:
time.sleep(0.5)
newoutput = self._tn.read_very_eager()
if len(newoutput) == 0:
lastline = output.splitlines()[-1]
if re.search(self.prompt,lastline):
go = False
else:
output += newoutput
return output

def exitwithsave(self,save):
if save == "Y":
print "Saving config"
self._tn.write("save\n")
output=""
go = True
try:
while go:
time.sleep(0.5)
newoutput = self._tn.read_very_eager()
if re.search(r'.*(y/N).*',newoutput):
go = False
self._tn.write(save+"\n")
go = True
while go:
time.sleep(0.5)
newoutput += self._tn.read_very_eager()
if re.search(r'.*successfully.*',newoutput):
go = False
print newoutput
except:
print "except"
self._tn.close()

self._tn.close()
self.connected = False

class SSH2EXOS:
def __init__(self, switch, user='admin',password=''):
self.connected = True
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(switch,username=user,password=password)
stdin, stdout, stderr = self.client.exec_command("disable clipaging")
stdin.close()

def cmdFast(self,cmd,timeout=30):
stdin, stdout, stderr = self.client.exec_command(cmd)
stdin.close()
return cmd+"\n"+stdout.read()

def exit(self):
self.client.close()
self.connected = False

def exitwithsave(self,save):
if save == "Y":
print "Saving config"
try:
stdin, stdout, stderr = self.client.exec_command('save')
stdin.write(save)
stdin.flush()
print stdout.read()
self.client.close()
self.connected = False
except:
print "except"
self.client.close()
self.connected = False

def isConnected(self):
if self.connected:
return True
else:
return False

def checkIP(address):
m = re.search('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',address)
if m:
return m.group(1)
else:
return None

def main():
parser = argparse.ArgumentParser(description='Connect to switch(es) and run commands')
parser.add_argument("-s", dest="switch", default=None, help="Switch IP")
parser.add_argument("-u", dest="user", default="admin", help="Username")
parser.add_argument("-p", dest="password", default="", help="Password, leave out for none")
parser.add_argument("-f", dest="file", default=None, help="File containing switch IP addresses")
parser.add_argument("-c", dest="cmdfile", default=None, help="File containing switch commands")
parser.add_argument("--ssh", dest="SSH", action='store_true', help="Use SSH to access switches instead of telnet")
parser.add_argument("--save", dest="save", action='store_true', default=False, help="Save config on switch")
parser.add_argument("--print", dest="cmdprint", action='store_true', default=False, help="Print commands being executed")
args = parser.parse_args()

switches = []
validInput = True
if args.switch:
if checkIP(args.switch):
switches.append(args.switch)
else:
print "No Valid IP address specified with -s"
validInput = False
elif args.file:
try:
f = open(args.file,'r')
for line in f.read().splitlines():
switches.append(line)
f.close()
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Something wrong with opening the switch file"
validInput = False
else:
print "No valid option -s or -f specified"
validInput = False

if args.cmdfile:
f = open(args.cmdfile,'r')
cmds = []
for line in f.read().splitlines():
cmds.append(line)
f.close()
else:
print "No file with commands given"
validInput = False

if args.save:
save = "Y"
else:
save = "N"
if validInput:
for switch in switches:
print "Executing on switch "+switch,
sys.stdout.flush()
if args.SSH:
MySess = SSH2EXOS(switch,args.user,args.password)
else:
MySess = ExosClass(switch,args.user,args.password)

if MySess.isConnected():
print " connected, running commands"
for cmd in cmds:
if args.cmdprint:
print cmd +"\n"
print MySess.cmd(cmd)
MySess.exitwithsave(save)

if __name__ == "__main__":
try:
main()
except SystemExit:
pass
Userlevel 7
OscarK wrote:

easiest would be using Netsight, create a script and run it on all your switches.

Next easiest would be run below python script on a PC that connects to each switch and run the commands you need.
#!/usr/bin/env python
# This script connect to one or more switches and execute the commands

__version__ = '0.80'

import telnetlib
import re
import argparse
import sys
import paramiko
import time

class ExosClass:
def __init__(self, host, user='admin',password=''):
self.host=host
self.user=user
self.password=password
self.prompt=re.compile(r'\S+\d+\s[#>]\s')
self.loginprompt=r"login"
self.passwordprompt=r"assword"
self.failedlogin = r"Login incorrect"
self.connected = True
try:
self._tn = telnetlib.Telnet(self.host)
self._tn.set_debuglevel(0)
self._tn.read_until(self.loginprompt,10)
self._tn.write(self.user + "\n")
self._tn.expect([self.passwordprompt],10)
self._tn.write(self.password + "\n")
loginresponse = self._tn.expect([self.prompt,self.failedlogin])
if loginresponse[0] == 1:
print "Login failed"
self.connected = False
self._tn.close()
else:
self._tn.write("disable clipaging\n")
self._tn.expect([self.prompt])
except:
print "Could not connect to switch "+host
self.connected = False

def exit(self):
self._tn.close()

def isConnected(self):
if self.connected:
return True
else:
return False

def cmd(self,cmd,timeout=30):
self._tn.write(cmd + "\n")
s=self._tn.expect([self.prompt],timeout)[2].lstrip(cmd).lstrip('\n\r')
if s.count('\n')>1:
return s[:s.rfind('\n')]
else:
return "OK"

def cmdFast(self,cmd,timeout=30):
self._tn.write(cmd+"\n")
output=""
go = True
while go:
time.sleep(0.5)
newoutput = self._tn.read_very_eager()
if len(newoutput) == 0:
lastline = output.splitlines()[-1]
if re.search(self.prompt,lastline):
go = False
else:
output += newoutput
return output

def exitwithsave(self,save):
if save == "Y":
print "Saving config"
self._tn.write("save\n")
output=""
go = True
try:
while go:
time.sleep(0.5)
newoutput = self._tn.read_very_eager()
if re.search(r'.*(y/N).*',newoutput):
go = False
self._tn.write(save+"\n")
go = True
while go:
time.sleep(0.5)
newoutput += self._tn.read_very_eager()
if re.search(r'.*successfully.*',newoutput):
go = False
print newoutput
except:
print "except"
self._tn.close()

self._tn.close()
self.connected = False

class SSH2EXOS:
def __init__(self, switch, user='admin',password=''):
self.connected = True
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(switch,username=user,password=password)
stdin, stdout, stderr = self.client.exec_command("disable clipaging")
stdin.close()

def cmdFast(self,cmd,timeout=30):
stdin, stdout, stderr = self.client.exec_command(cmd)
stdin.close()
return cmd+"\n"+stdout.read()

def exit(self):
self.client.close()
self.connected = False

def exitwithsave(self,save):
if save == "Y":
print "Saving config"
try:
stdin, stdout, stderr = self.client.exec_command('save')
stdin.write(save)
stdin.flush()
print stdout.read()
self.client.close()
self.connected = False
except:
print "except"
self.client.close()
self.connected = False

def isConnected(self):
if self.connected:
return True
else:
return False

def checkIP(address):
m = re.search('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',address)
if m:
return m.group(1)
else:
return None

def main():
parser = argparse.ArgumentParser(description='Connect to switch(es) and run commands')
parser.add_argument("-s", dest="switch", default=None, help="Switch IP")
parser.add_argument("-u", dest="user", default="admin", help="Username")
parser.add_argument("-p", dest="password", default="", help="Password, leave out for none")
parser.add_argument("-f", dest="file", default=None, help="File containing switch IP addresses")
parser.add_argument("-c", dest="cmdfile", default=None, help="File containing switch commands")
parser.add_argument("--ssh", dest="SSH", action='store_true', help="Use SSH to access switches instead of telnet")
parser.add_argument("--save", dest="save", action='store_true', default=False, help="Save config on switch")
parser.add_argument("--print", dest="cmdprint", action='store_true', default=False, help="Print commands being executed")
args = parser.parse_args()

switches = []
validInput = True
if args.switch:
if checkIP(args.switch):
switches.append(args.switch)
else:
print "No Valid IP address specified with -s"
validInput = False
elif args.file:
try:
f = open(args.file,'r')
for line in f.read().splitlines():
switches.append(line)
f.close()
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Something wrong with opening the switch file"
validInput = False
else:
print "No valid option -s or -f specified"
validInput = False

if args.cmdfile:
f = open(args.cmdfile,'r')
cmds = []
for line in f.read().splitlines():
cmds.append(line)
f.close()
else:
print "No file with commands given"
validInput = False

if args.save:
save = "Y"
else:
save = "N"
if validInput:
for switch in switches:
print "Executing on switch "+switch,
sys.stdout.flush()
if args.SSH:
MySess = SSH2EXOS(switch,args.user,args.password)
else:
MySess = ExosClass(switch,args.user,args.password)

if MySess.isConnected():
print " connected, running commands"
for cmd in cmds:
if args.cmdprint:
print cmd +"\n"
print MySess.cmd(cmd)
MySess.exitwithsave(save)

if __name__ == "__main__":
try:
main()
except SystemExit:
pass

that would be even better using json-rpc, if running 21.1+.
Userlevel 7
Well, if you have a GNU/Linux server and switches with a recent version of EXOS you could add an SSH key to the switches and use a simple bash script:
for S in switch1 switch2 switch3; do ssh -i the_private_key "$S" "show ports no-refresh" > "${S}.txt"; done[/code]Thanks,
Erik

Reply