首页 > 解决方案 > 找不到网络名称 - 在 Windows 中使用 Python 复制文件

问题描述

我正在尝试将文件从服务器远程复制到正在执行脚本的位置,但是它在连接中返回错误,如果我通过 RDP 从 winodws 建立连接,我会正常连接到主机

点击查看源代码

脚本.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')

输出

  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.')

标签: pythonwindowspython-2.7copypywin32

解决方案


根据[MS.Docs]: WNetAddConnection2W 函数重点是我的):

  • lp远程名称

    指向以字符结尾的字符串的指针,该字符串指定要连接的网络资源。该字符串的长度最多为 MAX_PATH 个字符,并且必须遵循网络提供商的命名约定

所以它应该是一个共享名称。我修改了代码以在我的环境中工作(只有一个更改 - 将netcopy调用从netcopy('192.168.9.254', 'C:\\Program Files (x86)\\Data\\connect.cfg', 'c:\\', 'localdomain\Administrator', 'pw1234'), 替换为netcopy("127.0.0.1", "C:\\c\\a.txt", "C$"),因为我连接到我有一些共享的本地主机)。
注意dest_dir值:C$

输出

[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

附带说明,在远程计算机上,用户必须具有管理权限,否则写入文件可能会失败并出现ERROR_ACCESS_DENIED ( 0x00000005 ),尤其是因为您的目标是C:。它对我有用,因为我的用户在我的计算机上拥有“上帝般的”特权。


推荐阅读