How to copy files to network path or drive using Python
Asked Answered
H

3

8

Mine is similar to this question.

How to copy a file from a network share to local disk with variables?

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.

Hick answered 12/4, 2010 at 22:24 Comment(0)
C
12

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")
Calabrese answered 12/4, 2010 at 23:23 Comment(5)
Hi what is the domain name argument ?Hick
The doomain name argument can be used when the user being authenticated is under a different auth domain. I didn't include it in the contextlib version because it can simply be made part of the username. If the user being authenticated is in the same domain as the current user, the domain can be omitted.Virtuoso
Thanks ... it worked... only sometimes if i run it a second time i get an error saying that the local device is in use.Hick
Thanks for this... using Subprocess caused a lot of problems but your os.system method worked just fine!Eriha
5 years later... this helped me. CheersCalais
M
4

If you have the pywin32 library (eg comes part of the ActiveState Python distro), then you can get it done in a few lines, without mapping a drive:

import win32wnet
win32wnet.WNetAddConnection2(0, None, '\\\\'+host, None, username, password)
shutil.copy(source_file, '\\\\'+host+dest_share_path+'\\')
win32wnet.WNetCancelConnection2('\\\\'+host, 0, 0) # optional disconnect

There is a more complete example on ActiveState Code

Montana answered 7/9, 2014 at 12:21 Comment(0)
O
0

I found this, and many other solutions, just would not work for me. I am running python on a non-windows computer. I also tried a number of AI suggested solutions, which also did not work. In the end, I installed and used smbprotocol. smbclient is part of it. This worked for me:

import smbclient
smbclient.ClientConfig(username='username', password='password')

source_file_path = "path/to/local/sourcefile"
destination_file_path = r"//your_server/your_share/your_file"

with smbclient.open_file(destination_file_path, mode="w") as fd:
    fd.write(open(source_file_path, "r").read())

smbclient.reset_connection_cache() # Reset the SMB client connection cache
Oyster answered 3/7, 2024 at 12:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.