Accessing shared smb ubuntu in python scripts

Murali Perumal picture Murali Perumal · May 18, 2015 · Viewed 13.8k times · Source

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.

Answer

Torxed picture Torxed · May 18, 2015

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.