开发者

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

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开发者_如何学Go: /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


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


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


There is a pretty easy and elegant way of doing this. We can use the shutil.copyfile of the smbclient to copy the file.

Install smbprotocol library.

pip install smbprotocol

Use the below code to copy the file.The 1st parameter is the path and filename in the Linux and the 2nd parameter is the target location of Shared network drive along with path and target filename. The last 2 parameters are username and password of the user who have access to the Shared network drive.

import smbclient.shutil
smbclient.shutil.copyfile(
    'source_path and filename', # Eg - /mnt/myfolder/Test.txt
    '\\\\PC name or IP\\folder\\Test.txt', # Eg \\CDTPS\Test.txt
    username='userName', # Username of the the user who have access to the Network drive
    password='password') # Password of the the user who have access to the Network drive

I would recommend the username and password to be created as a shared name instead of individual name, in case you are using this code for any organization. This username need to be added to the Active Directory of the Shared location in order to have the user access to this.


This should work for you. Note that Linux uses a root filesystem, not drive letters. Also note that this will only work if you have a folder called /mnt/P on your linux box. You can't mount to a folder that doesn't exist.

from contextlib import contextmanager
@contextmanager

def network_share_auth(share, username=None, password=None, drive_letter='/mnt/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 = ["smbmount %s %s" % (share, drive_letter)]

    if password:
        cmd_parts.append("-o password=%s,username=%s" % (password, username))
    os.system(" ".join(cmd_parts))
    try:
        yield
    finally:
        os.system("umount %s" % drive_letter)

with network_share_auth(r"//ComputerName/ShareName", username, password):
    shutil.copyfile("foo.txt", r"/mnt/P/foo.txt")


1.Install cifs-utils

sudo apt-get install cifs-utils

2.Make a directory for your share. Some thing like this:

sudo mkdir /media/localShareName

You can use another name instead of localShareName.

3.Code your python function

def mountWindowsShare():

    cmd1 ='sudo mount -t cifs' + '  '
    cmd1+='//Server_IP_Address/ShareFolder' + '  '
    cmd1+='/media/localShareName' + '  '
    cmd1+='-o username=<usernameOfWindowsShare>,'
    cmd1+='password=<passwordOfWindowsShare>,'
    cmd1+='domain=<DomainOfWindowsServer>,'
    cmd1+='noexec'

    os.system(cmd1)

    ''' 
          do whatever you want like:

    print(os.listdir('/media/localShareName'))
    '''

    os.system('sudo umount /media/localShareName')

replace

Server_IP_Address by the IP address of windows workstation or server

< usernameOfWindowsShare > by username of windows share

< passwordOfWindowsShare > by password of windows share

< DomainOfWindowsServer > by domain of windows server. it is almost WORKGROUP

If you want avoiding prompt for password (if it is really necessary), see visudo

sudo visudo

Type the following line to the opened file in the editor

username ALL=(ALL) NOPASSWD: ALL

Replace username by your user name on Ubuntu. Save the file ( Ctrl+x and then press Y ). logout and login

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