用python编写从局域网中的共享磁盘里面拉取文件到指定本地路径的脚本
时间: 2024-09-18 13:14:22 浏览: 30
在Python中,你可以使用`os`, `socket`和`smbprotocol`库来编写一个简单的脚本来从局域网的SMB共享目录拉取文件。这里是一个基本的示例,假设你知道共享资源的服务器名、共享名称、用户名、密码以及你要下载的文件路径:
```python
import os
from smb.SMBConnection import SMBConnection
def download_from_smb(server_ip, share_name, username, password, remote_path, local_path):
# 创建SMB连接
try:
conn = SMBConnection(username, password, server_ip, server_ip)
if not conn.connect():
print("Failed to connect to the server.")
return False
# 获取共享资源
share = conn.getShares()[share_name]
# 拼接远程文件路径
remote_file = os.path.join(share, remote_path)
# 检查目标文件是否存在
if not conn.fileExists(remote_file):
print(f"File {remote_file} does not exist on the server.")
conn.close()
return False
# 定义本地保存路径
local_file = os.path.join(local_path, os.path.basename(remote_file))
# 开始下载文件
with open(local_file, 'wb') as f:
file_data = conn.getFile(share_name, remote_file, f)
print(f"Successfully downloaded file from {remote_file} to {local_file}")
file_data.close()
conn.close()
return True
except Exception as e:
print(f"An error occurred: {e}")
conn.close()
return False
# 使用函数
download_from_smb('your_server_ip', 'your_share_name', 'your_username', 'your_password', 'remote_directory/file.ext', '/path/to/local/save/directory')
```
注意替换上述代码中的`your_server_ip`, `your_share_name`, `your_username`, `your_password`, `remote_directory/file.ext` 和 `/path/to/local/save/directory`为你实际的值。
阅读全文