本文目录导读:

我来帮你实现一个共享目录检测脚本,以下是一个功能完整的示例,支持检测网络共享和本地共享目录。
Windows共享目录检测脚本 (PowerShell)
# 共享目录检测脚本.ps1
param(
[string]$SharePath = "",
[array]$ShareList = @(),
[string]$OutputFile = "share_check_report.csv"
)
function Test-ShareAccess {
param($Path)
try {
# 测试连接
$testResult = Test-Connection -ComputerName $Path.Split('\')[2] -Count 1 -Quiet
if (-not $testResult) {
return @{
Path = $Path
Status = "ERROR"
Message = "无法连接到远程计算机"
}
}
# 测试访问权限
if (Test-Path $Path) {
# 测试读取权限
$files = Get-ChildItem $Path -ErrorAction Stop
$canRead = $true
# 测试写入权限
$testFile = Join-Path $Path "test_write_$(Get-Date -Format 'yyyyMMddHHmmss').tmp"
try {
New-Item -Path $testFile -ItemType File -Force | Out-Null
Remove-Item $testFile -Force
$canWrite = $true
} catch {
$canWrite = $false
}
return @{
Path = $Path
Status = "SUCCESS"
Message = "访问正常 - 读取: $canRead, 写入: $canWrite"
Readable = $canRead
Writable = $canWrite
}
} else {
return @{
Path = $Path
Status = "ERROR"
Message = "路径不存在或无法访问"
}
}
} catch {
return @{
Path = $Path
Status = "ERROR"
Message = $_.Exception.Message
}
}
}
function Get-LocalShares {
# 获取本地共享目录
$shares = Get-WmiObject -Class Win32_Share | Where-Object { $_.Type -eq 0 } # Type 0 = 磁盘共享
return $shares | ForEach-Object {
@{
Name = $_.Name
Path = $_.Path
Description = $_.Description
}
}
}
# 主程序
Write-Host "=== 共享目录检测工具 ===" -ForegroundColor Cyan
if ($ShareList.Count -eq 0 -and [string]::IsNullOrEmpty($SharePath)) {
# 如果没有指定共享,检测本地共享
Write-Host "检测本地共享目录..." -ForegroundColor Yellow
$localShares = Get-LocalShares
foreach ($share in $localShares) {
Write-Host "本地共享: $($share.Name) -> $($share.Path)"
$result = Test-ShareAccess $share.Path
Write-Host " 状态: $($result.Status) - $($result.Message)"
}
} elseif ($ShareList.Count -gt 0) {
# 批量检测指定共享
Write-Host "批量检测共享目录..." -ForegroundColor Yellow
$results = @()
foreach ($share in $ShareList) {
Write-Host "检测: $share"
$result = Test-ShareAccess $share
$results += $result
Write-Host " 状态: $($result.Status) - $($result.Message)"
}
# 导出结果
$results | Export-Csv $OutputFile -NoTypeInformation
Write-Host "结果已导出到: $OutputFile" -ForegroundColor Green
} else {
# 检测单个共享
Write-Host "检测共享: $SharePath"
$result = Test-ShareAccess $SharePath
Write-Host "状态: $($result.Status)"
Write-Host "信息: $($result.Message)"
}
# 使用示例说明
Write-Host "`n使用方法:" -ForegroundColor Cyan
Write-Host "1. 检测本地共享: .\share_check.ps1"
Write-Host "2. 检测单个共享: .\share_check.ps1 -SharePath '\\server\share'"
Write-Host "3. 批量检测: .\share_check.ps1 -ShareList @('\\server1\share1','\\server2\share2')"
Linux NFS/Samba共享检测脚本 (Bash)
#!/bin/bash
# 共享目录检测脚本 - Linux版本
# 文件名: share_check.sh
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 检测NFS共享
check_nfs_share() {
local share_path="$1"
local mount_point="/tmp/nfs_test_$$"
echo -e "${YELLOW}检测NFS共享: $share_path${NC}"
# 创建临时挂载点
mkdir -p "$mount_point"
# 尝试挂载
if mount -t nfs "$share_path" "$mount_point" 2>/dev/null; then
echo -e "${GREEN} 挂载成功${NC}"
# 测试读写权限
if touch "$mount_point/test_write_$$.tmp" 2>/dev/null; then
echo -e "${GREEN} 写入权限: 正常${NC}"
rm -f "$mount_point/test_write_$$.tmp"
else
echo -e "${RED} 写入权限: 无${NC}"
fi
# 测试读取权限
if ls "$mount_point" >/dev/null 2>&1; then
echo -e "${GREEN} 读取权限: 正常${NC}"
else
echo -e "${RED} 读取权限: 无${NC}"
fi
# 卸载
umount "$mount_point"
rmdir "$mount_point"
return 0
else
echo -e "${RED} 挂载失败${NC}"
rmdir "$mount_point"
return 1
fi
}
# 检测Samba/CIFS共享
check_smb_share() {
local share_path="$1"
local mount_point="/tmp/smb_test_$$"
local username="${2:-guest}"
local password="${3:-}"
echo -e "${YELLOW}检测Samba共享: $share_path${NC}"
# 创建临时挂载点
mkdir -p "$mount_point"
# 尝试挂载
if [ -z "$password" ]; then
mount_cmd="mount -t cifs -o username=$username,guest $share_path $mount_point"
else
mount_cmd="mount -t cifs -o username=$username,password=$password $share_path $mount_point"
fi
if $mount_cmd 2>/dev/null; then
echo -e "${GREEN} 挂载成功${NC}"
# 测试读写权限
if touch "$mount_point/test_write_$$.tmp" 2>/dev/null; then
echo -e "${GREEN} 写入权限: 正常${NC}"
rm -f "$mount_point/test_write_$$.tmp"
else
echo -e "${RED} 写入权限: 无${NC}"
fi
# 卸载
umount "$mount_point"
rmdir "$mount_point"
return 0
else
echo -e "${RED} 挂载失败${NC}"
rmdir "$mount_point"
return 1
fi
}
# 检测本地共享目录
check_local_share() {
local share_path="$1"
echo -e "${YELLOW}检测本地共享目录: $share_path${NC}"
# 检查目录是否存在
if [ ! -d "$share_path" ]; then
echo -e "${RED} 目录不存在${NC}"
return 1
fi
# 检查读取权限
if [ -r "$share_path" ]; then
echo -e "${GREEN} 读取权限: 正常${NC}"
else
echo -e "${RED} 读取权限: 无${NC}"
fi
# 检查写入权限
if [ -w "$share_path" ]; then
echo -e "${GREEN} 写入权限: 正常${NC}"
else
echo -e "${RED} 写入权限: 无${NC}"
fi
# 检查执行权限
if [ -x "$share_path" ]; then
echo -e "${GREEN} 执行权限: 正常${NC}"
else
echo -e "${RED} 执行权限: 无${NC}"
fi
# 检查磁盘空间
local disk_info=$(df -h "$share_path" | tail -1)
echo -e " 磁盘信息: $disk_info"
}
# 主函数
main() {
echo -e "${GREEN}=== 共享目录检测工具 (Linux版本) ===${NC}"
case "$1" in
nfs)
if [ -z "$2" ]; then
echo "用法: $0 nfs <server:/path>"
exit 1
fi
check_nfs_share "$2"
;;
smb|cifs)
if [ -z "$2" ]; then
echo "用法: $0 smb <//server/share> [username] [password]"
exit 1
fi
check_smb_share "$2" "$3" "$4"
;;
local)
if [ -z "$2" ]; then
echo "用法: $0 local <path>"
exit 1
fi
check_local_share "$2"
;;
*)
echo "用法: $0 {nfs|smb|local} <路径> [参数]"
echo "示例:"
echo " $0 nfs 192.168.1.100:/shared"
echo " $0 smb //192.168.1.100/share username password"
echo " $0 local /mnt/share"
exit 1
;;
esac
}
# 执行主函数
main "$@"
跨平台Python检测脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
共享目录检测脚本 - Python版本
支持Windows和Linux
"""
import os
import sys
import platform
import argparse
from pathlib import Path
import subprocess
import tempfile
class ShareChecker:
def __init__(self):
self.system = platform.system()
def check_local_share(self, path):
"""检查本地共享目录"""
path = Path(path)
result = {
'path': str(path),
'status': 'unknown',
'details': {}
}
if not path.exists():
result['status'] = 'error'
result['details']['message'] = '路径不存在'
return result
# 检查权限
result['details']['readable'] = os.access(path, os.R_OK)
result['details']['writable'] = os.access(path, os.W_OK)
result['details']['executable'] = os.access(path, os.X_OK)
# 检查磁盘空间
try:
stat = os.statvfs(str(path)) if hasattr(os, 'statvfs') else None
if stat:
total = stat.f_frsize * stat.f_blocks
free = stat.f_frsize * stat.f_bfree
result['details']['total_space'] = self._format_size(total)
result['details']['free_space'] = self._format_size(free)
except:
pass
# 判断状态
if result['details']['readable']:
result['status'] = 'success'
else:
result['status'] = 'error'
return result
def check_nfs_share(self, server, share_path):
"""检查NFS共享(Linux)"""
if self.system != 'Linux':
return {'status': 'error', 'message': 'NFS检查仅支持Linux'}
mount_point = tempfile.mkdtemp()
remote_path = f"{server}:{share_path}"
try:
# 尝试挂载
result = subprocess.run(
['mount', '-t', 'nfs', remote_path, mount_point],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0:
# 测试写入
test_file = Path(mount_point) / f"test_{os.getpid()}.tmp"
try:
test_file.write_text("test")
test_file.unlink()
writable = True
except:
writable = False
# 卸载
subprocess.run(['umount', mount_point], capture_output=True)
return {
'status': 'success',
'server': server,
'path': share_path,
'writable': writable
}
else:
return {
'status': 'error',
'server': server,
'path': share_path,
'message': result.stderr
}
except Exception as e:
return {
'status': 'error',
'server': server,
'path': share_path,
'message': str(e)
}
finally:
# 清理
if os.path.exists(mount_point):
os.rmdir(mount_point)
def check_smb_share(self, server, share_name, username='guest', password=''):
"""检查Samba共享"""
if self.system == 'Windows':
return self._check_windows_share(server, share_name)
else:
return self._check_linux_smb(server, share_name, username, password)
def _check_windows_share(self, server, share_name):
"""Windows系统检查共享"""
unc_path = f"\\\\{server}\\{share_name}"
# 使用PowerShell检查
ps_command = f"""
$testPath = '{unc_path}'
if (Test-Path $testPath) {{
$files = Get-ChildItem $testPath -ErrorAction SilentlyContinue
Write-Output "SUCCESS"
}} else {{
Write-Output "ERROR"
}}
"""
try:
result = subprocess.run(
['powershell', '-Command', ps_command],
capture_output=True, text=True, timeout=10
)
status = 'success' if 'SUCCESS' in result.stdout else 'error'
return {
'status': status,
'server': server,
'share': share_name,
'path': unc_path
}
except Exception as e:
return {
'status': 'error',
'server': server,
'share': share_name,
'path': unc_path,
'message': str(e)
}
def _check_linux_smb(self, server, share_name, username, password):
"""Linux系统检查Samba共享"""
mount_point = tempfile.mkdtemp()
remote_path = f"//{server}/{share_name}"
# 构建挂载命令
if password:
mount_cmd = f"mount -t cifs -o username={username},password={password}"
else:
mount_cmd = f"mount -t cifs -o username={username},guest"
mount_cmd += f" {remote_path} {mount_point}"
try:
result = subprocess.run(
mount_cmd.split(),
capture_output=True, text=True, timeout=30
)
if result.returncode == 0:
subprocess.run(['umount', mount_point], capture_output=True)
return {
'status': 'success',
'server': server,
'share': share_name,
'path': remote_path
}
else:
return {
'status': 'error',
'server': server,
'share': share_name,
'path': remote_path,
'message': result.stderr
}
except Exception as e:
return {
'status': 'error',
'server': server,
'share': share_name,
'path': remote_path,
'message': str(e)
}
finally:
if os.path.exists(mount_point):
os.rmdir(mount_point)
def _format_size(self, size):
"""格式化文件大小"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size:.2f} {unit}"
size /= 1024.0
return f"{size:.2f} PB"
def check_from_config(self, config_file):
"""从配置文件批量检查"""
import json
with open(config_file, 'r') as f:
config = json.load(f)
results = []
for share in config.get('shares', []):
share_type = share.get('type', 'local')
if share_type == 'local':
result = self.check_local_share(share['path'])
elif share_type == 'nfs':
result = self.check_nfs_share(share['server'], share['path'])
elif share_type == 'smb':
result = self.check_smb_share(
share['server'],
share['share'],
share.get('username', 'guest'),
share.get('password', '')
)
results.append(result)
self._print_result(result)
return results
def _print_result(self, result):
"""打印检查结果"""
status_color = '\033[92m' if result['status'] == 'success' else '\033[91m'
reset_color = '\033[0m'
print(f"{status_color}[{result['status'].upper()}]{reset_color} {result.get('path', '')}")
if 'details' in result:
for key, value in result['details'].items():
print(f" {key}: {value}")
def main():
parser = argparse.ArgumentParser(description='共享目录检测工具')
parser.add_argument('type', choices=['local', 'nfs', 'smb', 'config'],
help='检测类型')
parser.add_argument('path', nargs='?', help='要检测的路径')
parser.add_argument('--server', help='服务器地址')
parser.add_argument('--share', help='共享名称')
parser.add_argument('--username', default='guest', help='用户名')
parser.add_argument('--password', default='', help='密码')
parser.add_argument('--config', help='配置文件路径')
args = parser.parse_args()
checker = ShareChecker()
if args.type == 'config':
if not args.config:
print("使用config类型需要指定--config参数")
sys.exit(1)
checker.check_from_config(args.config)
elif args.type == 'local':
if not args.path:
print("使用local类型需要指定路径")
sys.exit(1)
result = checker.check_local_share(args.path)
checker._print_result(result)
elif args.type == 'nfs':
if not args.server or not args.path:
print("使用nfs类型需要指定--server和path")
sys.exit(1)
result = checker.check_nfs_share(args.server, args.path)
checker._print_result(result)
elif args.type == 'smb':
if not args.server or not args.share:
print("使用smb类型需要指定--server和--share")
sys.exit(1)
result = checker.check_smb_share(
args.server, args.share,
args.username, args.password
)
checker._print_result(result)
if __name__ == '__main__':
main()
配置文件示例 (config.json)
{
"shares": [
{
"type": "local",
"path": "/mnt/shared"
},
{
"type": "nfs",
"server": "192.168.1.100",
"path": "/export/shared"
},
{
"type": "smb",
"server": "192.168.1.100",
"share": "documents",
"username": "user1",
"password": "password123"
}
]
}
使用说明
Windows PowerShell脚本
# 添加执行策略
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# 运行脚本
.\share_check.ps1
.\share_check.ps1 -SharePath "\\server\share"
.\share_check.ps1 -ShareList @("\\server1\share1","\\server2\share2")
Linux Bash脚本
# 添加执行权限 chmod +x share_check.sh # 运行脚本 ./share_check.sh local /mnt/share ./share_check.sh nfs 192.168.1.100:/shared ./share_check.sh smb //192.168.1.100/share username password
Python脚本
# 安装依赖 pip install pathlib # Python 2兼容,Python 3内置 # 运行脚本 python share_check.py local /mnt/share python share_check.py nfs --server 192.168.1.100 --path /shared python share_check.py smb --server 192.168.1.100 --share documents --username user1 --password pwd python share_check.py config --config config.json
功能特点
- 多协议支持:支持本地、NFS、Samba/CIFS共享
- 权限检测:自动检测读写权限
- 跨平台:支持Windows和Linux
- 批量检测:支持配置文件批量检测
- 详细报告:输出详细的检测结果
- 错误处理:完善的异常处理机制
根据需要选择适合你环境的脚本版本。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播