python在Linux环境下访问Windows共享目录

在Windows环境下访问共享的时候,如果已经添加了访问凭据,直接提供共享路径;

在Linux环境下,可以使用mount挂载或者使用samba连接。

下面提供的python访问Windows共享目录两种方式都是samba连接:

返回结果为文件流。

1.smbprotocol 

不推荐,偶然会出现 "SMB socket was closed, cannot send or receive any more data" 的异常。

pip install smbprotocol 

实现代码:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from smbclient import open_file, register_session, delete_session

#共享目录:\\192.168.0.1\sharedic\business\date\test.txt
#file_path = "\\192.168.0.1\sharedic\business\date\test.txt"

def get_file_from_share(file_path):
    """
    从共享目录中获取文件内容。

    参数:
    filePath: 字符串,指定的文件路径,包括服务器IP和共享目录下的文件路径。

    返回值:
    bytes,文件的内容。
    """
    # 获取共享目录名称:sharedic
    shared_folder = file_path.lstrip('\\').split('\\')[1]
    server_ip = '192.168.0.1'
    username = 'username'
    password = 'password'
    # 使用提供的服务器IP、用户名和密码注册会话
    register_session(server_ip, username=username, password=password)
    remote_file_path = file_path.lstrip('\\').replace(server_ip + "\\" , "").replace("\\", "/")
    try:
        # 尝试打开并读取文件内容
        with open_file(f"/{server_ip}/{remote_file_path}", mode='rb') as file:
            text_content = file.read()
            return text_content
    except Exception as e:
        raise e
    finally:
        # 不论是否发生异常,最后都注销会话
        delete_session(server_ip)

 

2.pysmb

pip install pysmb

实现代码:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import io
import platform
from smb.SMBConnection import SMBConnection

#共享目录:\\192.168.0.1\sharedic\business\date\test.txt
#file_path = "\\192.168.0.1\sharedic\business\date\test.txt"

def get_file_from_share(file_path):
    """
    从通过 SMB 共享的服务器上获取文件。

    参数:
    - filePath: 字符串,指定的文件路径,包括服务器IP和共享文件夹内的路径。

    返回值:
    - stream_data: io.BytesIO 对象,包含从服务器检索到的文件内容。
    """
    # 提取共享文件夹名称
    shared_folder = file_path.lstrip('\\').split('\\')[1]
    # SMB连接的配置:服务器IP、用户名、密码
    server_ip = '192.168.0.1'
    username = 'username'
    password = 'password'
    # 建立SMB连接
    conn = SMBConnection(
        username,
        password,
        platform.uname().node,
        server_ip,
        domain='WORKGROUP',
        use_ntlm_v2=True,
        is_direct_tcp=True)
    try:
        conn.connect(server_ip, 445)  # 连接到服务器的SMB服务
        # 格式化远程文件路径,用于后续的文件检索
        remote_file_path = file_path.lstrip('\\').replace(server_ip + "\\" + shared_folder, "").replace("\\", "/")
        stream_data = io.BytesIO()  # 创建一个内存中的文件对象
        conn.retrieveFile(shared_folder, f"{remote_file_path}", stream_data)  # 从服务器下载文件到stream_data
        stream_data.seek(0)  # 重置stream_data的读取位置到文件开头
        return stream_data
    except Exception as e:
        raise e  # 如果发生异常,向上抛出
    finally:
        conn.close()  # 确保在函数退出前关闭SMB连接

 

posted @ 2024-05-23 08:58  十四年新*  阅读(99)  评论(0编辑  收藏  举报