Python Linux-复制文件到windows共享驱动器(samba)

发布于 2024-12-02 16:06:10 字数 1069 浏览 2 评论 0原文

这个问题类似于 如何将文件复制到网络路径或驱动器使用Python 但是,我在 Linux 上尝试将文件复制到通过 samba 访问的 Windows 共享网络。 我尝试了代码:

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

我收到错误:sh:NET:未找到

我认为这是因为“NET USE”是特定于Windows的。我如何在 Linux 中做类似的事情?

谢谢! 哈迈尼

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

错々过的事 2024-12-09 16:06:10

在 Linux 上,您可以使用 smbmount 来执行与此处使用 NET 相同的操作。

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

墨落画卷 2024-12-09 16:06:10

有一种非常简单且优雅的方法可以做到这一点。我们可以使用smbclientshutil.copyfile来复制文件。

安装 smbprotocol 库。

pip install smbprotocol

使用下面的代码复制文件。第一个参数是Linux中的路径和文件名,第二个参数是共享网络驱动器的目标位置以及路径和目标文件名。最后 2 个参数是有权访问共享网络驱动器的用户的用户名和密码。

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

如果您在任何组织中使用此代码,我建议将用户名和密码创建为共享名称而不是个人名称。需要将此用户名添加到共享位置的 Active Directory 中,以便用户可以访问该用户名。

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.

作死小能手 2024-12-09 16:06:10

感谢您的回复。我必须使用 mount -t smbfs 而不是 smbmount 才能使其正常工作。这有效:

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

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))
倾城花音 2024-12-09 16:06:10

这应该对你有用。请注意,Linux 使用根文件系统,而不是驱动器号。 请注意,只有当您的 Linux 机器上有一个名为 /mnt/P 的文件夹时,这才有效。您无法安装到不存在的文件夹。

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

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")
我是有多爱你 2024-12-09 16:06:10

1.安装 cifs-utils

sudo apt-get install cifs-utils

2.为您的共享创建一个目录。像这样的事情:

sudo mkdir /media/localShareName

您可以使用其他名称来代替 localShareName。

3.编写Python函数

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

,将Server_IP_Address替换

为Windows工作站或服务器的IP地址

<用户名OfWindowsShare >通过 Windows 共享的用户名

< Windows共享密码>通过Windows共享的密码

< Windows服务器域>按 Windows 服务器的域。它几乎是 WORKGROUP

如果您想避免提示输入密码(如果确实有必要),请参阅 visudo

sudo visudo

键入以下行在编辑器中打开的文件

username ALL=(ALL) NOPASSWD: ALL

将 username 替换为您在 Ubuntu 上的用户名。保存文件(Ctrl+x,然后按 Y)。注销并登录

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文