/*auto readmore*/ /*auto readmore*/ /* an hien script*/ // an hien password /*an hien ma chuong trinh cong tru */ /*Scrollbox thanh cuon*/ /***Nhung CODE***/ /* dòng xanh dòng trắng */ /* https://cdnjs.com/libraries/prism lay thu vien, can vao ten file ma goi 1. copy link vao vi du:prism-python.min.js 2. ten ngon nua la python */ /*=== New posts ===*/ /*header slider*/ /*=== bai viet lien quan===*/ /*===tabcode===*/

Network Automation #013 - Create/Unzip/Extract A ZIP Archive File In Python - Tạo/Bung/Giải File ZIP Trong Python

 YÊU CẦU

1. Viết hàm nén/tạo file ZIP:

a. Một loại định dạng file ở thư mục hiện tại.
b. Tất cả các file, đường dẫn tự truyền vào
c. Một loại định dạng file nhất định, đường dẫn và loại file được truyền vào
d. Thêm file vào file ZIP đã tồn tại

         

2. Viết hàm giải nén/extract file ZIP


THỰC HIỆN:

1. Viết hàm nén/tạo file ZIP:

a. Một loại định dạng file ở thư mục hiện tại.
'''
Tạo file nén ở thư mục hiện tại, file tự truyền vào.
Ví dụ chỉ nén các file *.py:
to_zip("abc",".py")
hoặc to_zip("abc1","csv")
'''
import os
from zipfile import ZipFile
from datetime import datetime
import zipfile

def to_zip(zip_file, type_file): # Hàm tạo file zip
	path = os.getcwd()  # lấy đường dẫn hiện tại	
	zip_file = zip_file + ".zip"
	if not os.path.isfile(zip_file):
   		zf = ZipFile(zip_file, "w")
	else: # Nếu file đã tồn tại thì không ghi header
   		zf = ZipFile(zip_file, "a")
	for file in os.listdir(os.curdir): # tương đương lệnh dir trong cmd của windows, liệt kê file, folder trong thư mục hiện tại
	    if file.endswith(type_file) and os.path.isfile(os.curdir + '/' + file): # đảm bảo đúng là file, và file có định dạng được đưa vào từ type_file
	       	#print(file) # Liệt kê các file cần nén
	       	zf.write(file)

	zf.close()
	print (f"***Please check files '{zip_file}' at '{path}' ***\n")		

# Gọi hàm zip
to_zip("abc",".py")
to_zip("abc1","csv")

 

b. Tất cả các file, đường dẫn tự truyền vào
'''
Nén tất cả các file ở thư mục
ví dụ nén tất cả các file tại đường dẫn "C:\Intel" thành file có tên abc123.zip:
to_zip_dir("abc123.zip", r"C:\Intel")
'''
from zipfile import ZipFile
import os
from os.path import basename
from pprint import pprint # dùng để in ra đẹp, dễ nhìn hơn

def to_zip_dir(zip_file, dir_name): # Hàm nén tất cả các file trong thư mục
    path = os.getcwd()  # lấy đường dẫn hiện tại    path = os.getcwd()  # lấy đường dẫn hiện tại    
    with ZipFile(zip_file, 'w') as zipObj:
       for folder_Name, sub_folders, file_names in os.walk(dir_name): # lấy thông tin của file, folder tại đường dẫn dir_name
           #pprint(list(os.walk(dir_name)) )
           for file_name in file_names:
               filePath = os.path.join(folder_Name, file_name) # đường dẫn đầy đủ đến file cần backup
               zipObj.write(filePath, basename(filePath)) # thực hiện nén file
    print (f"***Please check files '{zip_file}' at '{path}' ***\n")            

#gọi hàm nén file
to_zip_dir("abc123.zip", r"C:\Intel")

 

