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

Mine is similar to this question.

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

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

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

解决方案

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))

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")

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.

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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值