Python Linux-copy files to windows shared drive (samba)

Harmaini picture Harmaini · Sep 1, 2011 · Viewed 12.4k times · Source

this question is similar to How to copy files to network path or drive using Python However, I am on Linux and trying to copy files to a windows shared network accessed through samba. I tried the code:

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

I get the error: sh: NET: not found

I think this is because the 'NET USE' is windows specific. How do I do something similar in Linux?

Thanks! Harmaini

Answer

Devin Jeanpierre picture Devin Jeanpierre · Sep 1, 2011

On linux you would use smbmount to do the same thing as NET is being used for here.