Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing shared smb ubuntu in python scripts

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.

like image 399
Murali Perumal Avatar asked May 18 '15 07:05

Murali Perumal


2 Answers

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.

like image 90
Torxed Avatar answered Oct 18 '22 11:10

Torxed


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.
like image 40
abarnert Avatar answered Oct 18 '22 10:10

abarnert