Nov-25-2017, 07:16 PM
Hi all
im trying to get some reports from my network devices with netmiko.
i implement script that log into list of devices and runs commands from list of commands.
now, i add all to be export to mail.
the issue, its send me just the output from the last directory.
this is my code
im trying to get some reports from my network devices with netmiko.
i implement script that log into list of devices and runs commands from list of commands.
now, i add all to be export to mail.
the issue, its send me just the output from the last directory.
this is my code
#!/usr/bin/env python #This script log to list of devices, run lists of commands and send all results to mail from __future__ import absolute_import, division, print_function import json import netmiko import os import sys import signal import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import Encoders signal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken pipe signal.signal(signal.SIGINT, signal.SIG_DFL) #KeyboardInterrupt: Ctrl-C if len(sys.argv) < 3: print('Usage: cmdrunner.py commands.txt devices.json') exit() netmiko_exceptions = (netmiko.ssh_exception.NetMikoAuthenticationException, netmiko.ssh_exception.NetMikoTimeoutException) with open(sys.argv[1]) as cmd_file: commands = cmd_file.readlines() with open(sys.argv[2]) as dev_file: devices = json.load(dev_file) for device in devices: try: print('~'*40) print('connection to device', device['ip']) connection = netmiko.ConnectHandler(**device) newdir = connection.base_prompt for command in commands: filename = command.replace(' ', '_') + '.txt' filename = '/'.join((newdir, filename)) with open(filename, 'w') as out_file: out_file.write(connection.send_command(command) + '\n') filenames = [os.path.join(newdir, f) for f in os.listdir(newdir)] connection.disconnect() except netmiko_exceptions as e: print('Failed to ', device['ip'], e) fromaddr = "server ip" toaddr = "myip" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "TEST" body = "TEST" msg.attach(MIMEText(body, 'plain')) #files = newdir #filenames = [os.path.join(files, f) for f in os.listdir(files)] for file in filenames: part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(part) server = smtplib.SMTP('smtp-ip') text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()