如何使用Python将文件复制到网络路径或驱动器 [英] How to copy files to network path or drive using Python

查看:740
本文介绍了如何使用Python将文件复制到网络路径或驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此类似.

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

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

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命令(假定您在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: \\ComputerName\ShareName %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"\\ComputerName\ShareName", username, password):
     shutil.copyfile("foo.txt", r"P:\foo.txt")

这篇关于如何使用Python将文件复制到网络路径或驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