Python 下使用samba访问共享
时间: 2023-07-20 19:27:31 浏览: 63
要在 Python 下使用 Samba 访问共享,你可以使用 Python 的 Samba 模块 pysmb。以下是一个简单的示例代码:
```python
from smb.SMBConnection import SMBConnection
# 设置 Samba 连接参数
conn = SMBConnection('username', 'password', 'client_name', 'server_name', use_ntlm_v2=True)
conn.connect('server_ip', 139)
# 访问共享目录
shares = conn.listShares()
for share in shares:
if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
print(share.name)
# 读取共享文件
file_obj = conn.openFile('share_name', 'file_path', 'r')
content = file_obj.read()
file_obj.close()
# 写入共享文件
file_obj = conn.openFile('share_name', 'file_path', 'w')
file_obj.write('hello world')
file_obj.close()
# 断开 Samba 连接
conn.close()
```
在这个示例中,我们首先通过 SMBConnection() 构造函数设置了 Samba 连接参数。然后使用 connect() 方法连接到 Samba 服务器。接下来,我们使用 listShares() 方法列出了服务器上的共享目录,并打印了它们的名称。最后,我们使用 openFile() 方法读取了一个共享文件的内容,并使用同样的方法写入了一些内容。最后,我们使用 close() 方法断开了 Samba 连接。