如何使用 Python 将文件复制到网络路径或驱动器

2022-01-19 00:00:00 python drive network-programming share

问题描述

我的问题与此类似.

如何使用变量将文件从网络共享复制到本地磁盘?

唯一的区别是我的网络驱动器使用用户名和密码进行密码保护.

The only difference is my network drive has a password protect with username and password.

我需要使用 Python 将文件复制到 Samba 共享并进行验证.

I need to copy files to a Samba share using Python and verify it.

如果我手动登录,则代码可以正常工作,但如果不登录 shutil 命令将无法正常工作.

If I manually login in then the code works, but without logging in the shutil command does not work.


解决方案

我会尝试通过使用 os.system<调用 NET USE 命令将共享映射到未使用的驱动器号/code>(假设你在 Windows 上):

I'd try mapping the share to an unused drive letter by calling the NET USE command using os.system (assuming you are on Windows):

os.system(r"NET USE P: \ComputerNameShareName %s /USER:%s\%s" % (password, domain_name, user_name))

将共享映射到驱动器号后,您可以使用 shutil.copyfile 将文件复制到给定驱动器.最后,您应该卸载共享:

After you mapped the share to a drive letter, you can use shutil.copyfile to copy the file to the given drive. Finally, you should unmount the share:

os.system(r"NET USE P: /DELETE")

当然,这仅适用于 Windows,您必须确保驱动器号 P 可用.可以查看NET USE命令的返回码看是否挂载成功;如果没有,您可以尝试不同的驱动器号,直到成功为止.

Of course this works only on Windows, and you will have to make sure that the drive letter P is available. You can check the return code of the NET USE command to see whether the mount succeeded; if not, you can try a different drive letter until you succeed.

由于两个 NET USE 命令是成对出现的,并且第二个应该总是在第一个执行时执行(即使在两者之间的某个地方引发了异常),您可以将这两个包装起来如果您使用的是 Python 2.5 或更高版本,则在上下文管理器中调用:

Since the two NET USE commands come in pair and the second one should always be executed when the first one was executed (even if an exception was raised somewhere in between), you might wrap these two calls in a context manager if you are using Python 2.5 or later:

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"\ComputerNameShareName", username, password):
     shutil.copyfile("foo.txt", r"P:foo.txt")

相关文章