2017/08/22

[Python] 파일 보안 설정 변경(File Security)

윈도우에서 파일에대한 보안 설정을하는 코드.

"""File Security Sample"""
import os
import win32api
import win32security
import ntsecuritycon as con

FILENAME = "temp.txt"
os.remove(FILENAME)

#
#Show Cacls
#
def show_cacls(filename):
    for line in os.popen("icacls %s" % filename).read().splitlines():
        print(line)

#
# Find the SIDs for Everyone, the Admin group and the current user
#
everyone, domain, type = win32security.LookupAccountName("", "Everyone")
admins, domain, type = win32security.LookupAccountName("", "Administrators")
user, domain, type = win32security.LookupAccountName("", win32api.GetUserName())

#
# Touch the file and use CACLS to show its default permissions
# (which will probably be: Admins->Full; Owner->Full; Everyone->Read)
#
open(FILENAME, "w").close()
show_cacls(FILENAME)

#
# Find the DACL part of the Security Descriptor for the file
#
sd = win32security.GetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION)

#
# Create a blank DACL and add the three ACEs we want
# We will completely replace the original DACL with
# this. Obviously you might want to alter the original
# instead.
#
dacl = win32security.ACL()
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ, everyone)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, user)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, admins)

#
# Put our new DACL into the Security Descriptor,
# update the file with the updated SD, and use
# CACLS to show what's what.
#
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetFileSecurity(FILENAME, win32security.DACL_SECURITY_INFORMATION, sd)
show_cacls(FILENAME)

출처: http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html

[Python] 특정 경로 탐색

특정 경로의 파일과 폴더를 탐색하는 코드.

import os.path

FOLDER = "C:\\MyFolder"
print('Current Folder : {0}'.format(FOLDER))

for path, dirs, files in os.walk(FOLDER):
    print('\nFoler : {0}'.format(path))

    for dname in dirs:
        print('dir: {0}'.format(dname))

    for fname in files:
        print('file: {0}'.format(os.path.join(path, fname)))

[Python] 메일 보내기

간단하게 메일 전송을 테스트하기위한 코드이다.

import smtplib

from email.mime.text import MIMEText
from email import utils

MSG = MIMEText("내용 없음")

SENDER = "<보내는 메일주소>"
RECEIVER = "<받는 메일주소>"

MSG['Subject'] = "메일 전송 테스트"
MSG['From'] = SENDER
MSG['To'] = RECEIVER

MSG['Date'] = utils.formatdate(localtime=True)

print('Begin of sending...')
SERVER = smtplib.SMTP_SSL("<메일서버 주소>", <메일서버 포트번호>)
#SERVER.ehlo()
#SERVER.starttls()
#SERVER.ehlo()
SERVER.login("<메일서버 계정>", "<메일서버 암호>")
SERVER.sendmail(SENDER, RECEIVER, MSG.as_string())
SERVER.close()

print('End of sending...')