怎么用脚本获取共享文件夹

wen 实用脚本 1

本文目录导读:

怎么用脚本获取共享文件夹

  1. PowerShell脚本
  2. 批处理脚本 (BAT)
  3. VBScript脚本
  4. Python脚本
  5. 实用脚本组合
  6. 注意事项

我来介绍几种获取共享文件夹的脚本方法,主要针对Windows环境。

PowerShell脚本

查看本地共享文件夹

# 获取所有本地共享文件夹
Get-SmbShare
# 获取共享文件夹详细信息
Get-SmbShare | Select-Object Name, Path, Description
# 获取特定共享的权限
Get-SmbShare -Name "共享名" | Get-SmbShareAccess

查看远程计算机共享

# 查看远程计算机的共享文件夹
Get-SmbShare -CimSession "计算机名或IP"
# 使用NET命令查看共享
net share
net view \\计算机名

批处理脚本 (BAT)

@echo off
echo 查看本地共享文件夹:
net share
echo.
echo 查看网络共享资源:
net view
echo.
echo 连接到共享文件夹:
net use Z: \\服务器\共享文件夹 /persistent:yes

VBScript脚本

' 获取本地共享文件夹
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colShares = objWMIService.ExecQuery("SELECT * FROM Win32_Share")
For Each objShare In colShares
    WScript.Echo "名称: " & objShare.Name
    WScript.Echo "路径: " & objShare.Path
    WScript.Echo "描述: " & objShare.Description
    WScript.Echo "---"
Next

Python脚本

import subprocess
import os
def get_local_shares():
    """获取本地共享文件夹"""
    try:
        # 方法1: 使用net share命令
        result = subprocess.run(['net', 'share'], capture_output=True, text=True)
        print("本地共享文件夹:")
        print(result.stdout)
        # 方法2: 使用wmic
        result2 = subprocess.run(['wmic', 'share', 'get', 'name,path,description'], 
                               capture_output=True, text=True)
        print("共享详细信息:")
        print(result2.stdout)
    except Exception as e:
        print(f"错误: {e}")
def get_remote_shares(computer_name):
    """获取远程计算机共享"""
    try:
        result = subprocess.run(['net', 'view', f'\\\\{computer_name}'], 
                              capture_output=True, text=True)
        print(f"{computer_name} 的共享资源:")
        print(result.stdout)
    except Exception as e:
        print(f"错误: {e}")
def mount_share(share_path, drive_letter='Z:'):
    """挂载共享文件夹"""
    try:
        result = subprocess.run(['net', 'use', drive_letter, share_path], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"成功挂载 {share_path} 到 {drive_letter}")
        else:
            print(f"挂载失败: {result.stderr}")
    except Exception as e:
        print(f"错误: {e}")
# 使用示例
if __name__ == "__main__":
    # 获取本地共享
    get_local_shares()
    # 获取远程共享(修改为实际计算机名)
    # get_remote_shares("192.168.1.100")
    # 挂载共享(修改为实际的共享路径)
    # mount_share("\\\\服务器\\共享文件夹")

实用脚本组合

创建一个完整的共享文件夹管理脚本 manage_shares.py

import subprocess
import os
import sys
class ShareManager:
    def __init__(self):
        self.shares = []
    def list_local_shares(self):
        """列出本地所有共享"""
        print("=== 本地共享文件夹 ===")
        result = subprocess.run(['net', 'share'], capture_output=True, text=True)
        print(result.stdout)
    def list_network_shares(self, remote_computer):
        """列出网络共享"""
        print(f"=== {remote_computer} 的共享 ===")
        result = subprocess.run(['net', 'view', f'\\\\{remote_computer}'], 
                              capture_output=True, text=True)
        print(result.stdout)
    def connect_share(self, share_path, drive_letter):
        """连接共享文件夹"""
        print(f"连接到: {share_path}")
        result = subprocess.run(['net', 'use', drive_letter, share_path], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"成功映射到 {drive_letter}")
            return True
        else:
            print(f"连接失败: {result.stderr}")
            return False
    def disconnect_share(self, drive_letter):
        """断开共享连接"""
        result = subprocess.run(['net', 'use', drive_letter, '/delete'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"已断开 {drive_letter}")
        else:
            print(f"断开失败: {result.stderr}")
    def save_to_file(self, filename="shares.txt"):
        """保存共享列表到文件"""
        result = subprocess.run(['net', 'share'], capture_output=True, text=True)
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(result.stdout)
        print(f"已保存到 {filename}")
def main():
    manager = ShareManager()
    print("共享文件夹管理工具")
    print("1. 查看本地共享")
    print("2. 查看远程共享")
    print("3. 连接共享文件夹")
    print("4. 断开共享连接")
    print("5. 保存共享列表")
    print("0. 退出")
    while True:
        choice = input("\n请选择操作: ")
        if choice == '1':
            manager.list_local_shares()
        elif choice == '2':
            computer = input("请输入计算机名或IP: ")
            manager.list_network_shares(computer)
        elif choice == '3':
            share_path = input("请输入共享路径(如: \\\\server\\share): ")
            drive = input("请输入盘符(如: Z): ")
            manager.connect_share(share_path, f"{drive}:")
        elif choice == '4':
            drive = input("请输入要断开的盘符(如: Z): ")
            manager.disconnect_share(f"{drive}:")
        elif choice == '5':
            manager.save_to_file()
        elif choice == '0':
            break
if __name__ == "__main__":
    main()

注意事项

  1. 权限要求:运行这些脚本通常需要管理员权限
  2. 防火墙:确保防火墙允许文件共享(端口445、139)
  3. 网络环境:远程访问需要在同一网络或VPN连接
  4. 身份验证:可能需要输入用户名和密码
  5. 系统兼容性
    • PowerShell:Windows 7及以上
    • net命令:所有Windows版本
    • WMI:Windows XP及以上

选择哪种方式取决于你的具体需求和操作系统环境。

抱歉,评论功能暂时关闭!