c. Một loại định dạng file nhất định, đường dẫn và loại file được truyền vào 
'''
Ví dụ:
Thực hiện nén các file *.py tại đường dẫn "C:\Intel" thành file có tên abcde.zip:
to_zip_filter("abcde.zip",r"C:\Intel","py")

Thực hiện nén các file *.* tại đường dẫn "C:\Intel" thành file có tên abcdef.zip:
to_zip_filter("abcdef.zip",r"C:\Intel","")
'''
from zipfile import ZipFile
import os
from os.path import basename
from pprint import pprint # dùng để in ra đẹp, dễ nhìn hơn

def to_zip_filter(zip_file, dir_name, type_file): # Hàm nén (filter) file trong thư mục
    path = os.getcwd()  # lấy đường dẫn hiện tại    path = os.getcwd()  # lấy đường dẫn hiện tại    
    with ZipFile(zip_file, 'w') as zipObj:
       for folder_Name, sub_folders, file_names in os.walk(dir_name): # lấy thông tin của file, folder tại đường dẫn dir_name
           #pprint(list(os.walk(dir_name)) )
           for file_name in file_names:
               if file_name.endswith(type_file): # tên file tận cùng là ...
                 filePath = os.path.join(folder_Name, file_name) # đường dẫn đầy đủ đến file cần backup
                 zipObj.write(filePath, basename(filePath)) # thực hiện nén file
    print (f"***Please check files '{zip_file}' at '{path}' ***\n")            
         
to_zip_filter("abcde.zip",r"C:\Intel","py") # tất cả các file *.py
to_zip_filter("abcdef.zip",r"C:\Intel","") # tất cả các file


d. Thêm file vào file ZIP đã tồn tại


def add_tozip (path, file_name):
	with zipfile.ZipFile(rf"{path}\File_ZIP_DangTonTai.zip", 'a') as zipf: # Mở file zip tại đường dẫn, nếu file chưa có tạo mới file
    # Thêm file source_path vào destination
    # Nếu file đã có sẽ ghi đè
    

	    source_path = rf"{path}\{file_name}" 
	    destination = rf"{file_name}"
	    zipf.write(source_path, destination) # thực hiện việc ghi file, nếu có ghi đè (nhưng chương trình sẽ thông báo)

2. Viết hàm giải nén/extract file ZIP

'''
Giải nén file zip
Ví dụ:
- zip_extract(r"C:\Intel\now.zip", "abc.csv", r"C:\Intel") # tìm file abc.csv trong file "C:\Intel\now.zip" và extract đến đường dẫn "C:\Intel"
- zip_extract(r"C:\Intel\now.zip", "", r"C:\Intel") # Giải nén tất cả các file trong file "C:\Intel\now.zip" và extract đến đường dẫn "C:\Intel"

'''
import os
from zipfile import ZipFile
from datetime import datetime
import zipfile

def zip_extract(zip_file, type_file, to_dir): #Hàm giải nén file zip
	#zip_file = zip_file + ".zip"
	with ZipFile(zip_file, 'r') as zip:
		if type_file == "all" or type_file == "*" or type_file == "":
		    print('Extracting all the files ...')
		    zip.printdir()# in thông tin các file có trong file zip
		    zip.extractall(to_dir) # extract tất cả các file
		else: 
			zip.extract(type_file, to_dir) # extract 1 file với tên file mới truyền vào
	
	print (f"***Please check files '{type_file}' at '{to_dir}' ***\n")		

# cách gọi hàm    	
zip_extract(r"C:\Intel\now.zip", "abc.csv", r"C:\Intel") # tìm file abc.csv trong file "C:\Intel\now.zip" và extract đến đường dẫn "C:\Intel"
zip_extract(r"C:\Intel\now.zip", "", r"C:\Intel") # Giải nén tất cả các file trong file "C:\Intel\now.zip" và extract đến đường dẫn "C:\Intel"


Xong!

Network Automation #012 - SMTP Sending Emails With Attachment in Python - Gửi Mail Đính Kèm File Bằng Python

YÊU CẦU:

1. Sử dụng thư viện email smtplib của python để kết nối đến gmail để gửi mail đính kèm attach file

2. Gửi mail hàng loạt, đính kèm attach file với thông tin được lưu trữ trong file email_list.csv

3. Sử dụng profile hiện của MS Outlook để gửi mail.


THỰC HIỆN

1. Sử dụng thư viện email smtplib của python để kết nối đến gmail để gửi mail đính kèm attach file

Code:

'''
Kết nối đến Gmail để gửi mail và đính kèm attach file

Điều kiện:
1. Tắt bảo mật 2 lớp
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

2. Allow less secure apps: ON
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

nếu không chúng ta sẽ gặp lỗi
#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials qe12sm2115875pjb.29 - gsmtp')

Link tham khảo
https://realpython.com/python-send-email/
'''
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail_att(mail_from, mail_password, mail_to, mail_subject, mail_body, att_file): # Hàm gửi mail
	port = 465  # For SSL
	smtp_server = "smtp.gmail.com"
	# Create a multipart message and set headers
	message = MIMEMultipart()
	message["From"] = mail_from
	message["To"] = mail_to
	message["Subject"] = mail_subject
	#message["Bcc"] = "khanhvc2003@yahoo.com"

	# Add body to email
	message.attach(MIMEText(mail_body, "plain"))

	# Open file in binary mode
	with open(att_file, "rb") as attachment:
	    # Add file as application/octet-stream
	    # Email client can usually download this automatically as attachment
	    part = MIMEBase("application", "octet-stream")
	    part.set_payload(attachment.read())

	# Encode file in ASCII characters to send by email    
	encoders.encode_base64(part)

	# Add header as key/value pair to attachment part
	part.add_header("Content-Disposition", f"attachment; filename = {att_file}")

	# Add attachment to message and convert message to string
	message.attach(part)
	text = message.as_string()

	# Log in to server using secure context and send email
	context = ssl.create_default_context()
	try:
		with smtplib.SMTP_SSL(smtp_server, port, context = context) as server:
		    server.login(mail_from, mail_password)
		    server.sendmail(mail_from, mail_to, text)
		    print (f"Successfuly sent to '{mail_to}'")
	except:
		print (f"Communication failure in '{smtp_server}'")

email_info = {
	"mail_from": "khanhvc.wrk@gmail.com",
	"mail_password": "matkhaucuaban" ,
	"mail_to": "khanhvc@hansollvina.com",
	"mail_subject" : "This is for testing 8.19 r duong dan BO PHAY" ,
	"mail_body": "This is for testing email",
	"att_file": r"C:\python\Blog\TextFSM Custom.JPG"
	#pass_mail = input("Type your password and press enter:")
}
send_mail_att(**email_info)


2. Gửi mail hàng loạt, đính kèm attach file với thông tin được lưu trữ trong file email_list.csv

Tạo file email_list.csv có dạng:



Code:
'''
Kết nối đến Gmail để gửi mail và đính kèm attach file, danh sách các địa chỉ email được lưu trong file

Điều kiện:
1. Tắt bảo mật 2 lớp
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

2. Allow less secure apps: ON
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

nếu không chúng ta sẽ gặp lỗi
#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials qe12sm2115875pjb.29 - gsmtp')

Link tham khảo
https://realpython.com/python-send-email/
'''
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import pandas as pd
from datetime import datetime
import os

path = os.getcwd()  # lấy đường dẫn hiện tại
now = datetime.now().strftime("%Y-%b-%d_%H%M%S")

ERR_log = f"Send_Mail_{now}_ERR_logs.log" # định nghĩa tên file lưu trữ thông tin lỗi

