Advertisement
Gus1202

mandar mail con interfaz v5

May 3rd, 2022
865
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.54 KB | None | 0 0
  1. from ctypes import alignment
  2. from tkinter import *
  3. import os
  4. from tkinter import messagebox
  5. from tkinter import PhotoImage
  6. import win32com.client as win32
  7. from netmiko import ConnectHandler
  8. from datetime import datetime
  9. import time
  10. import os
  11. import threading
  12. import pythoncom
  13. import telnetlib
  14.  
  15. def acerca_de():
  16.     messagebox.showinfo("ACERCA DE...","""by Gustavo P. Fernandez 2022
  17.  
  18. comandos = []
  19. ruta = (os.path.abspath(os.getcwd()))
  20. root = Tk()
  21. barra_de_menu = Menu(root)
  22. menu_ayuda = Menu(root,barra_de_menu, tearoff=0)
  23. menu_ayuda.add_command(label="Acerca de...", command=acerca_de)
  24. barra_de_menu.add_cascade(label="Ayuda", menu=menu_ayuda)
  25. root.config(background="light gray",menu=barra_de_menu)
  26. root.geometry("610x550")
  27. root.title("enviar mail")
  28. root.iconbitmap("Logo2.ico")
  29.  
  30.  
  31. def recolectar():
  32.     putty = r.get()
  33.     comandos = []
  34.     if var1.get():
  35.         comandos.append("show version")
  36.     if var2.get():
  37.         comandos.append("show inventory")
  38.     if var3.get():
  39.         comandos.append("show log")
  40.     a = caja_comando_manual.get()
  41.     if a != "":
  42.         a.strip()
  43.         comandos.append(a)
  44.     if var4.get():
  45.         comandos.append("show running-config")
  46.  
  47.  
  48.  
  49.     address = direccion_host_box.get()
  50.     user = usuario_box.get()
  51.     psw = password_box.get()
  52.     hacia = direcciones_destinatario_box.get()
  53.     repetir = repetir_box.get()
  54.     cantidad = cant_veces_box.get()
  55.     cuerpo = cuerpo_c.get("1.0",END)
  56.     asunto = asunto_e.get()
  57.     nombre2 = ""
  58.    
  59.     try:        
  60.         repetir = int(repetir)
  61.         cantidad = int(cantidad)
  62.     except ValueError:
  63.         messagebox.showerror("ERROR","el campo cantidad de veces o repetir debe ser un numero entero mayor que 0")
  64.     if address == "" or user == "" or psw == "" or hacia == "" or repetir == "":
  65.         messagebox.showerror("ERROR","los campos no deben estar vacios")
  66.     if repetir <= 0:
  67.         messagebox.showerror("ERROR","el campo numero debe ser un numero entero mayor que 0")
  68.  
  69.  
  70.     def  mandar_mail():
  71.         pythoncom.CoInitialize()
  72.         def conectarse():
  73.             if putty == "SSH":
  74.                 try:
  75.                     swmsc = ConnectHandler(device_type="cisco_ios", ip=address, username=user, password=psw,secret=psw)
  76.                 except:
  77.                     messagebox.showerror("ERROR","El usuario,contraseƱa o puerto es incorrecto. por favor verifique")
  78.                     exit()
  79.                 swmsc.enable()
  80.  
  81.                 timestr = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")
  82.                 timestr2 = datetime.now().strftime("%d-%m-%Y %H-%M-%S")
  83.                 for x in comandos:
  84.                     a = swmsc.send_command(x)
  85.                     command = f"{x}"
  86.                     nombre = swmsc.send_command("show running | include hostname")
  87.                     nombre = nombre.replace("hostname ","")
  88.                     nombre = nombre.replace("\n.          @@@@@@    @@@@@@  @@@@@@@           Nodo: $(hostname)","")
  89.                     nombre2 = f"{nombre} {timestr2}.txt"
  90.                     r = open(nombre2,"a")
  91.                     r.writelines(f"{command}:\n{a}\n########################################################\n")
  92.                     r.close()
  93.                     swmsc.disconnect()
  94.             elif putty == "TELNET":
  95.                 try:
  96.                     timestr = datetime.now().strftime("%d/%m/%Y-%H:%M:%S")
  97.                     timestr2 = datetime.now().strftime("%d-%m-%Y %H-%M-%S")
  98.                     for x in comandos:
  99.                         tel = telnetlib.Telnet(address)
  100.                         tel.read_until(b"sername: " or b"ogin: ")
  101.                         tel.write(user.encode("ascii")+b"\n")
  102.                         tel.read_until(b"assword: ",timeout=5)
  103.                         tel.write(psw.encode("ascii")+b"\n")
  104.                         tel.write(b"enable\n")
  105.                         tel.read_until(b"assword: ",timeout=5)
  106.                         tel.write(psw.encode("ascii")+b"\n")
  107.                         nombre = tel.read_until(b"#",timeout=5)
  108.                         nombre = nombre.decode("utf-8")
  109.                         nombre = nombre.replace("*","")
  110.                         nombre = nombre.replace("#","")
  111.                         nombre = nombre.strip()
  112.                         if x == "show running-config":
  113.                             comando = x+"\n                                                                     "
  114.                             tel.write(comando.encode("ascii")+b"\n")
  115.                             time.sleep(2)
  116.                             output = tel.set_debuglevel(1000000000)
  117.                             output = tel.read_until(b"#")
  118.                             output = output.decode("utf-8")
  119.                         else:
  120.                             comando = x+"\n                      "
  121.                             tel.write(comando.encode("ascii")+b"\n")
  122.                             time.sleep(2)
  123.                             output = tel.set_debuglevel(1000000000)
  124.                             output = tel.read_until(b"#")
  125.                             output = output.decode("utf-8")
  126.                         nombre2 = f"{nombre} {timestr2}.txt"
  127.                         r = open(nombre2,"a")
  128.                         r.writelines(f"{output}:\n")
  129.                         tel.close()
  130.                         r.close()
  131.                 except:
  132.                     messagebox.showerror("ERROR","El usuario,contraseƱa o puerto es incorrecto. por favor verifique")
  133.                     exit()
  134.  
  135.             ################################ conexion outlook
  136.             body = f"{timestr}\n{cuerpo}"
  137.        
  138.             outlook = win32.Dispatch('outlook.application')
  139.             mail = outlook.CreateItem(0)
  140.             try:
  141.                 mail.To = hacia
  142.             except:
  143.                 messagebox.showerror("ERROR","Outlook no reconoce alguno de los nombres DE DESTINO")
  144.                 exit()
  145.             mail.Subject = asunto
  146.             mail.Body = body
  147.             # mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional
  148.  
  149.             # To attach a file to the email (optional):
  150.             # attachment  = nombre2
  151.  
  152.             mail.Attachments.Add(f"{ruta}\\{nombre2}")
  153.             mail.Send()
  154.         if ping.get():
  155.             if os.name == "nt":
  156.                 response = os.system("ping " + address + " -n 1")
  157.             elif os.name == "posix":
  158.                 response = os.system("ping " + address + " -c 1")
  159.             if response != 0:
  160.                 messagebox.showerror("ERROR","El Host no responde Ping")
  161.                 exit()
  162.             else:
  163.                 conectarse()
  164.         else:
  165.             conectarse()
  166.  
  167.     for x in range(1,cantidad+1):
  168.         mandar_mail()
  169.         time.sleep(repetir)
  170.  
  171. def hilo():
  172.     t1 = threading.Thread(target=recolectar)
  173.     t1.start()
  174.  
  175. ##############FRAMES#################
  176. marco1 = LabelFrame(root,text="datos del equipo",bg="light gray",borderwidth=5,pady=10,labelanchor="n")
  177. marco1.place(x=10,y=10)
  178. marco3 = LabelFrame(root,text="datos a recolectar",bg="light gray",borderwidth=5,pady=25,padx=5,labelanchor="n")
  179. marco3.place(x=210,y=80)
  180.  
  181. b_procesar = Button(root,text="Procesar",command=hilo,borderwidth=1,padx=5,pady=5)
  182. b_procesar.place(x=250,y=10)
  183.  
  184. marco2 = LabelFrame(root,text="Mail",bg="light gray",borderwidth=5,pady=25,padx=5,labelanchor="n")
  185. marco2.place(x=400,y=10)
  186.  
  187.  
  188. img = f"{ruta}\\logicalis-logo.png"
  189. imagen= PhotoImage(file=img)
  190. etiqueta_img = Label(root, image=imagen)
  191. etiqueta_img.place(x=0,y=410)
  192.  
  193. #       marco1
  194. direccion_host_et = Label(marco1,text="ip o hostname")
  195. direccion_host_et.pack()
  196. direccion_host_box = Entry(marco1)
  197. direccion_host_box.pack()
  198. direccion_host_et.config(background="light gray")
  199.  
  200.  
  201.  
  202. usuario_et = Label(marco1,text="usuario")
  203. usuario_et.pack()
  204. usuario_et.config(background="light gray")
  205. usuario_box = Entry(marco1)
  206. usuario_box.pack()
  207.  
  208.  
  209.  
  210. password_et = Label(marco1,text="password")
  211. password_et.pack()
  212. password_et.config(background="light gray")
  213. password_box = Entry(marco1,show="*")
  214. password_box.pack()
  215.  
  216. direcciones_destinatario_et = Label(marco1,text="e-mail destino")
  217. direcciones_destinatario_et.pack()
  218. direcciones_destinatario_et.config(background="light gray")
  219. direccion_host_et.config(background="light gray")
  220. direcciones_destinatario_box = Entry(marco1)
  221. direcciones_destinatario_box.pack()
  222.  
  223. repetir_et = Label(marco1,text="repetir cada... segundos")
  224. repetir_et.pack()
  225. repetir_et.config(background="light gray")
  226. repetir_box = Entry(marco1)
  227. repetir_box.pack()
  228.  
  229. ##################marco3
  230. cant_veces = Label(marco1,text="repetir ... veces")
  231. cant_veces.pack()
  232. cant_veces.config(background="light gray")
  233. cant_veces_box = Entry(marco1)
  234. cant_veces_box.pack()
  235. r = StringVar()
  236. r.set("SSH")
  237. Radiobutton(marco1,background="light gray",text="SSH/puerto22",variable=r,value="SSH").pack(anchor="w")
  238. Radiobutton(marco1,background="light gray",text="TELNET/puerto23",variable=r,value="TELNET").pack(anchor="w")
  239. comandos = []
  240. var1 = IntVar()
  241. var2 = IntVar()
  242. var3 = IntVar()
  243. var4 = IntVar()
  244. var5 = IntVar()
  245. ping = BooleanVar()
  246. p = Checkbutton(marco1,text="comprobacion por ping",variable=ping, onvalue=True, offvalue=False,background="light gray").pack(anchor="w")
  247. ping.set(True)
  248.  
  249. chk_sh_log = Checkbutton(marco3,text="show log",variable=var1, onvalue=1, offvalue=0)
  250. chk_sh_log.pack(anchor="w")
  251. chk_sh_log.config(background="light gray")
  252.  
  253. chk_sh_ver = Checkbutton(marco3,text="show version",variable=var2, onvalue=1, offvalue=0)
  254. chk_sh_ver.pack(anchor="w")
  255. chk_sh_ver.config(background="light gray")
  256.  
  257. chk_sh_inventory = Checkbutton(marco3,text="show inventory",variable=var3, onvalue=1, offvalue=0)
  258. chk_sh_inventory.pack(anchor="w")
  259. chk_sh_inventory.config(background="light gray")
  260.  
  261. chk_sh_run = Checkbutton(marco3,text="show running-config",variable=var4, onvalue=1, offvalue=0)
  262. chk_sh_run.pack(anchor="w")
  263. chk_sh_run.config(background="light gray")
  264.  
  265. texto_comando_manual = Label(marco3,text="introduzca comando:")
  266. texto_comando_manual.pack()
  267. texto_comando_manual.config(background="light gray")
  268. caja_comando_manual = Entry(marco3,state="normal")
  269. caja_comando_manual.pack()
  270.  
  271. ###################     marco2
  272. asunto_et = Label(marco2,text="Asunto:",pady=5)
  273. asunto_et.pack(anchor="w")
  274. asunto_e = Entry(marco2)
  275. asunto_e.pack(anchor="w")
  276. asunto_et.config(background="light gray")
  277.  
  278. cuerpo_e = Label(marco2,text="Cuerpo:",pady=5)
  279. cuerpo_e.pack(anchor="w")
  280. cuerpo_e.config(background="light gray")
  281. cuerpo_c = Text(marco2,width=20,height=15)
  282. cuerpo_c.pack()
  283.  
  284. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement