75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392 | @support_hooks
class Samba(FileConnection):
"""Samba file connection. [](/hooks/)
Based on [pysmb library](https://pypi.org/project/pysmb/).
!!! success "Added in 0.9.4"
!!! warning
To use Samba connector you should install package as follows:
```bash
pip install "onetl[samba]"
# or
pip install "onetl[files]"
```
See [install-files][] installation instruction for more details.
Parameters
----------
host : str
Host of Samba source. For example: `mydomain.com`.
share : str
The name of the share on the Samba server.
protocol : str, default: `SMB`
The protocol to use for the connection. Either `SMB` or `NetBIOS`.
Affects the default port and the `is_direct_tcp` flag in `SMBConnection`.
port : int, default: 445
Port of Samba source.
domain : str, default: ` `
Windows workgroup name. Empty strings means use `host` as domain name.
auth_type : str, default: `NTLMv2`
The authentication type to use. Either `NTLMv2` (recommended) or `NTLMv1` (Windows XP).
user : str, default: None
User, which have access to the file source. Can be `None` for anonymous connection.
password : str, default: None
Password for file source connection. Can be `None` for anonymous connection.
extra : SambaExtra, default: `SambaExtra()`
Extra options for Samba connection.
Examples
--------
=== "Create and check Samba connection"
```python
from onetl.connection import Samba
samba = Samba(
host="mydomain.com",
share="share_name",
protocol="SMB",
port=445,
user="user",
password="password",
).check()
```
=== "Create Samba connection with extra options"
```python
from onetl.connection import Samba
from smb.SMBConnection import SMBConnection
samba = Samba(
host="mydomain.com",
share="share_name",
protocol="SMB",
port=445,
user="user",
password="password",
extra=Samba.Extra(my_name="my_name", sign_options=SMBConnection.SIGN_NEVER),
).check()
```
"""
host: Host
share: str
protocol: Literal["SMB", "NetBIOS"] = "SMB"
port: Optional[int] = None
domain: str = ""
auth_type: Literal["NTLMv1", "NTLMv2"] = "NTLMv2"
user: Optional[str] = None
password: Optional[SecretStr] = None
extra: SambaExtra = Field(default_factory=SambaExtra)
Extra = SambaExtra
@validator("port", pre=True, always=True)
def _set_port_based_on_protocol(cls, port, values):
if port is None:
return 445 if values.get("protocol") == "SMB" else 139
return port
@property
def instance_url(self) -> str:
return f"smb://{self.host}:{self.port}/{self.share}"
def __str__(self):
return f"{self.__class__.__name__}[{self.host}:{self.port}/{self.share}]"
@slot
def check(self):
log.info("|%s| Checking connection availability...", self.__class__.__name__)
self._log_parameters()
try:
available_shares = {share.name for share in self.client.listShares()}
if self.share in available_shares:
log.info("|%s| Connection is available.", self.__class__.__name__)
else:
log.error(
"|%s| Share %r not found among existing shares %r",
self.__class__.__name__,
self.share,
available_shares,
)
msg = "Failed to connect to the Samba server."
raise ConnectionError(msg) # noqa: TRY301
except Exception as exc:
log.exception("|%s| Connection is unavailable", self.__class__.__name__)
msg = "Connection is unavailable"
raise RuntimeError(msg) from exc
return self
@slot
def path_exists(self, path: os.PathLike | str) -> bool:
try:
self.client.getAttributes(self.share, os.fspath(path))
except OperationFailure:
return False
else:
return True
def _scan_entries(self, path: RemotePath) -> list:
if self._is_dir(path):
return [
entry
for entry in self.client.listPath(
self.share,
os.fspath(path),
)
if entry.filename not in {".", ".."} # Filter out '.' and '..'
]
return [self.client.getAttributes(self.share, os.fspath(path))]
def _extract_name_from_entry(self, entry) -> str:
return entry.filename
def _is_dir_entry(self, top: RemotePath, entry) -> bool:
return entry.isDirectory
def _is_file_entry(self, top: RemotePath, entry) -> bool:
return not entry.isDirectory
def _extract_stat_from_entry(self, top: RemotePath, entry) -> RemotePathStat:
if entry.isDirectory:
return RemotePathStat()
return RemotePathStat(
st_size=entry.file_size,
st_mtime=entry.last_write_time,
st_uid=entry.filename,
)
def _get_stat(self, path: RemotePath) -> RemotePathStat:
info = self.client.getAttributes(self.share, os.fspath(path))
if info.isDirectory:
return RemotePathStat()
return RemotePathStat(
st_size=info.file_size,
st_mtime=info.last_write_time,
st_uid=info.filename,
)
def _get_client(self) -> SMBConnection:
is_direct_tcp = self.protocol == "SMB"
use_ntlm_v2 = self.auth_type == "NTLMv2"
extra = self.extra.dict(by_alias=True, exclude={"operation_timeout", "connect_timeout"})
conn = SMBConnection(
username=self.user,
password=self.password.get_secret_value() if self.password else None,
remote_name=self.host,
domain=self.domain,
use_ntlm_v2=use_ntlm_v2,
is_direct_tcp=is_direct_tcp,
**extra,
)
auth_result = conn.connect(
self.host,
port=self.port,
timeout=self.extra.connect_timeout,
)
if not auth_result:
msg = "Failed to connect to the Samba server."
raise ConnectionError(msg)
return conn
def _is_client_closed(self, client: SMBConnection) -> bool:
try:
socket_fileno = client.sock.fileno()
except (AttributeError, OSError):
return True
return socket_fileno == -1
def _close_client(self, client: SMBConnection) -> None:
client.close()
def _download_file(self, remote_file_path: RemotePath, local_file_path: LocalPath) -> None:
with local_file_path.open("wb") as local_file:
self.client.retrieveFile(
self.share,
os.fspath(remote_file_path),
local_file,
timeout=self.extra.operation_timeout,
)
def _create_dir(self, path: RemotePath) -> None:
path_obj = Path(path)
for parent in reversed(path_obj.parents):
# create dirs sequentially as .createDirectory(...) cannot create nested dirs
try:
self.client.getAttributes(self.share, os.fspath(parent), timeout=self.extra.operation_timeout)
except OperationFailure: # noqa: PERF203
self.client.createDirectory(self.share, os.fspath(parent), timeout=self.extra.operation_timeout)
self.client.createDirectory(self.share, os.fspath(path), timeout=self.extra.operation_timeout)
def _upload_file(self, local_file_path: LocalPath, remote_file_path: RemotePath) -> None:
with local_file_path.open("rb") as file_obj:
self.client.storeFile(
self.share,
os.fspath(remote_file_path),
file_obj,
)
def _rename_file(self, source: RemotePath, target: RemotePath) -> None:
self.client.rename(
self.share,
os.fspath(source),
os.fspath(target),
timeout=self.extra.operation_timeout,
)
def _remove_file(self, remote_file_path: RemotePath) -> None:
self.client.deleteFiles(
self.share,
os.fspath(remote_file_path),
timeout=self.extra.operation_timeout,
)
def _remove_dir(self, path: RemotePath) -> None:
self.client.deleteDirectory(
self.share,
os.fspath(path),
timeout=self.extra.operation_timeout,
)
def _remove_dir_recursive(self, root: RemotePath) -> None:
self.client.deleteFiles(
self.share,
os.fspath(root).rstrip("/") + "/*",
delete_matching_folders=True,
timeout=self.extra.operation_timeout,
)
self.client.deleteDirectory(
self.share,
os.fspath(root),
timeout=self.extra.operation_timeout,
)
def _read_text(self, path: RemotePath, encoding: str) -> str:
return self._read_bytes(path).decode(encoding)
def _read_bytes(self, path: RemotePath) -> bytes:
file_obj = BytesIO()
self.client.retrieveFile(
self.share,
os.fspath(path),
file_obj,
timeout=self.extra.operation_timeout,
)
file_obj.seek(0)
return file_obj.read()
def _write_text(self, path: RemotePath, content: str, encoding: str) -> None:
self._write_bytes(path, bytes(content, encoding))
def _write_bytes(self, path: RemotePath, content: bytes) -> None:
file_obj = BytesIO(content)
self.client.storeFile(
self.share,
os.fspath(path),
file_obj,
timeout=self.extra.operation_timeout,
)
def _is_dir(self, path: RemotePath) -> bool:
attributes = self.client.getAttributes(self.share, os.fspath(path), timeout=self.extra.operation_timeout)
return attributes.isDirectory
def _is_file(self, path: RemotePath) -> bool:
return not self._is_dir(path)
|