cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
322
Views
1
Helpful
2
Replies

Python E-Mail script for Nexus switches

alex_kross
Frequent Visitor
Frequent Visitor

Hello folks,

It looks like nobody here have shared a sample Python script to send email from Nexus switches.

So, here is my one:

 

#!/isan/bin/python3

import smtplib
from os import getenv
from sys import argv, stderr
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from cisco import set_global_vrf

from cisco.system import System
hostname = System().get_hostname() # includes domain part

if len(argv) < 2 or argv[1] in ('-h', '--help'):
    print("Usage:\n\tpython {} \"<message text>\" [subject [recipient (To:) [mailserver IP-address [vrf name or Id]]]]".format(argv[0]))
    exit(1)

text = argv[1] # at least one argument is mandatory

msg = MIMEMultipart('alternative')
msg['From'] = f = getenv('SENDEMAILFROM') or hostname.replace('.', '@', 1)
msg['Subject'] = s = getenv('SENDEMAILSUBJ') or (argv[2] if len(argv) > 2 else 'Unspecified subject')
msg['To'] = t = getenv('SENDEMAILTO') or (argv[3] if len(argv) > 3 else '<your@company.net>')
server = getenv('SENDEMAILSERVER') or (argv[4] if len(argv) > 4 else '<your e-mail server ip address in management vrf>') # port = 25
set_global_vrf(getenv('SENDEMAILVRF') or (argv[5] if len(argv) > 5 else 'management'))

header = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{}</title>
</head>
<text>
<pre>
'''.format(s)
footer = '''
</pre>
</text>
</html>
'''
msg.attach(MIMEText(text, 'plain'))
msg.attach(MIMEText(header + text + footer, 'html'))
# According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred.

try:
    m = smtplib.SMTP(server, 25)
    m.sendmail(f, t, msg.as_string())
    m.quit()
except smtplib.SMTPException:
    print("Failed to send E-Mail to {} on subject: \"{}\".".format(t, s, stderr))
    raise

exit(0)

E.g. use it in event manager applet like this:

action <#> cli python /scripts/sendemail.py "<Body text>." "<E-Mail subject>"

 

 

 

2 Replies 2

Mark Elsen
Hall of Fame
Hall of Fame

 

  - @alex_kross       Great! What is the purpose of the script ? Why do you want to send emails from nexus ?

  M.



-- Let everything happen to you  
       Beauty and terror
      Just keep going    
       No feeling is final
Reiner Maria Rilke (1899)

alex_kross
Frequent Visitor
Frequent Visitor

@Mark Elsen The example purpose might be as a part of action list in an event manager applet tied to a track object of an ip sla. That's because of mail server option is absent in NX-OS.