Failed to connect to the network drive – Using Python win32api, win32net

  Kiến thức lập trình

I am working on a Python script that will work with a shared network drive.

Here is the error I get: Failed to connect to the network drive: (50, ‘NetUseAdd’, ‘The request is not supported.’)

The credentials are correct, the URI paths are correct, I’ve updated Python and PIP, I’ve talked to my security team and my comms do get across their firewall.

I’m not sure if this matters, but I am using the Python terminal to execute this script and passing along parameters, to test the functionality of the script before I begin to hard coded it into our project.

The server is on a different domain, but that shouldn’t matter as my C# version is able to access the drive without any problem.

Here is the script -ps I am copying files from the network drive -Source to my C: drive -Destination:

import shutil
import os
import win32net
import win32api

username = "someName"
password = "somepassword"

def copy_file(source_path, destination_path):
    # Connect to the network drive
    try:
        win32net.NetUseAdd("server_address", 1, {
            'local': None,
            'remote': "networkdriveuri",
            'password': password,
            'username': username
        })
        print("Connected to the network drive successfully.")
    except Exception as e:
        print(f"Failed to connect to the network drive: {e}")
        return

    # Copy the file
    try:
        shutil.copy(source_path, destination_path)
        print("File copied successfully.")
    except Exception as e:
        print(f"Unable to copy file: {e}")
    finally:
        # Disconnect from the network drive
        try:
            win32net.NetUseDel(None, source_path)
            print("Disconnected from the network drive.")
        except Exception as e:
            print(f"Failed to disconnect from the network drive: {e}")

Here is what I’m typing into my Python 3.10(64-bit) console:

exec(open("C:\\Users\me\Desktop\test.py").read()) 

copy_file("//ServerAddress/folder/folder2/folder3/somefile.txt", "C://aFolder/")

New contributor

Miguel Villasenor Espinosa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT