脚本如何检测CIFS共享是否正常

wen 实用脚本 12

本文目录导读:

脚本如何检测CIFS共享是否正常

  1. Bash脚本 - Linux系统
  2. Python脚本
  3. Windows PowerShell脚本
  4. 综合监测脚本(带邮件告警)
  5. 使用Docker进行检测
  6. 推荐使用

Bash脚本 - Linux系统

简单挂载检测

#!/bin/bash
# 检测CIFS共享是否可挂载
CIFS_SERVER="//192.168.1.100"
CIFS_SHARE="/share_name"
MOUNT_POINT="/mnt/cifs_test"
# 创建临时挂载点
mkdir -p $MOUNT_POINT
# 尝试挂载
mount -t cifs $CIFS_SERVER$CIFS_SHARE $MOUNT_POINT -o username=user,password=pass 2>/dev/null
if [ $? -eq 0 ]; then
    echo "CIFS共享正常:可以挂载"
    umount $MOUNT_POINT
    exit 0
else
    echo "CIFS共享异常:无法挂载"
    rmdir $MOUNT_POINT
    exit 1
fi

使用smbclient检测

#!/bin/bash
# 使用smbclient检测共享可用性
SERVER="192.168.1.100"
SHARE="share_name"
USER="domain\\user"
PASS="password"
# 测试连接
smbclient "//$SERVER/$SHARE" -U "$USER%$PASS" -c "ls" 2>/dev/null | head -n 5
if [ $? -eq 0 ]; then
    echo "✓ CIFS共享 $SERVER/$SHARE 正常"
else
    echo "✗ CIFS共享 $SERVER/$SHARE 异常"
fi

Python脚本

#!/usr/bin/env python3
import subprocess
import sys
import os
def check_cifs_share(server, share, mount_point="/tmp/cifs_check"):
    """检测CIFS共享可用性"""
    # 尝试挂载
    if not os.path.exists(mount_point):
        os.makedirs(mount_point)
    cmd = f"mount -t cifs //{server}/{share} {mount_point} -o username=guest"
    try:
        result = subprocess.run(cmd.split(), capture_output=True, timeout=10)
        if result.returncode == 0:
            # 测试读写权限
            test_file = f"{mount_point}/test_write_{os.getpid()}.tmp"
            try:
                with open(test_file, 'w') as f:
                    f.write("test")
                os.remove(test_file)
                print(f"✓ CIFS共享 {server}/{share} 正常 (可读写)")
            except:
                print(f"✓ CIFS共享 {server}/{share} 正常 (只读)")
            # 卸载
            subprocess.run(f"umount {mount_point}".split())
            return True
        else:
            print(f"✗ CIFS共享 {server}/{share} 异常: {result.stderr.decode()}")
            return False
    except subprocess.TimeoutExpired:
        print(f"✗ CIFS共享 {server}/{share} 连接超时")
        return False
    except Exception as e:
        print(f"✗ 检测失败: {e}")
        return False
    finally:
        if os.path.exists(mount_point):
            os.rmdir(mount_point)
# 使用示例
if __name__ == "__main__":
    check_cifs_share("192.168.1.100", "share_name")

Windows PowerShell脚本

# 检测Windows下的SMB共享
$Server = "192.168.1.100"
$Share = "share_name"
# 方法1: 测试网络路径
$path = "\\$Server\$Share"
if (Test-Path $path) {
    Write-Host "✓ CIFS共享 $path 正常访问" -ForegroundColor Green
    # 测试读写
    $testFile = "$path\test_$(Get-Random).tmp"
    try {
        "test" | Out-File -FilePath $testFile -ErrorAction Stop
        Remove-Item $testFile -Force
        Write-Host "✓ 共享可读写" -ForegroundColor Green
    }
    catch {
        Write-Host "✓ 共享只读" -ForegroundColor Yellow
    }
}
else {
    Write-Host "✗ CIFS共享 $path 无法访问" -ForegroundColor Red
}
# 方法2: 使用net use命令
$result = net use "Z:" "\\$Server\$Share" /user:domain\user password 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "✓ 挂载成功" -ForegroundColor Green
    net use Z: /delete
}

综合监测脚本(带邮件告警)

