Connection abstact abstract classes API
This file describes abstract classes defining the package API.
ssh_utilities.abstract
Template module for all connection classes.
-
class
ssh_utilities.abstract.
ConnectionABC
Bases:
abc.ABC
Class defining API for connection classes.
-
static
_path2str
(path: Optional[_SPATH]) → str Converts pathlib.Path, SSHPath or plain str to string.
Also remove any rtailing backslashes.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to convert to string, if string is passed, then just returns itRaises: FileNotFoundError
– if path is not instance of str, Path or SSHPath
-
_to_str
(connection_name: str, host_name: str, address: Optional[str], user_name: str, ssh_key: Union[pathlib.Path, str, None], thread_safe: bool) → str Aims to ease persistance, returns string representation of instance.
With this method all data needed to initialize class are saved to sting and connection can be reinitialized with from_str method of conection.Connection class.
Parameters: - connection_name (str) – SSHConnection or LocalConnection
- host_name (str) – name of remote server
- address (str) – server address in case of remote connection
- user_name (str) – server login name
- ssh_key (Optional[Union[Path, str]]) – file with public key, pass none for LocalConnection
- thread_safe (bool) – make connection object thread safe so it can be safely accessed from any number of threads, it is disabled by default to avoid performance penalty of threading locks
Returns: string representation of the class
Return type: str
See also
ssh_utilities.conncection.Connection
-
static
-
class
ssh_utilities.abstract.
OsPathABC
Bases:
abc.ABC
os.path module drop-in replacement base.
-
exists
(path: _SPATH) → bool Check if path exists in filesystem.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool
-
getsize
(path: _SPATH) → int Return the size of path in bytes.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to file/directoryReturns: size in bytes Return type: int Raises: OsError
– if the file does not exist or is inaccessible
-
isdir
(path: _SPATH) → bool Check if path points to directory.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if dir could not be accessed
-
isfile
(path: _SPATH) → bool Check if path points to a file.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if file could not be accessed
-
islink
(path: _SPATH) → bool Check if path points to symbolic link.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if dir could not be accessed
-
join
(path: _SPATH, *paths) → str Join one or more path components intelligently.
The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. On Windows, the drive letter is not reset when an absolute path component (e.g., ‘foo’) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join(“c:”, “foo”) represents a path relative to the current directory on drive C: (c:foo), not c:/foo.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – the starting path part - *paths (
ssh_utilities.typeshed._SPATH
) – path parts to join to the first one
Returns: joined path parts
Return type: str
- path (
-
realpath
(path: _SPATH) → str Return the canonical path of the specified filename.
Eliminates any symbolic links encountered in the path.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to resolveReturns: string representation of the resolved path Return type: str
-
-
class
ssh_utilities.abstract.
BuiltinsABC
Bases:
abc.ABC
,typing.Generic
Python builtins drop-in replacement base.
-
open
(filename: _SPATH, mode: str = 'r', buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None) → _Builtins1 Opens remote file, works as python open function.
Can be used both as a function or a decorator.
Parameters: - filename (
ssh_utilities.typeshed._SPATH
) – path to file to be opened - mode (str) – select mode to open file. Same as python open modes
- encoding (Optional[str]) – encoding type to decode file bytes stream
- buffering (int) – buffer size, 0 turns off buffering, 1 uses line buffering, and any number greater than 1 (>1) uses that specific buffer size
- errors (Optional[str]) – string that specifies how encoding and decoding errors are to be handled, see builtin function open documentation for more details
- newline (Optional[str]) – this parameter is not used in ssh implementation
Raises: FileNotFoundError
– when mode is ‘r’ and file does not exist- filename (
-
-
class
ssh_utilities.abstract.
OsABC
Bases:
abc.ABC
,typing.Generic
os module drop-in replacement base.
-
chmod
(path: _SPATH, mode: int, *, dir_fd: Optional[int] = None, follow_symlinks: bool = True) Change the mode of path to the numeric mode.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path pointing to the file/directory - mode (int) – desired mode to set, check python os documentation to see options
- dir_fd (Optional[int], optional) – not used by ssh implementation, by default None
- follow_symlinks (bool, optional) – whether to resolve symlinks on the way, by default True
Raises: FileNotFoundError
– if the path does not exist- path (
-
lchmod
(path: _SPATH, mode: int) Change the mode of path to the numeric mode.
If path is a symlink, this affects the symlink rather than the target.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path pointing to the file/directory - mode (int) – desired mode to set, check python os documentation to see options
Raises: FileNotFoundError
– if the path does not exist- path (
-
listdir
(path: _SPATH) → _Os2 Lists contents of specified directory.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – directory pathReturns: list of files, dirs, symlinks … Return type: List[str] Raises: FileNotFoundError
– if directory does not exist
-
lstat
(path: _SPATH, *, dir_fd=None) → _Os3 Similar to stat only this does not resolve symlinks.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to file whose stats are desired - dir_fd (Any) – not implemented in remote version
Returns: stat object similar to one returned by os.lstat
Return type: SFTPAttributes
Warning
dir_fd parameter has no effect, it is present only so the signature is compatible with os.lstat
- path (
-
makedirs
(path: _SPATH, mode: int = 511, exist_ok: bool = True, parents: bool = True, quiet: bool = True) Recursively create directory.
If it already exists, show warning and return.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be created - mode (int) – create directory with mode, default is 511
- exist_ok (bool) – if true and directory exists, exception is silently passed when dir already exists
- parents (bool) – if true any missing parent dirs are automatically created, else exception is raised on missing parent
- quiet (bool) – if True informative messages are suppresssed
Raises: OSError
– if directory could not be createdFileNotFoundError
– when parent directory is missing and parents=FalseFileExistsError
– when directory already exists and exist_ok=False
- path (
-
mkdir
(path: _SPATH, mode: int = 511, quiet: bool = True) Create single directory.
If it already exists, show warning and return.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be created - mode (int) – create directory with mode, default is 511
- quiet (bool) – if True informative messages are suppresssed
Raises: OSError
– if directory could not be createdFileNotFoundError
– when parent directory is missing and parents=FalseFileExistsError
– when directory already exists and exist_ok=False
- path (
-
name
Try to get remote os name same as os.name function.
Warning
Due to the complexity of the check, this method only checks is remote server is windows by trying to run ver command. If that fails the remote is automatically assumed to be POSIX which should hold true in most cases. If absolute certianty is required you should do your own checks.
Note
This methods main purpose is to help choose the right flavour when instantiating ssh_utilities.path.SSHPath. For its use the provided accuracy should be sufficient.
Returns: remote server os name Return type: Literal[“nt”, “posix”] Raises: UnknownOsError
– if remote server os name could not be determined
-
remove
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove file.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a fileIsADirectoryError
– if path points to a directoryIOError
– if some other paramiko related error happens and file could not have been removed.
- path (
-
rename
(src: _SPATH, dst: _SPATH, *, src_dir_fd: Optional[int] = None, dst_dir_fd: Optional[int] = None) Rename the file or directory src to dst.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – source file or directory - dst (
ssh_utilities.typeshed._SPATH
) – destination file or directory - src_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
- dst_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: OsError
– If dst exists, the operation will fail with an OSError,- src (
-
replace
(src: _SPATH, dst: _SPATH, *, src_dir_fd: Optional[int] = None, dst_dir_fd: Optional[int] = None) Rename the file or directory src to dst.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – source file or directory - dst (
ssh_utilities.typeshed._SPATH
) – destination file or directory - src_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
- dst_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: OsError
– If dst is a directory, the operation will fail with an OSError,Warning
If dst exists and is a file, it will be replaced silently if the user has permission.
- src (
-
rmdir
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove directory.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a directoryOSError
– if directory is not empty or some other ssh implementation related error occured
- path (
-
scandir
(path: _SPATH) → _Os1 Return an iterator of os.DirEntry objects.
These correspond to the entries in the directory given by path.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – root path directory to scanReturns: scandir iterator. Return type: ssh_utilities.abstract._SCANDIR
-
stat
(path: _SPATH, *, dir_fd=None, follow_symlinks: bool = True) → _Os3 Replacement for os.stat function.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to file whose stats are desired - dir_fd (Any) – not implemented
- follow_symlinks (bool) – whether to resolve symbolic links along the way
Returns: stat object similar to one returned by os.stat
Return type: SFTPAttributes
Warning
dir_fd parameter has no effect, it is present only so the signature is compatible with os.stat
- path (
-
symlink
(src: _SPATH, dst: _SPATH, target_is_directory: bool = False, *, dir_fd: Optional[int] = None) Make this path a symlink pointing to the given path.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – target path to which symlink will point - dst (
ssh_utilities.typeshed._SPATH
) – symlink path - target_is_directory (bool, optional) – this parameter is ignored in ssh implementation
- dir_fd (Optional[int], optional) – this parameter is ignored in ssh implementation
Warning
target_is_directory parameter is ignored
- src (
-
unlink
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove file.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a fileIsADirectoryError
– if path points to a directoryIOError
– if some other paramiko related error happens and file could not have been removed.
- path (
-
walk
(top: _SPATH, topdown: bool = True, onerror: _ONERROR = None, followlinks: bool = False) → _Os6 Recursive directory listing.
Parameters: - top (
ssh_utilities.typeshed._SPATH
) – directory to start from - topdown (bool, optional) – if true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). This enables you to modify the subdirectories list in place befor iteration continues. If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories, by default True
- onerror (
ssh_utilities.typeshed._ONERROR
, optional) – Callable acception one argument of type exception which decides how to handle that exception, by default None - followlinks (bool, optional) – follow symbolic links if true, by default False
Returns: iterator of 3 tuples containing current dir, subdirs and files
Return type: - top (
-
-
class
ssh_utilities.abstract.
ShutilABC
Bases:
abc.ABC
shutil module drop-in replacement base.
-
copy
(src: _SPATH, dst: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, callback: _CALLBACK = None, quiet: bool = True) Send files in the chosen direction local <-> remote.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – path to the file - dst (
ssh_utilities.typeshed._SPATH
) – path to copy into - direction (
ssh_utilities.typeshed._DIRECTION
) – ‘get’ for download and ‘put’ for upload - follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- callback (
ssh_utilities.typeshed._CALLBACK
) – callback function that recives two arguments: amount done and total amount to be copied - quiet (bool) – if True informative messages are suppresssed
Warning
Unlike shutil this function cannot preserve file permissions (copy) or file metadata (copy2)
Raises: FileNotFoundError
– if src is not fileValueError
– if direction is not put or get
- src (
-
copy_files
(files: List[str], remote_path: _SPATH, local_path: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, quiet: bool = False) Send files in the chosen direction local <-> remote.
Parameters: - files (List[str]) – list of files to upload/download
- remote_path (
ssh_utilities.typeshed._SPATH
) – path to remote directory with files - local_path (
ssh_utilities.typeshed._SPATH
) – path to local directory with files - direction (str) – get for download and put for upload
- follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- quiet (bool) – if True informative messages are suppresssed
-
copyfile
(src: _SPATH, dst: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, callback: _CALLBACK = None, quiet: bool = True) Send files in the chosen direction local <-> remote.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – path to the file - dst (
ssh_utilities.typeshed._SPATH
) – path to copy into - direction (
ssh_utilities.typeshed._DIRECTION
) – ‘get’ for download and ‘put’ for upload - follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- callback (
ssh_utilities.typeshed._CALLBACK
) – callback function that recives two arguments: amount done and total amount to be copied - quiet (bool) – if True informative messages are suppresssed
Raises: FileNotFoundError
– if src is not fileIsADirectoryError
– if dst is a targer directory not full pathValueError
– if direction is not put or get
- src (
-
copyfileobj
(fsrc: Union[IO, SFTPFile], fdst: Union[IO, SFTPFile], *, direction: _DIRECTION, length: Optional[int] = None) Copy the contents of one file-like object to another.
Parameters: - fsrc (Union[IO, SFTPFile]) – source file-like object must be local/remote based on direction parameter
- fdst (Union[IO, SFTPFile]) – source file-like object must be local/remote based on direction parameter
- direction (_DIRECTION) – either ‘put’ or ‘get’
- length (int, optional) – [description], by default -1
-
download_tree
(remote_path: _SPATH, local_path: _SPATH, include: _GLOBPAT = None, exclude: _GLOBPAT = None, remove_after: bool = True, quiet: bool = False) Download directory tree from remote.
Remote directory must exist otherwise exception is raised.
Parameters: - remote_path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be downloaded - local_path (
ssh_utilities.typeshed._SPATH
) – directory to copy to, must be full path! - remove_after (bool) – remove remote copy after directory is uploaded
- include (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to include in copy, can be used simultaneously with exclude, default is None = no filtering - exclude (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to exclude in copy, can be used simultaneously with include, default is None = no filtering - quiet (Literal[True, False, "stats", "progress"]) – if True informative messages are suppresssed if False all is printed, if stats all statistics except progressbar are suppressed if progress only progressbar is suppressed
Warning
both paths must be full: <some_remote_path>/my_directory -> <some_local_path>/my_directory
Raises: FileNotFoundError
– when remote directory does not exist- remote_path (
-
ignore_patterns
(*paterns) → Callable[[Any, Sequence[str]], Set[str]] Creates a callable for shutil.copytree function to ignore files.
Parameters: *patterns (Sequence[str]) – a list of glob patterns that will ne used to exclude files Returns: Callable the filters files, when called with a list of strings returns a subset that matches one oth the exclude patterns Return type: Callable[[Any, Sequence[str]], Set[str]]
-
rmtree
(path: _SPATH, ignore_errors: bool = False, quiet: bool = True) Recursively remove directory tree.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – directory to be recursively removed - ignore_errors (bool) – if True only log warnings do not raise exception
- quiet (bool) – if True informative messages are suppresssed
Raises: FileNotFoundError
– if some part of deleting filed- path (
-
upload_tree
(local_path: _SPATH, remote_path: _SPATH, include: _GLOBPAT = None, exclude: _GLOBPAT = None, remove_after: bool = True, quiet: bool = False) Upload directory tree to remote.
Local path must exist otherwise, exception is raised.
Parameters: - local_path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be uploaded - remote_path (
ssh_utilities.typeshed._SPATH
) – directory to copy to, must be full path! - remove_after (bool) – remove local copy after directory is uploaded
- include (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to include in copy, can be used simultaneously with exclude, default is None = no filtering - exclude (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to exclude in copy, can be used simultaneously with include, default is None = no filtering - quiet (Literal[True, False, "stats", "progress"]) – if True informative messages are suppresssed if False all is printed, if stats all statistics except progressbar are suppressed if progress only progressbar is suppressed
Warning
both paths must be full: <some_local_path>/my_directory -> <some_remote_path>/my_directory
Raises: FileNotFoundError
– when local directory does not exist- local_path (
-
-
class
ssh_utilities.abstract.
SubprocessABC
Bases:
abc.ABC
,typing.Generic
subprocess module drop-in replacement base.
-
run
(args: _CMD, *, suppress_out: bool, quiet: bool = True, bufsize: int = -1, executable: _SPATH = None, input: Optional[str] = None, stdin: _FILE = None, stdout: _FILE = None, stderr: _FILE = None, capture_output: bool = False, shell: bool = False, cwd: _SPATH = None, timeout: Optional[float] = None, check: bool = False, encoding: Optional[str] = None, errors: Optional[str] = None, text: Optional[bool] = None, env: _ENV = None, universal_newlines: bool = False) → _Subprocess1 Excecute command on remote, has simillar API to subprocess run.
Parameters: - args (
ssh_utilities.typeshed._CMD
) – string, Path-like object or a list of strings. If it is a list it will be joined to string with whitespace delimiter. - suppress_out (bool) – whether to print command output to console, this is required keyword argument
- quiet (bool, optional) – whether to print other function messages, by default True
- bufsize (int, optional) – buffer size, 0 turns off buffering, 1 uses line buffering, and any number greater than 1 (>1) uses that specific buffer size. This applies ti underlying paramiko client as well as stdin, stdout and stderr PIPES, by default -1
- executable (
ssh_utilities.typeshed._SPATH
, optional) – [description], by default None - input (Optional[str], optional) – [description], by default None
- stdin (_FILE, optional) – [description], by default None
- stdout (_FILE, optional) – [description], by default None
- stderr (_FILE, optional) – [description], by default None
- capture_output (bool, optional) – if true then lightweight result object with same API as subprocess.CompletedProcess is returned. Same as passing PIPE to stdout and stderr. Both options cannot be used at the same time, by default False
- shell (bool, optional) – requests a pseudo terminal from server, by default False
- cwd (_SPATH, optional) – execute command in this directory, by default None
- timeout (Optional[float], optional) – set, by default None
- check (bool, optional) – checks for command return code if other than 0 raises CalledProcessError, by default False
- encoding (Optional[str], optional) – encoding to use when decoding remote output, default is utf-8, by default None
- errors (Optional[str], optional) –
string that specifies how encoding and decoding errors are to be handled, see builtin function open documentation for more details, by default None
- text (Optional[bool], optional) – will select default encoding and open stdin, stdout and stderr streams in text mode. The default encoding, contrary to behaviour of subprocess module is not selected by locale.getpreferredencoding(False) but is always set to utf-8. By default None
- env (
ssh_utilities.typeshed._ENV
, optional) – optinal environment variables that will be merged into the existing environment. This is different to subprocess behaviour which creates new environment with only specified variables, by default None - universal_newlines (bool, optional) – an alias for text keyword argument, by default None
Warning
New environment variables defined by env might get silently rejected by the server.
Currentlly it is only possible to use input agrgument, not stdin and send data to process only once at the begining. It is still under developement
Returns: if capture_output is true, returns lightweight result object with same API as subprocess.CompletedProcess
Return type: Raises: ValueError
– if stdin and input are specified at the same timeValueError
– if capture_output and stdout and/or stderr are specified at the same timeValueError
– if text or universal_newlines is used simultaneously with” encoding and/or errors argumentsNotImplementedError
– if stdin or executable is used - work in progressTypeError
– if stdin, stdout or stderr arguments are of wrong typeTypeError
– if args argument is of wrong typeCalledProcessError
– if check is true and command exited with non-zero statusTimeoutExpired
– if the command exceeded allowed run time
- args (
-
-
class
ssh_utilities.abstract.
PathlibABC
Bases:
abc.ABC
,typing.Generic
pathlib module drop-in replacement base.
-
Path
(path: _SPATH) → _Pathlib1 Provides API similar to pathlib.Path only for remote host.
Only for Unix to Unix connections
Parameters: path ( ssh_utilities.typeshed._SPATH
) – provide initial pathReturns: object representing remote path Return type: SSHPath
-
-
class
ssh_utilities.abstract.
DirEntryABC
Bases:
abc.ABC
Object representation of directory or a file yielded by scandir().
Has subset of Path object methods.
-
inode
() → int Return the inode number of the entry.
Returns: inode number Return type: int
-
is_dir
(*, follow_symlinks: bool = True) → bool Return True if this entry is a directory.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: True if path points to a directory. Return type: bool Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
is_file
(*, follow_symlinks: bool = True) → bool Return True if this entry is a file.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: True if path points to a file. Return type: bool Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
is_symlink
() → bool Return True if this entry is a symlink.
Returns: true if targer is symlink Return type: bool
-
stat
(*, follow_symlinks: bool = True) → _ATTRIBUTES Return SFTPAttributes object similar to os.stat.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: attributes object for the entry. Return type: SFTPAttributes Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
ssh_utilities.abstract._connection
Template module for all connections classes.
-
class
ssh_utilities.abstract._connection.
ConnectionABC
Bases:
abc.ABC
Class defining API for connection classes.
-
static
_path2str
(path: Optional[_SPATH]) → str Converts pathlib.Path, SSHPath or plain str to string.
Also remove any rtailing backslashes.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to convert to string, if string is passed, then just returns itRaises: FileNotFoundError
– if path is not instance of str, Path or SSHPath
-
_to_str
(connection_name: str, host_name: str, address: Optional[str], user_name: str, ssh_key: Union[pathlib.Path, str, None], thread_safe: bool) → str Aims to ease persistance, returns string representation of instance.
With this method all data needed to initialize class are saved to sting and connection can be reinitialized with from_str method of conection.Connection class.
Parameters: - connection_name (str) – SSHConnection or LocalConnection
- host_name (str) – name of remote server
- address (str) – server address in case of remote connection
- user_name (str) – server login name
- ssh_key (Optional[Union[Path, str]]) – file with public key, pass none for LocalConnection
- thread_safe (bool) – make connection object thread safe so it can be safely accessed from any number of threads, it is disabled by default to avoid performance penalty of threading locks
Returns: string representation of the class
Return type: str
See also
ssh_utilities.conncection.Connection
-
static
ssh_utilities.abstract._builtins
Template module for all builtins classes.
-
class
ssh_utilities.abstract._builtins.
BuiltinsABC
Bases:
abc.ABC
,typing.Generic
Python builtins drop-in replacement base.
-
open
(filename: _SPATH, mode: str = 'r', buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None) → _Builtins1 Opens remote file, works as python open function.
Can be used both as a function or a decorator.
Parameters: - filename (
ssh_utilities.typeshed._SPATH
) – path to file to be opened - mode (str) – select mode to open file. Same as python open modes
- encoding (Optional[str]) – encoding type to decode file bytes stream
- buffering (int) – buffer size, 0 turns off buffering, 1 uses line buffering, and any number greater than 1 (>1) uses that specific buffer size
- errors (Optional[str]) –
string that specifies how encoding and decoding errors are to be handled, see builtin function open documentation for more details
- newline (Optional[str]) – this parameter is not used in ssh implementation
Raises: FileNotFoundError
– when mode is ‘r’ and file does not exist- filename (
-
ssh_utilities.abstract._os
Template module for all os classes.
-
class
ssh_utilities.abstract._os.
OsPathABC
Bases:
abc.ABC
os.path module drop-in replacement base.
-
exists
(path: _SPATH) → bool Check if path exists in filesystem.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool
-
getsize
(path: _SPATH) → int Return the size of path in bytes.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to file/directoryReturns: size in bytes Return type: int Raises: OsError
– if the file does not exist or is inaccessible
-
isdir
(path: _SPATH) → bool Check if path points to directory.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if dir could not be accessed
-
isfile
(path: _SPATH) → bool Check if path points to a file.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if file could not be accessed
-
islink
(path: _SPATH) → bool Check if path points to symbolic link.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to checkReturns: check result Return type: bool Raises: IOError
– if dir could not be accessed
-
join
(path: _SPATH, *paths) → str Join one or more path components intelligently.
The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. On Windows, the drive letter is not reset when an absolute path component (e.g., ‘foo’) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join(“c:”, “foo”) represents a path relative to the current directory on drive C: (c:foo), not c:/foo.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – the starting path part - *paths (
ssh_utilities.typeshed._SPATH
) – path parts to join to the first one
Returns: joined path parts
Return type: str
- path (
-
realpath
(path: _SPATH) → str Return the canonical path of the specified filename.
Eliminates any symbolic links encountered in the path.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – path to resolveReturns: string representation of the resolved path Return type: str
-
-
class
ssh_utilities.abstract._os.
OsABC
Bases:
abc.ABC
,typing.Generic
os module drop-in replacement base.
-
chmod
(path: _SPATH, mode: int, *, dir_fd: Optional[int] = None, follow_symlinks: bool = True) Change the mode of path to the numeric mode.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path pointing to the file/directory - mode (int) – desired mode to set, check python os documentation to see options
- dir_fd (Optional[int], optional) – not used by ssh implementation, by default None
- follow_symlinks (bool, optional) – whether to resolve symlinks on the way, by default True
Raises: FileNotFoundError
– if the path does not exist- path (
-
lchmod
(path: _SPATH, mode: int) Change the mode of path to the numeric mode.
If path is a symlink, this affects the symlink rather than the target.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path pointing to the file/directory - mode (int) – desired mode to set, check python os documentation to see options
Raises: FileNotFoundError
– if the path does not exist- path (
-
listdir
(path: _SPATH) → _Os2 Lists contents of specified directory.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – directory pathReturns: list of files, dirs, symlinks … Return type: List[str] Raises: FileNotFoundError
– if directory does not exist
-
lstat
(path: _SPATH, *, dir_fd=None) → _Os3 Similar to stat only this does not resolve symlinks.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to file whose stats are desired - dir_fd (Any) – not implemented in remote version
Returns: stat object similar to one returned by os.lstat
Return type: SFTPAttributes
Warning
dir_fd parameter has no effect, it is present only so the signature is compatible with os.lstat
- path (
-
makedirs
(path: _SPATH, mode: int = 511, exist_ok: bool = True, parents: bool = True, quiet: bool = True) Recursively create directory.
If it already exists, show warning and return.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be created - mode (int) – create directory with mode, default is 511
- exist_ok (bool) – if true and directory exists, exception is silently passed when dir already exists
- parents (bool) – if true any missing parent dirs are automatically created, else exception is raised on missing parent
- quiet (bool) – if True informative messages are suppresssed
Raises: OSError
– if directory could not be createdFileNotFoundError
– when parent directory is missing and parents=FalseFileExistsError
– when directory already exists and exist_ok=False
- path (
-
mkdir
(path: _SPATH, mode: int = 511, quiet: bool = True) Create single directory.
If it already exists, show warning and return.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be created - mode (int) – create directory with mode, default is 511
- quiet (bool) – if True informative messages are suppresssed
Raises: OSError
– if directory could not be createdFileNotFoundError
– when parent directory is missing and parents=FalseFileExistsError
– when directory already exists and exist_ok=False
- path (
-
name
Try to get remote os name same as os.name function.
Warning
Due to the complexity of the check, this method only checks is remote server is windows by trying to run ver command. If that fails the remote is automatically assumed to be POSIX which should hold true in most cases. If absolute certianty is required you should do your own checks.
Note
This methods main purpose is to help choose the right flavour when instantiating ssh_utilities.path.SSHPath. For its use the provided accuracy should be sufficient.
Returns: remote server os name Return type: Literal[“nt”, “posix”] Raises: UnknownOsError
– if remote server os name could not be determined
-
remove
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove file.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a fileIsADirectoryError
– if path points to a directoryIOError
– if some other paramiko related error happens and file could not have been removed.
- path (
-
rename
(src: _SPATH, dst: _SPATH, *, src_dir_fd: Optional[int] = None, dst_dir_fd: Optional[int] = None) Rename the file or directory src to dst.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – source file or directory - dst (
ssh_utilities.typeshed._SPATH
) – destination file or directory - src_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
- dst_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: OsError
– If dst exists, the operation will fail with an OSError,- src (
-
replace
(src: _SPATH, dst: _SPATH, *, src_dir_fd: Optional[int] = None, dst_dir_fd: Optional[int] = None) Rename the file or directory src to dst.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – source file or directory - dst (
ssh_utilities.typeshed._SPATH
) – destination file or directory - src_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
- dst_dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: OsError
– If dst is a directory, the operation will fail with an OSError,Warning
If dst exists and is a file, it will be replaced silently if the user has permission.
- src (
-
rmdir
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove directory.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a directoryOSError
– if directory is not empty or some other ssh implementation related error occured
- path (
-
scandir
(path: _SPATH) → _Os1 Return an iterator of os.DirEntry objects.
These correspond to the entries in the directory given by path.
Parameters: path ( ssh_utilities.typeshed._SPATH
) – root path directory to scanReturns: scandir iterator. Return type: ssh_utilities.abstract._SCANDIR
-
stat
(path: _SPATH, *, dir_fd=None, follow_symlinks: bool = True) → _Os3 Replacement for os.stat function.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to file whose stats are desired - dir_fd (Any) – not implemented
- follow_symlinks (bool) – whether to resolve symbolic links along the way
Returns: stat object similar to one returned by os.stat
Return type: SFTPAttributes
Warning
dir_fd parameter has no effect, it is present only so the signature is compatible with os.stat
- path (
-
symlink
(src: _SPATH, dst: _SPATH, target_is_directory: bool = False, *, dir_fd: Optional[int] = None) Make this path a symlink pointing to the given path.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – target path to which symlink will point - dst (
ssh_utilities.typeshed._SPATH
) – symlink path - target_is_directory (bool, optional) – this parameter is ignored in ssh implementation
- dir_fd (Optional[int], optional) – this parameter is ignored in ssh implementation
Warning
target_is_directory parameter is ignored
- src (
-
unlink
(path: _SPATH, *, dir_fd: Optional[int] = None) Remove file.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – path to remove - dir_fd (Optional[int], optional) – file descriptor, not used in ssh implementation, by default None
Raises: FileNotFoundError
– if path does not point to a fileIsADirectoryError
– if path points to a directoryIOError
– if some other paramiko related error happens and file could not have been removed.
- path (
-
walk
(top: _SPATH, topdown: bool = True, onerror: _ONERROR = None, followlinks: bool = False) → _Os6 Recursive directory listing.
Parameters: - top (
ssh_utilities.typeshed._SPATH
) – directory to start from - topdown (bool, optional) – if true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). This enables you to modify the subdirectories list in place befor iteration continues. If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories, by default True
- onerror (
ssh_utilities.typeshed._ONERROR
, optional) – Callable acception one argument of type exception which decides how to handle that exception, by default None - followlinks (bool, optional) – follow symbolic links if true, by default False
Returns: iterator of 3 tuples containing current dir, subdirs and files
Return type: - top (
-
-
class
ssh_utilities.abstract._os.
DirEntryABC
Bases:
abc.ABC
Object representation of directory or a file yielded by scandir().
Has subset of Path object methods.
-
inode
() → int Return the inode number of the entry.
Returns: inode number Return type: int
-
is_dir
(*, follow_symlinks: bool = True) → bool Return True if this entry is a directory.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: True if path points to a directory. Return type: bool Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
is_file
(*, follow_symlinks: bool = True) → bool Return True if this entry is a file.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: True if path points to a file. Return type: bool Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
is_symlink
() → bool Return True if this entry is a symlink.
Returns: true if targer is symlink Return type: bool
-
stat
(*, follow_symlinks: bool = True) → _ATTRIBUTES Return SFTPAttributes object similar to os.stat.
Parameters: follow_symlinks (bool, optional) – if we method should follow and resolve symlinks, by default False Returns: attributes object for the entry. Return type: SFTPAttributes Warning
follow_symlinks is False by default in the remote implementation, contrary to the implementation in python os library!
-
ssh_utilities.abstract._pathlib
Template module for all pathlib classes.
-
class
ssh_utilities.abstract._pathlib.
PathlibABC
Bases:
abc.ABC
,typing.Generic
pathlib module drop-in replacement base.
-
Path
(path: _SPATH) → _Pathlib1 Provides API similar to pathlib.Path only for remote host.
Only for Unix to Unix connections
Parameters: path ( ssh_utilities.typeshed._SPATH
) – provide initial pathReturns: object representing remote path Return type: SSHPath
-
ssh_utilities.abstract._shutil
Template module for all shutil classes.
-
class
ssh_utilities.abstract._shutil.
ShutilABC
Bases:
abc.ABC
shutil module drop-in replacement base.
-
copy
(src: _SPATH, dst: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, callback: _CALLBACK = None, quiet: bool = True) Send files in the chosen direction local <-> remote.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – path to the file - dst (
ssh_utilities.typeshed._SPATH
) – path to copy into - direction (
ssh_utilities.typeshed._DIRECTION
) – ‘get’ for download and ‘put’ for upload - follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- callback (
ssh_utilities.typeshed._CALLBACK
) – callback function that recives two arguments: amount done and total amount to be copied - quiet (bool) – if True informative messages are suppresssed
Warning
Unlike shutil this function cannot preserve file permissions (copy) or file metadata (copy2)
Raises: FileNotFoundError
– if src is not fileValueError
– if direction is not put or get
- src (
-
copy_files
(files: List[str], remote_path: _SPATH, local_path: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, quiet: bool = False) Send files in the chosen direction local <-> remote.
Parameters: - files (List[str]) – list of files to upload/download
- remote_path (
ssh_utilities.typeshed._SPATH
) – path to remote directory with files - local_path (
ssh_utilities.typeshed._SPATH
) – path to local directory with files - direction (str) – get for download and put for upload
- follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- quiet (bool) – if True informative messages are suppresssed
-
copyfile
(src: _SPATH, dst: _SPATH, *, direction: _DIRECTION, follow_symlinks: bool = True, callback: _CALLBACK = None, quiet: bool = True) Send files in the chosen direction local <-> remote.
Parameters: - src (
ssh_utilities.typeshed._SPATH
) – path to the file - dst (
ssh_utilities.typeshed._SPATH
) – path to copy into - direction (
ssh_utilities.typeshed._DIRECTION
) – ‘get’ for download and ‘put’ for upload - follow_symlinks (bool) – resolve symlinks when looking for file, by default True
- callback (
ssh_utilities.typeshed._CALLBACK
) – callback function that recives two arguments: amount done and total amount to be copied - quiet (bool) – if True informative messages are suppresssed
Raises: FileNotFoundError
– if src is not fileIsADirectoryError
– if dst is a targer directory not full pathValueError
– if direction is not put or get
- src (
-
copyfileobj
(fsrc: Union[IO, SFTPFile], fdst: Union[IO, SFTPFile], *, direction: _DIRECTION, length: Optional[int] = None) Copy the contents of one file-like object to another.
Parameters: - fsrc (Union[IO, SFTPFile]) – source file-like object must be local/remote based on direction parameter
- fdst (Union[IO, SFTPFile]) – source file-like object must be local/remote based on direction parameter
- direction (_DIRECTION) – either ‘put’ or ‘get’
- length (int, optional) – [description], by default -1
-
download_tree
(remote_path: _SPATH, local_path: _SPATH, include: _GLOBPAT = None, exclude: _GLOBPAT = None, remove_after: bool = True, quiet: bool = False) Download directory tree from remote.
Remote directory must exist otherwise exception is raised.
Parameters: - remote_path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be downloaded - local_path (
ssh_utilities.typeshed._SPATH
) – directory to copy to, must be full path! - remove_after (bool) – remove remote copy after directory is uploaded
- include (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to include in copy, can be used simultaneously with exclude, default is None = no filtering - exclude (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to exclude in copy, can be used simultaneously with include, default is None = no filtering - quiet (Literal[True, False, "stats", "progress"]) – if True informative messages are suppresssed if False all is printed, if stats all statistics except progressbar are suppressed if progress only progressbar is suppressed
Warning
both paths must be full: <some_remote_path>/my_directory -> <some_local_path>/my_directory
Raises: FileNotFoundError
– when remote directory does not exist- remote_path (
-
ignore_patterns
(*paterns) → Callable[[Any, Sequence[str]], Set[str]] Creates a callable for shutil.copytree function to ignore files.
Parameters: *patterns (Sequence[str]) – a list of glob patterns that will ne used to exclude files Returns: Callable the filters files, when called with a list of strings returns a subset that matches one oth the exclude patterns Return type: Callable[[Any, Sequence[str]], Set[str]]
-
rmtree
(path: _SPATH, ignore_errors: bool = False, quiet: bool = True) Recursively remove directory tree.
Parameters: - path (
ssh_utilities.typeshed._SPATH
) – directory to be recursively removed - ignore_errors (bool) – if True only log warnings do not raise exception
- quiet (bool) – if True informative messages are suppresssed
Raises: FileNotFoundError
– if some part of deleting filed- path (
-
upload_tree
(local_path: _SPATH, remote_path: _SPATH, include: _GLOBPAT = None, exclude: _GLOBPAT = None, remove_after: bool = True, quiet: bool = False) Upload directory tree to remote.
Local path must exist otherwise, exception is raised.
Parameters: - local_path (
ssh_utilities.typeshed._SPATH
) – path to directory which should be uploaded - remote_path (
ssh_utilities.typeshed._SPATH
) – directory to copy to, must be full path! - remove_after (bool) – remove local copy after directory is uploaded
- include (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to include in copy, can be used simultaneously with exclude, default is None = no filtering - exclude (
ssh_utilities.typeshed._GLOBPAT
) – glob pattern of files to exclude in copy, can be used simultaneously with include, default is None = no filtering - quiet (Literal[True, False, "stats", "progress"]) – if True informative messages are suppresssed if False all is printed, if stats all statistics except progressbar are suppressed if progress only progressbar is suppressed
Warning
both paths must be full: <some_local_path>/my_directory -> <some_remote_path>/my_directory
Raises: FileNotFoundError
– when local directory does not exist- local_path (
-
ssh_utilities.abstract._subprocess
Template module for all subprocess classes.
-
class
ssh_utilities.abstract._subprocess.
SubprocessABC
Bases:
abc.ABC
,typing.Generic
subprocess module drop-in replacement base.
-
run
(args: _CMD, *, suppress_out: bool, quiet: bool = True, bufsize: int = -1, executable: _SPATH = None, input: Optional[str] = None, stdin: _FILE = None, stdout: _FILE = None, stderr: _FILE = None, capture_output: bool = False, shell: bool = False, cwd: _SPATH = None, timeout: Optional[float] = None, check: bool = False, encoding: Optional[str] = None, errors: Optional[str] = None, text: Optional[bool] = None, env: _ENV = None, universal_newlines: bool = False) → _Subprocess1 Excecute command on remote, has simillar API to subprocess run.
Parameters: - args (
ssh_utilities.typeshed._CMD
) – string, Path-like object or a list of strings. If it is a list it will be joined to string with whitespace delimiter. - suppress_out (bool) – whether to print command output to console, this is required keyword argument
- quiet (bool, optional) – whether to print other function messages, by default True
- bufsize (int, optional) – buffer size, 0 turns off buffering, 1 uses line buffering, and any number greater than 1 (>1) uses that specific buffer size. This applies ti underlying paramiko client as well as stdin, stdout and stderr PIPES, by default -1
- executable (
ssh_utilities.typeshed._SPATH
, optional) – [description], by default None - input (Optional[str], optional) – [description], by default None
- stdin (_FILE, optional) – [description], by default None
- stdout (_FILE, optional) – [description], by default None
- stderr (_FILE, optional) – [description], by default None
- capture_output (bool, optional) – if true then lightweight result object with same API as subprocess.CompletedProcess is returned. Same as passing PIPE to stdout and stderr. Both options cannot be used at the same time, by default False
- shell (bool, optional) – requests a pseudo terminal from server, by default False
- cwd (_SPATH, optional) – execute command in this directory, by default None
- timeout (Optional[float], optional) – set, by default None
- check (bool, optional) – checks for command return code if other than 0 raises CalledProcessError, by default False
- encoding (Optional[str], optional) – encoding to use when decoding remote output, default is utf-8, by default None
- errors (Optional[str], optional) –
string that specifies how encoding and decoding errors are to be handled, see builtin function open documentation for more details, by default None
- text (Optional[bool], optional) – will select default encoding and open stdin, stdout and stderr streams in text mode. The default encoding, contrary to behaviour of subprocess module is not selected by locale.getpreferredencoding(False) but is always set to utf-8. By default None
- env (
ssh_utilities.typeshed._ENV
, optional) – optinal environment variables that will be merged into the existing environment. This is different to subprocess behaviour which creates new environment with only specified variables, by default None - universal_newlines (bool, optional) – an alias for text keyword argument, by default None
Warning
New environment variables defined by env might get silently rejected by the server.
Currentlly it is only possible to use input agrgument, not stdin and send data to process only once at the begining. It is still under developement
Returns: if capture_output is true, returns lightweight result object with same API as subprocess.CompletedProcess
Return type: Raises: ValueError
– if stdin and input are specified at the same timeValueError
– if capture_output and stdout and/or stderr are specified at the same timeValueError
– if text or universal_newlines is used simultaneously with” encoding and/or errors argumentsNotImplementedError
– if stdin or executable is used - work in progressTypeError
– if stdin, stdout or stderr arguments are of wrong typeTypeError
– if args argument is of wrong typeCalledProcessError
– if check is true and command exited with non-zero statusTimeoutExpired
– if the command exceeded allowed run time
- args (
-