在 python 脚本中访问共享的 smb ubuntu [英] Accessing shared smb ubuntu in python scripts

查看:39
本文介绍了在 python 脚本中访问共享的 smb ubuntu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网络上有一个共享的 ubuntu 驱动器,我可以在 nautilus 中使用 smb://servername/sharedfolder 或 smb:///sharedfolder 访问它.

I have a shared ubuntu drive on my network that I can access in nautilus using smb://servername/sharedfolder or smb:///sharedfolder.

我需要能够从我的 ubuntu 机器 (8.10) 访问它的 python 脚本,但我不知道如何.我尝试了显而易见的方法(与 nautilus 相同的地址),但没有成功.

I need to be able to access it python scripting from my ubuntu machine (8.10), but I can't figure out how. I tried the obvious way (same address as nautilus), but wasn't successful.

为了玩耍,我尝试使用两者打印该文件夹的内容:

To play around, I tried printing the content of that folder with both:

代码:对于 os.listdir("smb://servername/sharedfolder") 中的文件打印文件两者都在该路径上给我没有文件或目录"错误.

Code: for file in os.listdir("smb://servername/sharedfolder") print file Both give me "no file or directory" error on that path.

我真的很感激这方面的帮助 - 谢谢.

I'd really appreciate help on this - thanks.

推荐答案

Python 只能处理本地路径.Samba 是由 Linux 系统中的驱动程序或应用程序读取的远程路径,除非您使用像 这个实验库.

Python can only handle local paths. Samba is a remote path read by a driver or application in your Linux system and can there for not be directly accessed from Python unless you're using a custom library like this experimental library.

您可以执行类似于(确保您的用户具有挂载内容所需的权限)的操作:

You could do something similar to (make sure your user has the permission needed to mount stuff):

import os
from subprocess import Popen, PIPE, STDOUT

# Note: Try with shell=True should not be used, but it increases readability to new users from my years of teaching people Python.
process = Popen('mkdir ~/mnt && mount -t cifs //myserver_ip_address/myshare ~/mnt -o username=samb_user,noexec', shell=True, stdout=PIPE, stderr=PIPE)
while process.poll() is None:
    print(process.stdout.readline()) # For debugging purposes, in case it asks for password or anything.

print(os.listdir('~/mnt'))

同样,使用 shell=True 是危险的,它应该是 False 并且您应该将命令字符串作为列表传递.但是出于某种原因,如果您按照您应该的方式使用它,它会显得复杂",所以我会写给您这个警告,您可以选择遵循通用准则或仅使用它来尝试功能.

Again, using shell=True is dangerous, it should be False and you should pass the command-string as a list. But for some reason it appears "complex" if you use it the way you're supposed to, so i'll write you this warning and you can choose to follow common guidelines or just use this to try the functionality out.

这是有关如何手动挂载 samba 的完整指南.按照此操作,并用自动编程替换手动步骤.

Here's a complete guide on how to manually mount samba. Follow this, and replace the manual steps with automated programming.

这篇关于在 python 脚本中访问共享的 smb ubuntu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