【问题标题】:Python - get a size of a network path folderPython - 获取网络路径文件夹的大小
【发布时间】:2017-12-05 11:52:28
【问题描述】:

我正在使用 Python 2.7 来监控在 Windows 2012 服务器上运行的某些应用程序的磁盘使用情况。如何获取位于例如此处的某些网络存储文件夹的大小:

\\storage\my_folder\

我尝试过使用(来自这篇文章:calculating-a-directory-size-using-python):

import os

def getFolderSize(folder):
    total_size = os.path.getsize(folder)
    for item in os.listdir(folder):
        itempath = os.path.join(folder, item)
        if os.path.isfile(itempath):
            total_size += os.path.getsize(itempath)
        elif os.path.isdir(itempath):
            total_size += getFolderSize(itempath)
    return total_size

当然不支持网络路径。

【问题讨论】:

  • 我必须将网络驱动器映射到本地字母才能使某些脚本正常工作。

标签: python


【解决方案1】:

如果是 2012 (Windows) 服务器,您也许可以使用 SMB。

这是我刚刚用来获取 Windows 服务器上共享文件夹大小的一个小型测试程序。我没有对它进行详尽的测试,所以它可能需要一些工作,但它应该为你提供工作的基础。

它使用pysmb

from smb import SMBConnection

sep = '\\'

def RecursiveInspector(conn, shareName, path):
    #print path.encode('utf8')
    localSize = 0
    response = conn.listPath(shareName, path, timeout=30)
    for i in range(len(response)):
        fname = response[i].filename
        if (fname == ".") or (fname == ".."):
            continue
        if (response[i].isDirectory):
            dname = path
            if not (path.endswith(sep)):
                dname += sep
            dname += fname
            localSize += RecursiveInspector(conn, shareName, dname)
        else:
            localSize += response[i].file_size
    return localSize

conn = SMBConnection.SMBConnection("my_username",
                                   "my_password",
                                   "laptop",
                                   "the_shared_folder_name",
                                   use_ntlm_v2 = True)
conn.connect("1.2.3.4", 139)

path      = sep # start at root
totalSize = RecursiveInspector(conn, "the_shared_folder_name", path)

print totalSize

希望这可能有用。

【讨论】:

  • 能否请您帮我修改脚本以便可以在存储文件夹中使用?似乎 SMBConnection.SMBConnection 函数需要共享文件夹所在机器的“remote_name”。如果是存储位置,我该如何使用它?
【解决方案2】:

感谢post 使用win32com.client 使我能够获得网络文件夹的大小!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    相关资源
    最近更新 更多