| 1 |
from lxml.builder import E |
| 2 |
|
| 3 |
from jnpr.junos.utils.util import Util |
| 4 |
from jnpr.junos.utils.start_shell import StartShell |
| 5 |
|
| 6 |
from jnpr.junos.exception import RpcError |
| 7 |
|
| 8 |
|
| 9 |
class FS(Util): |
| 10 |
""" |
| 11 |
Filesystem (FS) utilities: |
| 12 |
|
| 13 |
* :meth:`cat`: show the contents of a file |
| 14 |
* :meth:`checksum`: calculate file checksum (md5,sha256,sha1) |
| 15 |
* :meth:`cp`: local file copy (not scp) |
| 16 |
* :meth:`cwd`: change working directory |
| 17 |
* :meth:`ls`: return file/dir listing |
| 18 |
* :meth:`mkdir`: create a directory |
| 19 |
* :meth:`pwd`: get working directory |
| 20 |
* :meth:`mv`: local file rename |
| 21 |
* :meth:`rm`: local file delete |
| 22 |
* :meth:`rmdir`: remove a directory |
| 23 |
* :meth:`stat`: return file/dir information |
| 24 |
* :meth:`storage_usage`: return storage usage |
| 25 |
* :meth:`directory_usage`: return directory usage |
| 26 |
* :meth:`storage_cleanup`: perform storage storage_cleanup |
| 27 |
* :meth:`storage_cleanup_check`: returns a list of files which will be |
| 28 |
removed at cleanup |
| 29 |
* :meth:`symlink`: create a symlink |
| 30 |
* :meth:`tgz`: tar+gzip a directory |
| 31 |
|
| 32 |
.. note: The following methods require 'start shell' priveldges: |
| 33 |
|
| 34 |
* mkdir |
| 35 |
* rmdir |
| 36 |
* symlink |
| 37 |
""" |
| 38 |
|
| 39 |
# ------------------------------------------------------------------------- |
| 40 |
# cat - show file contents |
| 41 |
# ------------------------------------------------------------------------- |
| 42 |
|
| 43 |
def cat(self, path): |
| 44 |
""" |
| 45 |
Returns the contents of the file **path**. |
| 46 |
|
| 47 |
:param str path: File-path |
| 48 |
|
| 49 |
:returns: contents of the file (str) or ``None`` if file does not exist |
| 50 |
""" |
| 51 |
try: |
| 52 |
rsp = self._dev.rpc.file_show(filename=path) |
| 53 |
except: |
| 54 |
return None |
| 55 |
return rsp.text |
| 56 |
|
| 57 |
# ------------------------------------------------------------------------- |
| 58 |
# cwd - change working directory |
| 59 |
# ------------------------------------------------------------------------- |
| 60 |
|
| 61 |
def cwd(self, path): |
| 62 |
""" |
| 63 |
Change working directory to **path**. |
| 64 |
|
| 65 |
:param str path: path to working directory |
| 66 |
""" |
| 67 |
rsp = self._dev.rpc.set_cli_working_directory(directory=path) |
| 68 |
return rsp.findtext("working-directory") |
| 69 |
|
| 70 |
# ------------------------------------------------------------------------- |
| 71 |
# pwd - return current working directory |
| 72 |
# ------------------------------------------------------------------------- |
| 73 |
|
| 74 |
def pwd(self): |
| 75 |
""" |
| 76 |
:returns: The current working directory path (str) |
| 77 |
""" |
| 78 |
rsp = self._dev.rpc(E.command("show cli directory")) |
| 79 |
return rsp.findtext("./working-directory") |
| 80 |
|
| 81 |
# ------------------------------------------------------------------------- |
| 82 |
# checksum - compute file checksum |
| 83 |
# ------------------------------------------------------------------------- |
| 84 |
|
| 85 |
def checksum(self, path, calc="md5"): |
| 86 |
""" |
| 87 |
Performs the checksum command on the given file path using the |
| 88 |
required calculation method and returns the string value. |
| 89 |
If the **path** is not found on the device, then ``None`` is returned. |
| 90 |
|
| 91 |
:param str path: file-path on local device |
| 92 |
:param str calc: checksum calculation method: |
| 93 |
|
| 94 |
* "md5" |
| 95 |
* "sha256" |
| 96 |
* "sha1" |
| 97 |
|
| 98 |
:returns: checksum value (str) or ``None`` if file not found |
| 99 |
""" |
| 100 |
cmd_map = { |
| 101 |
"md5": self._dev.rpc.get_checksum_information, |
| 102 |
"sha256": self._dev.rpc.get_sha256_checksum_information, |
| 103 |
"sha1": self._dev.rpc.get_sha1_checksum_information, |
| 104 |
} |
| 105 |
rpc = cmd_map.get(calc) |
| 106 |
if rpc is None: |
| 107 |
raise ValueError("Unknown calculation method: '%s'" % calc) |
| 108 |
try: |
| 109 |
rsp = rpc(path=path) |
| 110 |
return rsp.findtext(".//checksum").strip() |
| 111 |
except: |
| 112 |
# the only exception is that the path is not found |
| 113 |
return None |
| 114 |
|
| 115 |
@classmethod |
| 116 |
def _decode_file(cls, fileinfo): |
| 117 |
results = {} |
| 118 |
|
| 119 |
not_file = fileinfo.xpath("file-directory | file-symlink-target") |
| 120 |
if len(not_file): |
| 121 |
results["type"] = {"file-directory": "dir", "file-symlink-target": "link"}[ |
| 122 |
not_file[0].tag |
| 123 |
] |
| 124 |
if "link" == results["type"]: |
| 125 |
results["link"] = not_file[0].text.strip() |
| 126 |
else: |
| 127 |
results["type"] = "file" |
| 128 |
|
| 129 |
results["path"] = fileinfo.findtext("file-name").strip() |
| 130 |
results["owner"] = fileinfo.findtext("file-owner").strip() |
| 131 |
results["size"] = int(fileinfo.findtext("file-size")) |
| 132 |
fper = fileinfo.find("file-permissions") |
| 133 |
results["permissions"] = int(fper.text.strip()) |
| 134 |
results["permissions_text"] = fper.get("format") |
| 135 |
fdate = fileinfo.find("file-date") |
| 136 |
results["ts_date"] = fdate.get("format") |
| 137 |
results["ts_epoc"] = fdate.text.strip() |
| 138 |
return results |
| 139 |
|
| 140 |
@classmethod |
| 141 |
def _decode_dir(cls, dirinfo, files=None): |
| 142 |
results = {} |
| 143 |
results["type"] = "dir" |
| 144 |
results["path"] = dirinfo.get("name") |
| 145 |
if files is None: |
| 146 |
files = dirinfo.xpath("file-information") |
| 147 |
results["file_count"] = len(files) |
| 148 |
results["size"] = sum([int(f.findtext("file-size")) for f in files]) |
| 149 |
return results |
| 150 |
|
| 151 |
# ------------------------------------------------------------------------- |
| 152 |
# stat - file information |
| 153 |
# ------------------------------------------------------------------------- |
| 154 |
|
| 155 |
def stat(self, path): |
| 156 |
""" |
| 157 |
Returns a dictionary of status information on the path, or ``None`` |
| 158 |
if the path does not exist. |
| 159 |
|
| 160 |
:param str path: file-path on local device |
| 161 |
|
| 162 |
:returns: status information on the file |
| 163 |
:rtype: dict |
| 164 |
""" |
| 165 |
rsp = self._dev.rpc.file_list(detail=True, path=path) |
| 166 |
|
| 167 |
# if there is an output tag, then it means that the path |
| 168 |
# was not found |
| 169 |
if rsp.find("output") is not None: |
| 170 |
return None |
| 171 |
|
| 172 |
# ok, so we've either got a directory or a file at |
| 173 |
# this point, so decode accordingly |
| 174 |
|
| 175 |
xdir = rsp.find("directory") |
| 176 |
if xdir.get("name"): # then this is a directory path |
| 177 |
return FS._decode_dir(xdir) |
| 178 |
else: |
| 179 |
return FS._decode_file(xdir.find("file-information")) |
| 180 |
|
| 181 |
# ------------------------------------------------------------------------- |
| 182 |
# ls - file/dir listing |
| 183 |
# ------------------------------------------------------------------------- |
| 184 |
|
| 185 |
def ls(self, path=".", brief=False, followlink=True): |
| 186 |
""" |
| 187 |
File listing, returns a dict of file information. If the |
| 188 |
path is a symlink, then by default **followlink** will |
| 189 |
recursively call this method to obtain the symlink specific |
| 190 |
information. |
| 191 |
|
| 192 |
:param str path: |
| 193 |
file-path on local device. defaults to current |
| 194 |
working directory |
| 195 |
:param bool brief: |
| 196 |
when ``True`` brief amount of data |
| 197 |
:param bool followlink: |
| 198 |
when ``True`` (default) this method will recursively |
| 199 |
follow the directory symlinks to gather data |
| 200 |
|
| 201 |
:returns: dict collection of file information or ``None`` |
| 202 |
if **path** is not found |
| 203 |
""" |
| 204 |
rsp = self._dev.rpc.file_list(detail=True, path=path) |
| 205 |
|
| 206 |
# if there is an output tag, then it means that the path |
| 207 |
# was not found, and we return :None: |
| 208 |
|
| 209 |
if rsp.find("output") is not None: |
| 210 |
return None |
| 211 |
|
| 212 |
xdir = rsp.find(".//directory") |
| 213 |
|
| 214 |
# check to see if the directory element has a :name: |
| 215 |
# attribute, and if it does not, then this is a file, and |
| 216 |
# decode accordingly. If the file is a symlink, then we |
| 217 |
# want to follow the symlink to get what we want. |
| 218 |
|
| 219 |
if not xdir.get("name"): |
| 220 |
results = FS._decode_file(xdir.find("file-information")) |
| 221 |
link_path = results.get("link") |
| 222 |
if not link_path: # then we are done |
| 223 |
return results |
| 224 |
else: |
| 225 |
return results if followlink is False else self.ls(path=link_path) |
| 226 |
|
| 227 |
# if we are here, then it's a directory, include information on all |
| 228 |
# files |
| 229 |
files = xdir.xpath("file-information") |
| 230 |
results = FS._decode_dir(xdir, files) |
| 231 |
|
| 232 |
if brief is True: |
| 233 |
results["files"] = [f.findtext("file-name").strip() for f in files] |
| 234 |
else: |
| 235 |
results["files"] = dict( |
| 236 |
(f.findtext("file-name").strip(), FS._decode_file(f)) for f in files |
| 237 |
) |
| 238 |
|
| 239 |
return results |
| 240 |
|
| 241 |
# ------------------------------------------------------------------------- |
| 242 |
# storage_usage - filesystem storage usage |
| 243 |
# ------------------------------------------------------------------------- |
| 244 |
|
| 245 |
def storage_usage(self): |
| 246 |
""" |
| 247 |
Returns the storage usage, similar to the unix "df" command. |
| 248 |
|
| 249 |
:returns: dict of storage usage |
| 250 |
""" |
| 251 |
rsp = self._dev.rpc.get_system_storage() |
| 252 |
|
| 253 |
def _name(fs): |
| 254 |
return fs.findtext("filesystem-name").strip() |
| 255 |
|
| 256 |
def _decode(fs): |
| 257 |
r = {} |
| 258 |
r["mount"] = fs.find("mounted-on").text.strip() |
| 259 |
tb = fs.find("total-blocks") |
| 260 |
r["total"] = tb.get("format") |
| 261 |
r["total_blocks"] = int(tb.text) |
| 262 |
ub = fs.find("used-blocks") |
| 263 |
r["used"] = ub.get("format") |
| 264 |
r["used_blocks"] = int(ub.text) |
| 265 |
r["used_pct"] = fs.find("used-percent").text.strip() |
| 266 |
ab = fs.find("available-blocks") |
| 267 |
r["avail"] = ab.get("format") |
| 268 |
r["avail_block"] = int(ab.text) |
| 269 |
return r |
| 270 |
|
| 271 |
re_list = rsp.xpath("multi-routing-engine-item") |
| 272 |
if re_list: |
| 273 |
fs_dict = {} |
| 274 |
for re in re_list: |
| 275 |
re_name = re.findtext("re-name").strip() |
| 276 |
re_fs_dict = dict( |
| 277 |
(_name(fs), _decode(fs)) |
| 278 |
for fs in re.xpath("system-storage-information/filesystem") |
| 279 |
) |
| 280 |
fs_dict[re_name] = re_fs_dict |
| 281 |
return fs_dict |
| 282 |
|
| 283 |
return dict((_name(fs), _decode(fs)) for fs in rsp.xpath("filesystem")) |
| 284 |
|
| 285 |
# ------------------------------------------------------------------------- |
| 286 |
# directory_usage - filesystem directory usage |
| 287 |
# ------------------------------------------------------------------------- |
| 288 |
|
| 289 |
def directory_usage(self, path=".", depth=0): |
| 290 |
""" |
| 291 |
Returns the directory usage, similar to the unix "du" command. |
| 292 |
|
| 293 |
:returns: dict of directory usage, including subdirectories |
| 294 |
if depth > 0 |
| 295 |
""" |
| 296 |
BLOCK_SIZE = 512 |
| 297 |
|
| 298 |
rsp = self._dev.rpc.get_directory_usage_information(path=path, depth=str(depth)) |
| 299 |
|
| 300 |
result = {} |
| 301 |
|
| 302 |
directories = rsp.findall(".//directory") |
| 303 |
if not directories: |
| 304 |
raise RpcError(rsp=rsp) |
| 305 |
|
| 306 |
for directory in directories: |
| 307 |
dir_name = directory.findtext("directory-name") |
| 308 |
if dir_name is not None: |
| 309 |
dir_name = dir_name.strip() |
| 310 |
else: |
| 311 |
raise RpcError(rsp=rsp) |
| 312 |
|
| 313 |
used_space = directory.find("used-space") |
| 314 |
if used_space is not None: |
| 315 |
dir_size = used_space.text.strip() |
| 316 |
dir_blocks = used_space.get("used-blocks") |
| 317 |
if dir_blocks is not None: |
| 318 |
dir_blocks = int(dir_blocks) |
| 319 |
dir_bytes = dir_blocks * BLOCK_SIZE |
| 320 |
result[dir_name.strip()] = { |
| 321 |
"size": dir_size, |
| 322 |
"blocks": dir_blocks, |
| 323 |
"bytes": dir_bytes, |
| 324 |
} |
| 325 |
|
| 326 |
return result |
| 327 |
|
| 328 |
# ------------------------------------------------------------------------- |
| 329 |
# storage_cleanup_check, storage_cleanip |
| 330 |
# ------------------------------------------------------------------------- |
| 331 |
|
| 332 |
@classmethod |
| 333 |
def _decode_storage_cleanup(cls, files): |
| 334 |
def _name(f): |
| 335 |
return f.findtext("file-name").strip() |
| 336 |
|
| 337 |
def _decode(f): |
| 338 |
return { |
| 339 |
"size": int(f.findtext("size")), |
| 340 |
"ts_date": f.findtext("date").strip(), |
| 341 |
} |
| 342 |
|
| 343 |
# return a dict of name/decode pairs for each file |
| 344 |
return dict((_name(f), _decode(f)) for f in files) |
| 345 |
|
| 346 |
def storage_cleanup_check(self): |
| 347 |
""" |
| 348 |
Perform the 'request system storage cleanup dry-run' command |
| 349 |
to return a ``dict`` of files/info that would be removed if |
| 350 |
the cleanup command was executed. |
| 351 |
|
| 352 |
:returns: dict of files that would be removed (dry-run) |
| 353 |
""" |
| 354 |
rsp = self._dev.rpc.request_system_storage_cleanup(dry_run=True) |
| 355 |
files = rsp.xpath("file-list/file") |
| 356 |
return FS._decode_storage_cleanup(files) |
| 357 |
|
| 358 |
def storage_cleanup(self): |
| 359 |
""" |
| 360 |
Perform the 'request system storage cleanup' command to remove |
| 361 |
files from the filesystem. Return a ``dict`` of file name/info |
| 362 |
on the files that were removed. |
| 363 |
|
| 364 |
:returns: dict on files that were removed |
| 365 |
""" |
| 366 |
rsp = self._dev.rpc.request_system_storage_cleanup() |
| 367 |
files = rsp.xpath("file-list/file") |
| 368 |
return FS._decode_storage_cleanup(files) |
| 369 |
|
| 370 |
# ------------------------------------------------------------------------- |
| 371 |
# rm - local file delete |
| 372 |
# ------------------------------------------------------------------------- |
| 373 |
|
| 374 |
def rm(self, path): |
| 375 |
""" |
| 376 |
Performs a local file delete action, per Junos CLI command |
| 377 |
"file delete". |
| 378 |
|
| 379 |
:returns: ``True`` when successful, ``False`` otherwise. |
| 380 |
""" |
| 381 |
# the return value from this RPC will return either True if the delete |
| 382 |
# was successful, or an XML structure otherwise. So we can do a simple |
| 383 |
# test to provide the return result to the caller. |
| 384 |
rsp = self._dev.rpc.file_delete(path=path) |
| 385 |
if rsp is True: |
| 386 |
return True |
| 387 |
else: |
| 388 |
return False |
| 389 |
|
| 390 |
# ------------------------------------------------------------------------- |
| 391 |
# cp - local file copy |
| 392 |
# ------------------------------------------------------------------------- |
| 393 |
|
| 394 |
def cp(self, from_path, to_path, routing_instance=None, **kvargs): |
| 395 |
""" |
| 396 |
Perform a local file copy where **from_path** and **to_path** can be |
| 397 |
any valid Junos path argument. Refer to the Junos "file copy" command |
| 398 |
documentation for details. |
| 399 |
|
| 400 |
:param str from_path: source file-path |
| 401 |
:param str to_path: destination file-path |
| 402 |
:param str routing_instance: (optional) routing_instance name |
| 403 |
:param dict kvargs: Any additional parameters to the 'file copy' command can |
| 404 |
be passed within **kvargs**, following the RPC syntax |
| 405 |
methodology (dash-2-underscore,etc.) |
| 406 |
|
| 407 |
.. notes: Valid Junos file-path can include URL, such as ``http://``. |
| 408 |
this is handy for copying files for webservers. |
| 409 |
|
| 410 |
:returns: ``True`` if OK, ``False`` if file does not exist. |
| 411 |
""" |
| 412 |
# this RPC returns True if it is OK. If the file does not exist |
| 413 |
# this RPC will generate an RpcError exception, so just return False |
| 414 |
try: |
| 415 |
if routing_instance is None: |
| 416 |
self._dev.rpc.file_copy(source=from_path, destination=to_path, **kvargs) |
| 417 |
else: |
| 418 |
self._dev.rpc.file_copy( |
| 419 |
source=from_path, |
| 420 |
destination=to_path, |
| 421 |
routing_instance=routing_instance, |
| 422 |
**kvargs |
| 423 |
) |
| 424 |
except: |
| 425 |
return False |
| 426 |
return True |
| 427 |
|
| 428 |
# ------------------------------------------------------------------------- |
| 429 |
# mv - local file rename |
| 430 |
# ------------------------------------------------------------------------- |
| 431 |
|
| 432 |
def mv(self, from_path, to_path): |
| 433 |
""" |
| 434 |
Perform a local file rename function, same as "file rename" Junos CLI. |
| 435 |
|
| 436 |
:returns: ``True`` if OK, ``False`` if file does not exist. |
| 437 |
""" |
| 438 |
rsp = self._dev.rpc.file_rename(source=from_path, destination=to_path) |
| 439 |
if rsp is True: |
| 440 |
return True |
| 441 |
else: |
| 442 |
return False |
| 443 |
|
| 444 |
def tgz(self, from_path, tgz_path): |
| 445 |
""" |
| 446 |
Create a file called **tgz_path** that is the tar-gzip of the given |
| 447 |
directory specified **from_path**. |
| 448 |
|
| 449 |
:param str from_path: file-path to directory of files |
| 450 |
:param str tgz_path: file-path name of tgz file to create |
| 451 |
|
| 452 |
:returns: ``True`` if OK, error-msg (str) otherwise |
| 453 |
""" |
| 454 |
rsp = self._dev.rpc.file_archive( |
| 455 |
compress=True, source=from_path, destination=tgz_path |
| 456 |
) |
| 457 |
|
| 458 |
# if the rsp is True, then the command executed OK. |
| 459 |
if rsp is True: |
| 460 |
return True |
| 461 |
|
| 462 |
# otherwise, return the error string to the caller |
| 463 |
return rsp.text |
| 464 |
|
| 465 |
# ------------------------------------------------------------------------- |
| 466 |
# !!!!! methods that use SSH shell commands, require that the user |
| 467 |
# !!!!! has 'start shell' privileges |
| 468 |
# ------------------------------------------------------------------------- |
| 469 |
|
| 470 |
def _ssh_exec(self, command): |
| 471 |
with StartShell(self._dev) as sh: |
| 472 |
got = sh.run(command) |
| 473 |
return got |
| 474 |
|
| 475 |
def rmdir(self, path): |
| 476 |
""" |
| 477 |
Executes the 'rmdir' command on **path**. |
| 478 |
|
| 479 |
.. warning:: REQUIRES SHELL PRIVILEGES |
| 480 |
|
| 481 |
:param str path: file-path to directory |
| 482 |
|
| 483 |
:returns: ``True`` if OK, error-message (str) otherwise |
| 484 |
""" |
| 485 |
results = self._ssh_exec("rmdir %s" % path) |
| 486 |
return True if results[0] is True else "".join(results[1][2:-1]) |
| 487 |
|
| 488 |
def mkdir(self, path): |
| 489 |
""" |
| 490 |
Executes the 'mkdir -p' command on **path**. |
| 491 |
|
| 492 |
.. warning:: REQUIRES SHELL PRIVILEGES |
| 493 |
|
| 494 |
:returns: ``True`` if OK, error-message (str) otherwise |
| 495 |
""" |
| 496 |
results = self._ssh_exec("mkdir -p %s" % path) |
| 497 |
return True if results[0] is True else "".join(results[1][2:-1]) |
| 498 |
|
| 499 |
def symlink(self, from_path, to_path): |
| 500 |
""" |
| 501 |
Executes the 'ln -sf **from_path** **to_path**' command. |
| 502 |
|
| 503 |
.. warning:: REQUIRES SHELL PRIVILEGES |
| 504 |
|
| 505 |
:returns: ``True`` if OK, or error-message (str) otherwise |
| 506 |
""" |
| 507 |
results = self._ssh_exec("ln -sf %s %s" % (from_path, to_path)) |
| 508 |
return True if results[0] is True else "".join(results[1][2:-1]) |