aliases : [서버파일다운, 파일압축, 이미지바이트배열변환]
tags : 서버파일저장, 압축파일저장, SMBConnection
로컬에 파일을 저장하지 않고 압축파일만 저장해보자
서버에서 파일을 읽어서 D:/temp.zip로 저장한다
<<temp>>
항목은 알맞게 변경하자
from smb.SMBConnection import SMBConnection
import platform
user = <<user>>
pssward = <<pssward>>
sharName = <<sharName>>
ip = <<ip>>
path = <<path>>
extension = 'jpg'
def make_datapath_list(conn, sharName, path, extension):
"""
서버의 폴더 하위의 모든 파일중 extension을 포함하는 해당하는 리스트를 만든다
extension: 이름의 일부분이나 확장자를 주면됨
"""
path_list = []
dir = conn.listPath(sharName, path)
for e in dir:
if e.isDirectory and e.filename not in ['.', '..']:
filepath = path + '/' +e.filename
path_list.extend(make_datapath_list(conn, sharName, filepath, extension))
elif extension in e.filename:
path_list.append(path + '/' +e.filename)
return path_list
#SMB 연결
conn = SMBConnection(user, pssward, platform.uname().node,
sharName, domain='WORKGROUP', use_ntlm_v2=True)
conn.connect(ip, 139)
#파일 목록 구하기
path_list = make_datapath_list(conn, sharName, path, extension)
#압축없이 파일 저장 하기
# for path_item in path_list:
# split_path = path_item.split('/') # 파일명 구하기
# fileName = split_path[-1]
# with open('D:/temp/' + fileName, 'wb') as fp:
# conn.retrieveFile(sharName, path_item, fp)
#압축하여 파일저장
#로컬에 Zip파일만 저장됨
flo = BytesIO()
images = []
# 파일읽어옴
for path_item in path_list:
conn.retrieveFile(sharName, path_item, flo)
flo.seek(0)
split_path = path_item.split('/') # 파일명 구하기
fileName = split_path[-1]
images.append([fileName, flo]) # [파일명, 받은파일]
# print(split_path[-1]) # 이름출력
# 읽은파일 압축하여 저장
zip_file_bytes_io = BytesIO()
with ZipFile(zip_file_bytes_io, 'w') as zip_file:
for image_name, bytes_stream in images:
zip_file.writestr(image_name, bytes_stream.getvalue())
with open('D:/temp.zip', 'wb') as f:
f.write(zip_file_bytes_io.getvalue())
conn.close()