Search code examples
pythonwindowspython-2.7copypywin32

The network name cannot be found - Copy file with Python in Windows


I am trying to copy a file from a server remotely to where the script is being executed, however it is returning me an error in the connection, if I make the connection via RDP from winodws, I connect normally to the host

Click to view the source code

script.py

#!/usr/bin/env python
#win32wnetfile.py

import os
import os.path
import shutil
import sys
import win32wnet

def netcopy(host, source, dest_dir, username=None, password=None, move=False):
    """ Copies files or directories to a remote computer. """

    wnet_connect(host, username, password)

    dest_dir = covert_unc(host, dest_dir)

    # Pad a backslash to the destination directory if not provided.
    if not dest_dir[len(dest_dir) - 1] == '\\':
        dest_dir = ''.join([dest_dir, '\\'])

    # Create the destination dir if its not there.
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    else:
        # Create a directory anyway if file exists so as to raise an error.
         if not os.path.isdir(dest_dir):
             os.makedirs(dest_dir)

    if move:
        shutil.move(source, dest_dir)
    else:
        shutil.copy(source, dest_dir)

def covert_unc(host, path):
    """ Convert a file path on a host to a UNC path."""
    return ''.join(['\\\\', host, '\\', path.replace(':', '$')])

def wnet_connect(host, username, password):
    unc = ''.join(['\\\\', host])
    try:
        win32wnet.WNetAddConnection2(0, None, unc, None, username, password)
    except Exception, err:
        if isinstance(err, win32wnet.error):
            # Disconnect previous connections if detected, and reconnect.
            if err[0] == 1219:
                win32wnet.WNetCancelConnection2(unc, 0, 0)
                return wnet_connect(host, username, password)
        raise err

if __name__ == '__main__':

    netcopy('192.168.9.254', 'C:\\Program Files (x86)\\Data\\connect.cfg', 'c:\\', 'localdomain\Administrator', 'pw1234')

Output

  File "script.py", line 13, in netcopy
    wnet_connect(host, username, password)
  File "script.py", line 67, in wnet_connect
    raise err
pywintypes.error: (67, 'WNetAddConnection2', 'The network name cannot be found.')

Solution

  • According to [MS.Docs]: WNetAddConnection2W function (emphasis is mine):

    • lpRemoteName

      A pointer to a null-terminated string that specifies the network resource to connect to. The string can be up to MAX_PATH characters in length, and must follow the network provider's naming conventions.

    So it should be a share name. I modified the code to work in my environment (one change only - replace the netcopy call from netcopy('192.168.9.254', 'C:\\Program Files (x86)\\Data\\connect.cfg', 'c:\\', 'localdomain\Administrator', 'pw1234'), to netcopy("127.0.0.1", "C:\\c\\a.txt", "C$"), as I connect to localhost where I have some shares).
    Notice dest_dir value: C$.

    Output:

    [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q061107274]> sopr.bat
    *** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***
    
    [prompt]> net share
    
    Share name   Resource                        Remark
    
    -------------------------------------------------------------------------------
    ADMIN$       C:\WINDOWS                      Remote Admin
    C$           C:\                             Default share
    E$           E:\                             Default share
    F$           F:\                             Default share
    G$           G:\                             Default share
    IPC$                                         Remote IPC
    L$           L:\                             Default share
    M$           M:\                             Default share
    N$           N:\                             Default share
    share-cfati  L:\Share\cfati
    share-public L:\Share\public
    The command completed successfully.
    
    
    [prompt]> dir /b c:\a*
    File Not Found
    
    [prompt]> "e:\Work\Dev\VEnvs\py_pc064_02.07.17_test0\Scripts\python.exe" code_orig.py
    
    [prompt]> dir /b c:\a*
    a.txt
    

    As a side note, on the remote machine the user must have administrative privileges, otherwise writing the file might fail with ERROR_ACCESS_DENIED (0x00000005), especially since you're targeting C:. It works for me, since my user has "God like" privileges on my computer.