def send_mail_att(mail_from, mail_password, mail_to, mail_subject, mail_body, att_file): # Hàm gửi mail
	port = 465  # For SSL
	smtp_server = "smtp.gmail.com"
	# Create a multipart message and set headers
	message = MIMEMultipart()
	message["From"] = mail_from
	message["To"] = mail_to
	message["Subject"] = mail_subject
	#message["Bcc"] = "khanhvc2003@yahoo.com"

	# Add body to email
	message.attach(MIMEText(mail_body, "plain"))

	# Open file in binary mode
	with open(att_file, "rb") as attachment:
	    # Add file as application/octet-stream
	    # Email client can usually download this automatically as attachment
	    part = MIMEBase("application", "octet-stream")
	    part.set_payload(attachment.read())

	# Encode file in ASCII characters to send by email    
	encoders.encode_base64(part)

	# Add header as key/value pair to attachment part
	part.add_header("Content-Disposition", f"attachment; filename = {att_file}")

	# Add attachment to message and convert message to string
	message.attach(part)
	text = message.as_string()

	# Log in to server using secure context and send email
	context = ssl.create_default_context()
	try:
		with smtplib.SMTP_SSL(smtp_server, port, context = context) as server:
		    server.login(mail_from, mail_password)
		    server.sendmail(mail_from, mail_to, text)
		    print (f"Successfuly sent to '{mail_to}'")
	except:
		f = open(ERR_log,"a")
		f.write(f'Undelivered email to: {mail_to}')
		f.write("\n")
		f.close()
		print (f"Communication failure in '{smtp_server}'")
		pass

att_file = r"C:\python\Blog\TextFSM Custom.JPG" # tên file cần đính kèm

email_list = 'email_list.csv' # tên file lưu trữ thông tin thiết bị
column_name = ['mail_from', 'mail_subject', 'mail_to', 'mail_body', 'mail_password'] # chỉ định các cột cần lấy
try:
	email_list = pd.read_csv(email_list, usecols = column_name, encoding = "utf-8") # đọc và xử lý chuyển dữ liệu về dạng DataFrame, và sử dụng code utf-8
	email_list = email_list.to_dict(orient='records') # chuyển đổi về dict tương ứng (ví dụ: nếu file có 10 dòng thì sẽ tạo ra 9 (10 dòng bỏ đi dòng đầu tiên đã làm key) dictionary tương ứng)
	#pprint(email_list)

	for email_info in email_list:
		email_info["att_file"] = att_file # thêm thông tin att_file vào dict
		send_mail_att(**email_info)
	ERR_info = f"*** ERROR: Please check file : '{ERR_log}' at '{path}' ***\n"
	print (ERR_info)
except:
	ERR_info = f"*** ERROR: Please check file : '{email_list}' at '{path}' ***\n"
	print (ERR_info)
	pass


3. Sử dụng profile hiện của MS Outlook để gửi mail.
import win32com.client
def outlook_send_mail(mail_to, mail_subject, mail_body, att_file):
	"""
 	gọi outlook hiện tại để send mail
	"""
	outlook = win32com.client.Dispatch('outlook.application')
	mail = outlook.CreateItem(0)
	mail.To = rf"{mail_to}"
	mail.Subject = rf"{mail_subject}"
	mail.HTMLBody = '

This is HTML Body

' mail.Body = rf"{mail_body}" mail.Attachments.Add(rf"{att_file}") # mail.Attachments.Add('them file nua.abc') # mail.CC = 'somebody@company.com' mail.Send()


Tham khảo bài gửi mail KHÔNG attach file tại đây.


Xong!

Network Automation #011 - SMTP Sending Emails With Python - Gửi Mail Bằng Python

 YÊU CẦU:

1. Sử dụng thư viện smtplib của python để kết nối đến gmail và gửi mail

2. Gửi mail hàng loạt với thông tin được lưu trữ trong file email_list.csv


THỰC HIỆN

1. Sử dụng thư viện smtplib của python để kết nối đến gmail và gửi mail

Code:
'''
Kết nối đến Gmail để gửi mail

Điều kiện:
1. Tắt bảo mật 2 lớp
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

2. Allow less secure apps: ON
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

nếu không chúng ta sẽ gặp lỗi
#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials qe12sm2115875pjb.29 - gsmtp')

nếu trong nội dung email có gõ tiếng việt sẽ bị lỗi, các địa chỉ không gửi đến được sẽ được lưu vào file
'''
import smtplib, ssl

