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

13,649

Solution 1

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

Solution 2

Thanks for your responses. I had to use mount -t smbfs instead of smbmount to get it working. This worked:

        cmd_parts = ["mount -t smbfs"]
        if password:
            cmd_parts.append("-o password=%s,user=%s %s %s" % (password, username, share, drive_letter))
        os.system(" ".join(cmd_parts))
Share:
13,649
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    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