Python Forum
Netmiko - add multiple files, from different folders to mail.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Netmiko - add multiple files, from different folders to mail.
#1
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

#!/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()
Reply
#2
We can help you better, if we can try your program on our PCs.
So I have a Linux PCs and a printer, router, ...

Can you give an sample, how I can use your code ?
Reply
#3
Hi heiner, thanks for your reply.
you need to install netmiko: Multi-vendor library to simplify Paramiko SSH connections to network devices.
https://github.com/ktbyers/netmiko

then, to create 2 files:
1. devices list.
2. commands list.

the script will run with the following command:
./results_and_send_mail.py switch_commands.txt switches.json

Instead of that, maybe you can look and help on the section of my code that adding the files to the mail?
Thanks.
Reply
#4
If only the mail part is important, you should make us a sample without netmiko.
(with fake data)
Reply
#5
Finally i succeed to to solve this.
i just add in the top an empty array
filenames = []
and
filenames.append(filename)

thanks.
Reply
#6
OK, good to hear your program runs well now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using zipfile module - finding folders not files darter1010 2 246 Apr-06-2024, 07:22 AM
Last Post: Pedroski55
  python convert multiple files to multiple lists MCL169 6 1,522 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  splitting file into multiple files by searching for string AlphaInc 2 877 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Create new folders and copy files cocobolli 3 1,439 Mar-22-2023, 10:23 AM
Last Post: Gribouillis
  Copy only hidden files and folders with rsync Cannondale 2 997 Mar-04-2023, 02:48 PM
Last Post: Cannondale
  Merging multiple csv files with same X,Y,Z in each Auz_Pete 3 1,146 Feb-21-2023, 04:21 AM
Last Post: Auz_Pete
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 955 Feb-15-2023, 05:34 PM
Last Post: zsousa
  Find duplicate files in multiple directories Pavel_47 9 3,064 Dec-27-2022, 04:47 PM
Last Post: deanhystad
  I have an issue with Netmiko Error reading SSH protocol banner omarhegazy 2 3,561 May-16-2022, 06:05 PM
Last Post: omarhegazy
  Extract parts of multiple log-files and put it in a dataframe hasiro 4 2,081 Apr-27-2022, 12:44 PM
Last Post: hasiro

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020