def send_mail(mail_from, mail_password, mail_to, mail_subject, mail_body): # Hàm gửi mail
	port = 465  # For SSL
	smtp_server = "smtp.gmail.com"
	#mail_password = input("Type your password and press enter: ")
	mail_message = f"Subject: {mail_subject}\n\n{mail_body}"
	context = ssl.create_default_context()
	try:
		with smtplib.SMTP_SSL(smtp_server, port, context = context) as server:
		    server.login(mail_from, mail_password)
		    server.sendmail(mail_from, mail_to, mail_message)
		    print (f"Successfuly sent to '{mail_to}'")
	except:
		print (f"Communication failure in '{smtp_server}'")
            
# Định nghĩa các thông tin 
email_info = {
	"mail_from": "khanhvc.wrk@gmail.com",
	"mail_password": "admin" ,
	"mail_to": "khanhvc@tencongty.com",
	"mail_subject" : "This is send python 3.10" ,
	"mail_body": "This is for testing email",
	#mail_password = input("Type your password and press enter:")
}

send_mail(**email_info)

2. Gửi mail hàng loạt với thông tin được lưu trữ trong file email_list.csv

Tạo file email_list.csv có dạng:


Code:
'''
Kết nối đến Gmail để gửi mail, danh sách các email được lưu trữ trong file email_list.csv

Điều kiện:
1. Tắt bảo mật 2 lớp
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

2. Allow less secure apps: ON
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

nếu không chúng ta sẽ gặp lỗi
#smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials qe12sm2115875pjb.29 - gsmtp')
'''
import smtplib, ssl
import pandas as pd
from pprint import pprint
from datetime import datetime
import os

path = os.getcwd()  # lấy đường dẫn hiện tại
now = datetime.now().strftime("%Y-%b-%d_%H%M%S")

ERR_log = f"Send_Mail_{now}_ERR_logs.log" # định nghĩa tên file lưu trữ thông tin lỗi

def send_mail(mail_from, mail_password, mail_to, mail_subject, mail_body):
	port = 465  # For SSL
	smtp_server = "smtp.gmail.com"
	#mail_password = input("Type your password and press enter: ")
	mail_message = f"Subject: {mail_subject}\n\n{mail_body}"
	context = ssl.create_default_context()
	try:
		with smtplib.SMTP_SSL(smtp_server, port, context = context) as server:
		    server.login(mail_from, mail_password)
		    server.sendmail(mail_from, mail_to, mail_message)
		    print (f"Successfuly sent to '{mail_to}'")
	except:
		f = open(ERR_log,"a")
		f.write(f'Undelivered email to: {mail_to}')
		f.write("\n")
		f.close()
		print (f"Communication failure in '{smtp_server}'")
		pass
            
email_list = 'email_list.csv' # tên file lưu trữ thông tin thiết bị
column_name = ['mail_from', 'mail_subject', 'mail_to', 'mail_body', 'mail_password'] # chỉ định các cột cần lấy
try:
	email_list = pd.read_csv(email_list, usecols = column_name, encoding = "utf-8") # đọc và xử lý chuyển dữ liệu về dạng DataFrame, và sử dụng code utf-8
	email_list = email_list.to_dict(orient='records') # chuyển đổi về dict tương ứng (ví dụ: nếu file có 10 dòng thì sẽ tạo ra 9 (10 dòng bỏ đi dòng đầu tiên đã làm key) dictionary tương ứng)
	#pprint(email_list)

	for email_info in email_list:
		send_mail(**email_info)
	ERR_info = f"*** ERROR: Please check file : '{ERR_log}' at '{path}' ***\n"
	print (ERR_info)
except:
	ERR_info = f"*** ERROR: Please check file : '{email_list}' at '{path}' ***\n"
	print (ERR_info)
	pass

Kết quả:


Tham khảo bài gửi mail có đính kèm attach file tại đây


Xong!


/*header slide*/