Accessing shared smb ubuntu in python scripts

≯℡__Kan透↙ 提交于 2019-12-24 13:41:09

问题


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

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:

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.


回答1:


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

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.

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




回答2:


Python's file-handling functions like os.listdir don't take GNOME URLs like Nautilus does, they take filenames. Those aren't the same thing.

You have three basic options here:

  1. Ask GNOME to look up the URLs for you, the same way Nautilus does.
  2. Pick a Python SMB client and use that instead. There are multiple options to choose from.
  3. Use an SMB filesystem plugin like CIFS VFS to mount the remote filesystem to a mount point so you can then access its files by pathname instead of by URL.


来源:https://stackoverflow.com/questions/30297355/accessing-shared-smb-ubuntu-in-python-scripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!