Skip to content Skip to sidebar Skip to footer

Access Remote Files On Server With Smb Protocol Python3

I have a remote server with some files. smb://ftpsrv/public/ I can be authorized there as an anonymous user. In java I could simply write this code: SmbFile root = new SmbFile(SMB

Solution 1:

A simple example of opening a file using urllib and pysmb in Python 3

import urllib
from smb.SMBHandler import SMBHandler
opener = urllib.request.build_opener(SMBHandler)
fh = opener.open('smb://host/share/file.txt')
data = fh.read()
fh.close()

I haven't got an anonymous SMB share ready to test it with, but this code should work. urllib2 is the python 2 package, in python 3 it was renamed to just urllib and some stuff got moved around.

Solution 2:

I think you were asking for Linux, but for completeness I'll share how it works on Windows.

On Windows, it seems that Samba access is supported out of the box with Python's standard library functions:

import glob, os

withopen(r'\\USER1-PC\Users\Public\test.txt', 'w') as f:
    f.write('hello')    # write a file on a distant Samba sharefor f in glob.glob(r'\\USER1-PC\Users\**\*', recursive=True):
    print(f)   # glob works tooif os.path.isfile(f):
        print(os.path.getmtime(f))  # we can get filesystem information

Post a Comment for "Access Remote Files On Server With Smb Protocol Python3"