Python realizes NAS server file upload and download based on smb communication protocol

What is NAS service

NAS (Network Attached Storage) is a device that is connected to the network and has the function of data storage, so it is also called "network storage." It is a dedicated data storage server.
NAS devices generally support multiple computer platforms, and users can access the same files through network support protocols, so NAS devices can be used in mixed Unix/Windows NT LANs without modification.
The NAS itself can support multiple protocols (such as NFS, CIFS, FTP, HTTP, etc.), and can support various operating systems. Through any workstation, IE or Netscape browsers can be used for intuitive and convenient management of NAS devices.

What is the SMB protocol

SMB (Server Message Block), also known as CIFS (Common Internet File System), is an application layer network transmission protocol (a protocol developed by Microsoft and Intel in 1987), developed by Microsoft, and its main function is to make the network The machines on the computer can share resources such as computer files, printers, serial ports, and communications. It also provides certified inter-process communication skills. It is mainly used on Windows machines. SMB uses the Application Program Interface (API) of NetBIOS, and the general port usage is 139 and 445.

pysmb module installation method

pip install pysmb

ps: To speed up the download and installation process, you can use the pip mirror source to download common mirror sources, see the description of adding links

Python implements file upload and download reference code

#!usr/bin/python
# _*_ coding:utf-8 _*_
"""python
Created on 2020/08/14
@author: 
@theme:实现磁盘阵列读取与存储
"""
import datetime
import os
from smb.SMBConnection import SMBConnection
from smb.smb_structs import OperationFailure

def connect(user_name, passwd, ip, port):
    '''
    建立smb服务连接
    :param user_name:
    :param passwd:
    :param ip:
    :param port: 445或者139
    :return:
    '''
    samba = None
    status = False
    try:
        samba = SMBConnection(user_name, passwd, '', '', use_ntlm_v2=True)
        samba.connect(ip, port)
        status = samba.auth_result

    except:
        samba.close()
    return samba, status
def all_shares_name(samba):
    '''
    列出smb服务器下的所有共享目录
    :param samba:
    :return:
    '''
    share_names = list()
    sharelist = samba.listShares()
    for s in sharelist:
        share_names.append(s.name)
    return share_names
def all_file_names_in_dir(samba, service_name, dir_name):
    '''
    列出文件夹内所有文件名
    :param service_name: 服务名(smb中的文件夹名,一级目录)
    :param dir_name: 二级目录及以下的文件目录
    :return:
    '''
    f_names = list()
    for e in samba.listPath(service_name, dir_name):
        if e.filename[0] != '.':   # (会返回一些.的文件,需要过滤)
            f_names.append(e.filename)
    return f_names
def get_last_updatetime(samba, service_name, file_path):
    '''
    返回samba server上的文件更新时间(时间戳),如果出现OperationFailure说明无此文件,返回0
    :param samba:
    :param service_name:
    :param file_path:
    :return:
    '''
    try:
        sharedfile_obj = samba.getAttributes(service_name, file_path)
        return sharedfile_obj.last_write_time
    except OperationFailure:
        return 0
def download(samba, f_names, service_name, smb_dir, local_dir):
    '''
    下载文件
    :param samba:
    :param f_names:文件名
    :param service_name:服务名(smb中的文件夹名)
    :param smb_dir: smb文件夹
    :param local_dir: 本地文件夹
    :return:
    '''
    assert isinstance(f_names, list)
    for f_name in f_names:
        f = open(os.path.join(local_dir, f_name), 'wb')
        samba.retrieveFile(service_name, os.path.join(smb_dir, f_name), f)
        f.close()
def createDir(samba, service_name, path):
    """
    创建文件夹
    :param samba:
    :param service_name:
    :param path:
    :return:
    """
    try:
        samba.createDirectory(service_name, path)
    except OperationFailure:
        pass
def upload(samba, service_name, smb_dir, local_dir, f_names):
    '''
    上传文件
    :param samba:
    :param service_name:服务名(smb中的文件夹名)
    :param smb_dir: smb文件夹
    :param local_dir: 本地文件列表所在目录
    :param f_names: 本地文件列表
    :return:
    '''
    assert isinstance(f_names, list)
    for f_name in f_names:
        f = open(os.path.join(local_dir, f_name), 'rb')
        samba.storeFile(service_name, os.path.join(smb_dir, f_name), f)  # 第二个参数path包含文件全路径
        f.close()
if __name__ == '__main__':
    samba, status = connect('ll', 'llllllll', '192.168.77.177', 445)
    if status:
        print('smb服务器连接成功!')
    else:
        print('smb服务器连接失败!')
    share_names = all_shares_name(samba)
    print("share_names:", share_names)
    share_name = "rd117"
    dst_name = 'Hdata'
    f_names = all_file_names_in_dir(samba, share_name, dst_name)
    print("share_name: {} -dir_name: {} include f_names:".format(share_name, dst_name), f_names)

    file_path = '/程序/auto_start.bat'
    timestamp = get_last_updatetime(samba, share_name, file_path)
    print(datetime.datetime.fromtimestamp(timestamp))


    # smb_dir = '/数据/历史气象数据'
    # f_names =['README.txt','MERRA-2全球再分析数据集.doc','Delivery_05-29-2009_05-28-2019_hourly.zip']
    # local_dir = ''
    # download(samba, f_names, share_name, smb_dir, local_dir)

    # path = "/数据/test"
    # createDir(samba, share_name, path)

    # smb_dir = '/数据/test'  # 该目录需提前创建好
    # local_dir = 'pic'
    # f_names = ['ana1.txt','ana2.txt']
    # upload(samba, share_name, smb_dir, local_dir, f_names)

    samba.close()

Reference:
NAS basic knowledge
Samba service-SMB protocol

Guess you like

Origin blog.csdn.net/qq_43314560/article/details/113882498