Python在Linux上复制文件到Windows共享驱动器(Samba)

4 投票
5 回答
17590 浏览
提问于 2025-04-17 01:07

这个问题和如何使用Python复制文件到网络路径或驱动器的内容很相似。不过,我是在Linux系统上,想把文件复制到通过samba访问的Windows共享网络上。

我试了以下代码:

from contextlib import contextmanager
@contextmanager

def network_share_auth(share, username=None, password=None, drive_letter='P'):

    """Context manager that mounts the given share using the given
    username and password to the given drive letter when entering
    the context and unmounts it when exiting."""

    cmd_parts = ["NET USE %s: %s" % (drive_letter, share)]

    if password:
        cmd_parts.append(password)
    if username:
        cmd_parts.append("/USER:%s" % username)
    os.system(" ".join(cmd_parts))
    try:
        yield
    finally:
        os.system("NET USE %s: /DELETE" % drive_letter)

with network_share_auth(r"\\ComputerName\ShareName", username, password):
    shutil.copyfile("foo.txt", r"P:\foo.txt")

但是我遇到了一个错误:sh: NET: not found

我觉得这是因为'NET USE'这个命令是Windows特有的。那么在Linux上我该怎么做类似的操作呢?

谢谢!

Harmaini

5 个回答

2

谢谢大家的回复。我需要使用 mount -t smbfs 而不是 smbmount 才能让它正常工作。这个方法有效:

        cmd_parts = ["mount -t smbfs"]
        if password:
            cmd_parts.append("-o password=%s,user=%s %s %s" % (password, username, share, drive_letter))
        os.system(" ".join(cmd_parts))
3

其实有一个很简单又优雅的方法来做到这一点。我们可以用 shutil.copyfile 结合 smbclient 来复制文件。

首先,你需要安装 smbprotocol 这个库。

pip install smbprotocol

接下来,使用下面的代码来复制文件。第一个参数是Linux系统中的文件路径和文件名,第二个参数是共享网络驱动器的目标位置,包括路径和目标文件名。最后两个参数是有权限访问这个共享网络驱动器的用户的用户名和密码。

import smbclient.shutil
smbclient.shutil.copyfile(
    'source_path and filename', # Eg - /mnt/myfolder/Test.txt
    '\\\\PC name or IP\\folder\\Test.txt', # Eg \\CDTPS\Test.txt
    username='userName', # Username of the the user who have access to the Network drive
    password='password') # Password of the the user who have access to the Network drive

如果你是在为某个组织使用这段代码,我建议把用户名和密码设置为一个共享的名字,而不是每个人的个人名字。这个用户名需要被添加到共享位置的活动目录中,这样才能让用户访问到这个共享。

4

在Linux系统中,你可以使用 smbmount 来完成和这里提到的NET相同的操作。

撰写回答