背景说明
自己在做一个视频分析项目的时候,视频的分析程序已经写完,但是最终源视频和分析后的视频段需要存储到云盘上,便于存储管理。于是乎,考虑直接使用python命令代码去访问云盘,云盘的实际显示有两种,一种是链接的形式,另外一种是盘符的形式,考虑到链接局域随机性,于是考虑使用python命令,访问网络盘符的形式进行访问。
在 Python 中,可以使用 os
和 subprocess
模块来访问网络共享盘符。以下是使用 Python 访问网络共享盘符的几种方法:
方法一:使用 os
模块
可以使用 os
模块的 os.listdir()
函数来列出共享目录中的文件和文件夹。
import os
# 网络共享路径
network_path = r'\\10.192.168.138\视频数据库'
try:
# 列出共享目录中的文件和文件夹
files = os.listdir(network_path)
print("Files and directories in '", network_path, "' :")
print(files)
except Exception as e:
print(f"Failed to access the network path: {e}")
亲测可行,将IP换成自己需要使用的网盘IP即可。
方法二:使用 subprocess
模块并结合 net use
命令
可以使用 subprocess
模块来运行命令行命令,例如 net use
,以映射网络共享到一个本地驱动器盘符。
import subprocess
# 网络共享路径
network_path = r'\\10.192.168.138\视频数据库'
# 本地驱动器盘符
local_drive = 'Z:'
# 映射网络共享到本地驱动器盘符
try:
subprocess.run(['net', 'use', local_drive, network_path], check=True)
print(f"Network path {network_path} mapped to {local_drive}")
# 现在可以使用本地驱动器盘符访问网络共享
files = os.listdir(local_drive)
print(f"Files and directories in '{local_drive}' :")
print(files)
# 访问完后可以取消映射
subprocess.run(['net', 'use', local_drive, '/delete'], check=True)
print(f"Network path {network_path} unmapped from {local_drive}")
except subprocess.CalledProcessError as e:
print(f"Failed to map network path: {e}")
except Exception as e:
print(f"Failed to access the network path: {e}")
方法三:使用 pandas
和 openpyxl
读取共享目录中的Excel文件
如果你要访问共享目录中的特定文件(例如 Excel 文件),可以使用 pandas
和 openpyxl
库。
import pandas as pd
# 网络共享路径中的Excel文件
excel_path = r'\\10.192.168.138\视频数据库\example.xlsx'
try:
# 读取Excel文件
df = pd.read_excel(excel_path, engine='openpyxl')
print(df)
except Exception as e:
print(f"Failed to read the Excel file: {e}")
以上示例展示了如何在 Python 中访问网络共享。请根据实际需要选择合适的方法。注意,在使用网络共享时,可能需要提供访问凭证(用户名和密码),这可以通过命令行参数或库函数实现。
密码验证
如果在访问网络共享时需要提供用户名和密码,可以在使用 subprocess
模块时将凭证传递给 net use
命令。在这种情况下,net use
命令的语法为:
net use [local_drive] [network_path] /user:[domain\username] [password]
下面是如何修改代码以支持用户名和密码验证:
import os
import subprocess
# 网络共享路径
network_path = r'\\10.192.168.138\视频数据库'
# 本地驱动器盘符
local_drive = 'Z:'
# 用户名和密码
username = 'your_username'
password = 'your_password'
# 如果有域,可以使用 domain\username 的格式
domain = 'your_domain' # 如果没有域,可以设为空字符串 ''
# 构建 net use 命令
if domain:
user_with_domain = f"{domain}\\{username}"
else:
user_with_domain = username
try:
# 映射网络共享到本地驱动器盘符
subprocess.run(['net', 'use', local_drive, network_path, f'/user:{user_with_domain}', password], check=True)
print(f"Network path {network_path} mapped to {local_drive}")
# 现在可以使用本地驱动器盘符访问网络共享
files = os.listdir(local_drive)
print(f"Files and directories in '{local_drive}' :")
print(files)
# 访问完后可以取消映射
subprocess.run(['net', 'use', local_drive, '/delete'], check=True)
print(f"Network path {network_path} unmapped from {local_drive}")
except subprocess.CalledProcessError as e:
print(f"Failed to map network path: {e}")
except Exception as e:
print(f"Failed to access the network path: {e}")
注意事项
1.安全性:将密码直接嵌入代码中是不安全的,建议从环境变量或外部配置文件中读取凭证,避免将敏感信息硬编码在代码中。
2.域名:如果网络共享在域中,确保提供正确的域名。如果没有域名,可以忽略或留空。
3.错误处理:确保添加适当的错误处理,以应对可能出现的各种异常情况。
从环境变量读取凭证
一种更安全的方式是从环境变量中读取用户名和密码:
import os
import subprocess
# 从环境变量中读取用户名和密码
username = os.getenv('NETWORK_USERNAME')
password = os.getenv('NETWORK_PASSWORD')
domain = os.getenv('NETWORK_DOMAIN', '') # 默认为空字符串
# 网络共享路径
network_path = r'\\10.192.30.138\工站專家會診平台'
# 本地驱动器盘符
local_drive = 'Z:'
# 构建 net use 命令
if domain:
user_with_domain = f"{domain}\\{username}"
else:
user_with_domain = username
try:
# 映射网络共享到本地驱动器盘符
subprocess.run(['net', 'use', local_drive, network_path, f'/user:{user_with_domain}', password], check=True)
print(f"Network path {network_path} mapped to {local_drive}")
# 现在可以使用本地驱动器盘符访问网络共享
files = os.listdir(local_drive)
print(f"Files and directories in '{local_drive}' :")
print(files)
# 访问完后可以取消映射
subprocess.run(['net', 'use', local_drive, '/delete'], check=True)
print(f"Network path {network_path} unmapped from {local_drive}")
except subprocess.CalledProcessError as e:
print(f"Failed to map network path: {e}")
except Exception as e:
print(f"Failed to access the network path: {e}")
在运行代码之前,确保设置环境变量,例如在 Windows 命令提示符中:
set NETWORK_USERNAME=your_username
set NETWORK_PASSWORD=your_password
set NETWORK_DOMAIN=your_domain
这样可以更安全地处理敏感信息。