How do I mount a Windows server file share in MacOS in python?
An error results from this code (MacOS Sequoia, Windows Server 2022, VSCode, python 3.12.6):
from contextlib import contextmanager
import os
import shutil
import subprocess
remote_share = '//user:[email protected]/remote_share_folder'
local_folder = 'local_folder'
@contextmanager
def mounted():
retcode = subprocess.call(['/sbin/mount_smbfs', remote_share, local_folder])
if retcode != 0:
raise OSError("mount operation failed")
try:
with mounted():
shutil.copy(os.path.join(remote_share, 'textfile.txt'), local_folder)
except OSError as e:
print(f"Error: {e}")
Error: mount operation failed
mount_smbfs: server connection failed: No route to host
1
Looks like smbclient is a painless way to transfer files from a Windows Server to a local Mac:
import smbclient
file_name = "mytext.txt"
remote_path = r"\10.0.0.100\shared_folder\"
remotefile_path = fr"{remote_path}{file_name}"
local_path = "/Users/user/Documents/data/"
localfile_path = f"{local_path}{file_name}"
username = 'user'
pw = 'mypassword'
smbclient.ClientConfig(username=username, password=pw)
with smbclient.open_file(remotefile_path, mode="rb") as remote_file:
content = remote_file.read()
with open(localfile_path, "wb") as local_file:
local_file.write(content)
# Write to a file
# with smbclient.open_file(remote_path, mode="w") as file:
# file.write("Hello, Windows share!")
# List directory contents
# files = smbclient.listdir(remote_path)
# for file in files:
# print(file)
1