#!/usr/bin/env python3
"""
完整的CIFS共享监控脚本
依赖: python3, smbclient, mount.cifs
"""
import subprocess
import smtplib
from email.mime.text import MIMEText
import datetime
import socket
def check_cifs(server, share, username="guest", password=""):
    """完整检测CIFS共享状态"""
    results = {
        'server': server,
        'share': share,
        'timestamp': datetime.datetime.now(),
        'ping_ok': False,
        'smb_connect': False,
        'mount_ok': False,
        'readwrite': False
    }
    # 1. Ping测试
    ping_result = subprocess.run(
        ['ping', '-c', '1', '-W', '3', server],
        capture_output=True
    )
    results['ping_ok'] = ping_result.returncode == 0
    if not results['ping_ok']:
        return results
    # 2. SMB端口测试
    try:
        import socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)
        result = sock.connect_ex((server, 445))
        results['smb_connect'] = result == 0
        sock.close()
    except:
        pass
    # 3. smbclient测试
    cmd = f"smbclient //{server}/{share} -N -c 'ls'"
    smb_result = subprocess.run(cmd.split(), capture_output=True, timeout=10)
    results['smb_connect'] = smb_result.returncode == 0
    # 4. 挂载测试
    mount_point = "/tmp/cifs_monitor"
    subprocess.run(['mkdir', '-p', mount_point])
    mount_cmd = f"mount -t cifs //{server}/{share} {mount_point}"
    if username != "guest":
        mount_cmd += f" -o username={username}"
    if password:
        mount_cmd += f",password={password}"
    mount_result = subprocess.run(mount_cmd.split(), capture_output=True, timeout=15)
    results['mount_ok'] = mount_result.returncode == 0
    # 5. 读写测试
    if results['mount_ok']:
        test_file = f"{mount_point}/test_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.tmp"
        try:
            with open(test_file, 'w') as f:
                f.write("test")
            os.remove(test_file)
            results['readwrite'] = True
        except:
            pass
    # 清理
    if results['mount_ok']:
        subprocess.run(['umount', mount_point])
    subprocess.run(['rmdir', mount_point])
    return results
def send_alert(results):
    """发送告警邮件"""
    msg = f"""
    CIFS共享异常告警
    服务器: {results['server']}
    共享: {results['share']}
    时间: {results['timestamp']}
    检测结果:
    - Ping: {'正常' if results['ping_ok'] else '失败'}
    - SMB连接: {'正常' if results['smb_connect'] else '失败'}
    - 挂载: {'正常' if results['mount_ok'] else '失败'}
    - 读写: {'正常' if results['readwrite'] else '失败'}
    """
    # 配置邮件发送
    # ... 邮件配置代码
# 主程序
if __name__ == "__main__":
    import os
    config = {
        'server': '192.168.1.100',
        'share': 'share_name',
        'username': 'user',
        'password': 'pass'
    }
    result = check_cifs(**config)
    # 检查是否正常
    if not all([result['ping_ok'], result['smb_connect'], result['mount_ok']]):
        print(f"[ALERT] CIFS共享异常: {result['server']}/{result['share']}")
        # send_alert(result)
    else:
        print(f"[OK] CIFS共享正常: {result['server']}/{result['share']}")

使用Docker进行检测

#!/bin/bash
# Docker容器化检测
docker run --rm \
  -v /mnt/cifs_check:/mnt/cifs:shared \
  alpine:latest \
  sh -c "
    apk add cifs-utils
    mount -t cifs //192.168.1.100/share /mnt/cifs -o username=guest
    if [ \$? -eq 0 ]; then
        echo 'CIFS共享正常'
        umount /mnt/cifs
    else
        echo 'CIFS共享异常'
    fi
  "

推荐使用

  • 日常监控:使用Bash + smbclient组合
  • 企业环境:使用Python综合检测脚本,配合Zabbix/Nagios
  • Windows环境:使用PowerShell脚本

注意事项

  1. 需要安装cifs-utils(smbclient)包
  2. 敏感信息(密码)建议使用配置文件或环境变量
  3. 生产环境建议使用非root用户执行
  4. 考虑网络延迟,设置适当的超时时间

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