From a1ae4706c643e4d3a15f41ef35cb304278787be6 Mon Sep 17 00:00:00 2001 From: Waket Zheng Date: Sat, 11 Jul 2026 01:55:32 +0800 Subject: [PATCH] Auto-reformat with `ruff check --select=I --fix` --- .pre-commit-config.yaml | 7 + asyncssh/__init__.py | 256 +++++++++++------- asyncssh/agent.py | 15 +- asyncssh/agent_unix.py | 1 - asyncssh/agent_win32.py | 1 - asyncssh/asn1.py | 4 +- asyncssh/auth.py | 30 ++- asyncssh/auth_keys.py | 17 +- asyncssh/channel.py | 102 ++++--- asyncssh/client.py | 1 - asyncssh/compression.py | 2 +- asyncssh/config.py | 16 +- asyncssh/connection.py | 373 +++++++++++++++++--------- asyncssh/crypto/__init__.py | 44 +-- asyncssh/crypto/chacha.py | 1 - asyncssh/crypto/cipher.py | 5 +- asyncssh/crypto/dsa.py | 1 - asyncssh/crypto/ec.py | 4 +- asyncssh/crypto/ed.py | 4 +- asyncssh/crypto/misc.py | 16 +- asyncssh/crypto/rsa.py | 4 +- asyncssh/crypto/umac.py | 1 - asyncssh/crypto/x509.py | 8 +- asyncssh/dsa.py | 16 +- asyncssh/ecdsa.py | 34 ++- asyncssh/eddsa.py | 22 +- asyncssh/editor.py | 15 +- asyncssh/encryption.py | 5 +- asyncssh/forward.py | 5 +- asyncssh/gss.py | 6 +- asyncssh/gss_unix.py | 3 +- asyncssh/gss_win32.py | 19 +- asyncssh/kex.py | 1 - asyncssh/kex_dh.py | 36 ++- asyncssh/kex_rsa.py | 23 +- asyncssh/keysign.py | 7 +- asyncssh/known_hosts.py | 22 +- asyncssh/listener.py | 22 +- asyncssh/logging.py | 1 - asyncssh/mac.py | 4 +- asyncssh/misc.py | 51 +++- asyncssh/packet.py | 13 +- asyncssh/pattern.py | 1 - asyncssh/pbe.py | 5 +- asyncssh/pkcs11.py | 15 +- asyncssh/process.py | 62 +++-- asyncssh/public_key.py | 67 +++-- asyncssh/rsa.py | 16 +- asyncssh/saslprep.py | 2 +- asyncssh/scp.py | 49 +++- asyncssh/server.py | 22 +- asyncssh/session.py | 22 +- asyncssh/sftp.py | 254 ++++++++++++------ asyncssh/sk.py | 23 +- asyncssh/sk_ecdsa.py | 26 +- asyncssh/sk_eddsa.py | 14 +- asyncssh/socks.py | 1 - asyncssh/sshsig.py | 31 ++- asyncssh/stream.py | 42 ++- asyncssh/subprocess.py | 13 +- asyncssh/tuntap.py | 1 - asyncssh/x11.py | 16 +- docs/conf.py | 3 +- examples/callback_client.py | 6 +- examples/callback_client2.py | 6 +- examples/callback_client3.py | 6 +- examples/callback_math_server.py | 6 +- examples/chat_server.py | 6 +- examples/check_exit_status.py | 6 +- examples/chroot_sftp_server.py | 7 +- examples/direct_client.py | 6 +- examples/direct_server.py | 6 +- examples/editor.py | 6 +- examples/gather_results.py | 5 +- examples/listening_client.py | 6 +- examples/local_forwarding_client.py | 6 +- examples/local_forwarding_client2.py | 6 +- examples/local_forwarding_server.py | 6 +- examples/math_client.py | 6 +- examples/math_server.py | 6 +- examples/redirect_input.py | 6 +- examples/redirect_local_pipe.py | 7 +- examples/redirect_remote_pipe.py | 6 +- examples/redirect_server.py | 7 +- examples/remote_forwarding_client.py | 6 +- examples/remote_forwarding_client2.py | 6 +- examples/remote_forwarding_server.py | 6 +- examples/reverse_client.py | 6 +- examples/reverse_server.py | 6 +- examples/scp_client.py | 6 +- examples/set_environment.py | 6 +- examples/set_terminal.py | 6 +- examples/sftp_client.py | 6 +- examples/show_environment.py | 6 +- examples/show_terminal.py | 6 +- examples/simple_cert_server.py | 6 +- examples/simple_client.py | 6 +- examples/simple_keyed_server.py | 6 +- examples/simple_scp_server.py | 6 +- examples/simple_server.py | 7 +- examples/simple_sftp_server.py | 6 +- examples/stream_direct_client.py | 6 +- examples/stream_direct_server.py | 6 +- examples/stream_listening_client.py | 6 +- tests/keysign_stub.py | 2 +- tests/pkcs11_stub.py | 1 + tests/server.py | 10 +- tests/sk_stub.py | 13 +- tests/sspi_stub.py | 8 +- tests/test_agent.py | 12 +- tests/test_asn1.py | 17 +- tests/test_auth.py | 32 ++- tests/test_channel.py | 31 ++- tests/test_compression.py | 8 +- tests/test_config.py | 2 - tests/test_connection.py | 58 ++-- tests/test_connection_auth.py | 16 +- tests/test_editor.py | 1 + tests/test_encryption.py | 8 +- tests/test_forward.py | 9 +- tests/test_kex.py | 54 ++-- tests/test_logging.py | 1 - tests/test_mac.py | 2 +- tests/test_packet.py | 13 +- tests/test_pkcs11.py | 10 +- tests/test_process.py | 4 +- tests/test_public_key.py | 40 +-- tests/test_saslprep.py | 3 +- tests/test_sftp.py | 126 ++++++--- tests/test_sk.py | 2 +- tests/test_sshsig.py | 1 - tests/test_subprocess.py | 1 + tests/test_tuntap.py | 1 - tests/test_x11.py | 25 +- tests/test_x509.py | 9 +- tests/util.py | 5 +- 136 files changed, 1825 insertions(+), 852 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ed888e4e..835eae4f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,3 +18,10 @@ repos: additional_dependencies: - tomli exclude: '^docs/changes\.rst$|^\.?pylintrc$' + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: 'v0.15.21' + hooks: + - id: ruff + args: [--select=I, --fix, --exit-non-zero-on-fix, --show-fixes] + types: [python] diff --git a/asyncssh/__init__.py b/asyncssh/__init__.py index c38d9dcc..680575a1 100644 --- a/asyncssh/__init__.py +++ b/asyncssh/__init__.py @@ -20,110 +20,184 @@ """An asynchronous SSH2 library for Python""" -from .version import __author__, __author_email__, __url__, __version__ - -# pylint: disable=wildcard-import - -from .constants import * +# Import these explicitly to trigger register calls in them +from . import dsa, ecdsa, eddsa, kex_dh, kex_rsa, rsa, sk_ecdsa, sk_eddsa # pylint: enable=wildcard-import - from .agent import SSHAgentClient, SSHAgentKeyPair, connect_agent - -from .auth_keys import SSHAuthorizedKeys -from .auth_keys import import_authorized_keys, read_authorized_keys - -from .channel import SSHClientChannel, SSHServerChannel -from .channel import SSHTCPChannel, SSHUNIXChannel, SSHTunTapChannel - +from .auth_keys import SSHAuthorizedKeys, import_authorized_keys, read_authorized_keys +from .channel import ( + SSHClientChannel, + SSHServerChannel, + SSHTCPChannel, + SSHTunTapChannel, + SSHUNIXChannel, +) from .client import SSHClient - from .config import ConfigParseError +from .connection import ( + SSHAcceptHandler, + SSHAcceptor, + SSHClientConnection, + SSHClientConnectionOptions, + SSHServerConnection, + SSHServerConnectionOptions, + connect, + connect_reverse, + create_connection, + create_server, + get_server_auth_methods, + get_server_host_key, + listen, + listen_reverse, + run_client, + run_server, +) -from .forward import SSHForwarder - -from .connection import SSHAcceptor, SSHClientConnection, SSHServerConnection -from .connection import SSHClientConnectionOptions, SSHServerConnectionOptions -from .connection import SSHAcceptHandler -from .connection import create_connection, create_server, connect, listen -from .connection import connect_reverse, listen_reverse, get_server_host_key -from .connection import get_server_auth_methods, run_client, run_server - +# pylint: disable=wildcard-import +from .constants import * from .editor import SSHLineEditorChannel - -from .known_hosts import SSHKnownHosts -from .known_hosts import import_known_hosts, read_known_hosts -from .known_hosts import match_known_hosts - +from .forward import SSHForwarder +from .known_hosts import ( + SSHKnownHosts, + import_known_hosts, + match_known_hosts, + read_known_hosts, +) from .listener import SSHListener - -from .logging import logger, set_log_level, set_sftp_log_level, set_debug_level - -from .misc import BytesOrStr -from .misc import Error, DisconnectError, ChannelOpenError, ChannelListenError -from .misc import ConnectionLost, CompressionError, HostKeyNotVerifiable -from .misc import KeyExchangeFailed, IllegalUserName, MACError -from .misc import PermissionDenied, ProtocolError, ProtocolNotSupported -from .misc import ServiceNotAvailable, PasswordChangeRequired -from .misc import BreakReceived, SignalReceived, TerminalSizeChanged - +from .logging import logger, set_debug_level, set_log_level, set_sftp_log_level +from .misc import ( + BreakReceived, + BytesOrStr, + ChannelListenError, + ChannelOpenError, + CompressionError, + ConnectionLost, + DisconnectError, + Error, + HostKeyNotVerifiable, + IllegalUserName, + KeyExchangeFailed, + MACError, + PasswordChangeRequired, + PermissionDenied, + ProtocolError, + ProtocolNotSupported, + ServiceNotAvailable, + SignalReceived, + TerminalSizeChanged, +) from .pbe import KeyEncryptionError - from .pkcs11 import load_pkcs11_keys - -from .process import SSHServerProcessFactory -from .process import SSHClientProcess, SSHServerProcess -from .process import SSHCompletedProcess, ProcessError -from .process import TimeoutError # pylint: disable=redefined-builtin -from .process import DEVNULL, PIPE, STDOUT - -from .public_key import SSHKey, SSHKeyPair, SSHCertificate -from .public_key import KeyGenerationError, KeyImportError, KeyExportError -from .public_key import generate_private_key, import_private_key -from .public_key import import_public_key, import_certificate -from .public_key import read_private_key, read_public_key, read_certificate -from .public_key import read_private_key_list, read_public_key_list -from .public_key import read_certificate_list -from .public_key import load_keypairs, load_public_keys, load_certificates -from .public_key import load_resident_keys - +from .process import ( + DEVNULL, + PIPE, + STDOUT, + ProcessError, + SSHClientProcess, + SSHCompletedProcess, + SSHServerProcess, + SSHServerProcessFactory, + TimeoutError, # pylint: disable=redefined-builtin +) +from .public_key import ( + KeyExportError, + KeyGenerationError, + KeyImportError, + SSHCertificate, + SSHKey, + SSHKeyPair, + generate_private_key, + import_certificate, + import_private_key, + import_public_key, + load_certificates, + load_keypairs, + load_public_keys, + load_resident_keys, + read_certificate, + read_certificate_list, + read_private_key, + read_private_key_list, + read_public_key, + read_public_key_list, +) from .rsa import set_default_skip_rsa_key_validation - from .scp import scp - -from .session import DataType, SSHClientSession, SSHServerSession -from .session import SSHTCPSession, SSHUNIXSession, SSHTunTapSession - from .server import SSHServer - -from .sftp import SFTPClient, SFTPClientFile, SFTPServer, SFTPError -from .sftp import SFTPEOFError, SFTPNoSuchFile, SFTPPermissionDenied -from .sftp import SFTPFailure, SFTPBadMessage, SFTPNoConnection -from .sftp import SFTPInvalidHandle, SFTPNoSuchPath, SFTPFileAlreadyExists -from .sftp import SFTPWriteProtect, SFTPNoMedia, SFTPNoSpaceOnFilesystem -from .sftp import SFTPQuotaExceeded, SFTPUnknownPrincipal, SFTPLockConflict -from .sftp import SFTPDirNotEmpty, SFTPNotADirectory, SFTPInvalidFilename -from .sftp import SFTPLinkLoop, SFTPCannotDelete, SFTPInvalidParameter -from .sftp import SFTPFileIsADirectory, SFTPByteRangeLockConflict -from .sftp import SFTPByteRangeLockRefused, SFTPDeletePending -from .sftp import SFTPFileCorrupt, SFTPOwnerInvalid, SFTPGroupInvalid -from .sftp import SFTPNoMatchingByteRangeLock -from .sftp import SFTPConnectionLost, SFTPOpUnsupported -from .sftp import SFTPAttrs, SFTPVFSAttrs, SFTPName, SFTPLimits -from .sftp import SEEK_SET, SEEK_CUR, SEEK_END - -from .sshsig import SSHAllowedSigners -from .sshsig import import_allowed_signers, read_allowed_signers -from .sshsig import create_sshsig, validate_sshsig - -from .stream import SSHSocketSessionFactory, SSHServerSessionFactory -from .stream import SFTPServerFactory, SSHReader, SSHWriter - -from .subprocess import SSHSubprocessReadPipe, SSHSubprocessWritePipe -from .subprocess import SSHSubprocessProtocol, SSHSubprocessTransport - -# Import these explicitly to trigger register calls in them -from . import sk_eddsa, sk_ecdsa, eddsa, ecdsa, rsa, dsa, kex_dh, kex_rsa +from .session import ( + DataType, + SSHClientSession, + SSHServerSession, + SSHTCPSession, + SSHTunTapSession, + SSHUNIXSession, +) +from .sftp import ( + SEEK_CUR, + SEEK_END, + SEEK_SET, + SFTPAttrs, + SFTPBadMessage, + SFTPByteRangeLockConflict, + SFTPByteRangeLockRefused, + SFTPCannotDelete, + SFTPClient, + SFTPClientFile, + SFTPConnectionLost, + SFTPDeletePending, + SFTPDirNotEmpty, + SFTPEOFError, + SFTPError, + SFTPFailure, + SFTPFileAlreadyExists, + SFTPFileCorrupt, + SFTPFileIsADirectory, + SFTPGroupInvalid, + SFTPInvalidFilename, + SFTPInvalidHandle, + SFTPInvalidParameter, + SFTPLimits, + SFTPLinkLoop, + SFTPLockConflict, + SFTPName, + SFTPNoConnection, + SFTPNoMatchingByteRangeLock, + SFTPNoMedia, + SFTPNoSpaceOnFilesystem, + SFTPNoSuchFile, + SFTPNoSuchPath, + SFTPNotADirectory, + SFTPOpUnsupported, + SFTPOwnerInvalid, + SFTPPermissionDenied, + SFTPQuotaExceeded, + SFTPServer, + SFTPUnknownPrincipal, + SFTPVFSAttrs, + SFTPWriteProtect, +) +from .sshsig import ( + SSHAllowedSigners, + create_sshsig, + import_allowed_signers, + read_allowed_signers, + validate_sshsig, +) +from .stream import ( + SFTPServerFactory, + SSHReader, + SSHServerSessionFactory, + SSHSocketSessionFactory, + SSHWriter, +) +from .subprocess import ( + SSHSubprocessProtocol, + SSHSubprocessReadPipe, + SSHSubprocessTransport, + SSHSubprocessWritePipe, +) +from .version import __author__, __author_email__, __url__, __version__ __all__ = [ '__author__', '__author_email__', '__url__', '__version__', diff --git a/asyncssh/agent.py b/asyncssh/agent.py index be7f3984..8db77798 100644 --- a/asyncssh/agent.py +++ b/asyncssh/agent.py @@ -24,15 +24,20 @@ import os import sys from types import TracebackType -from typing import TYPE_CHECKING, List, Optional, Protocol, Sequence, Tuple -from typing import Type, Union +from typing import TYPE_CHECKING, List, Optional, Protocol, Sequence, Tuple, Type, Union + from typing_extensions import Self from .listener import SSHForwardListener from .misc import async_context_manager, maybe_wait_closed -from .packet import Byte, String, UInt32, PacketDecodeError, SSHPacket -from .public_key import KeyPairListArg, SSHCertificate, SSHKeyPair -from .public_key import load_default_keypairs, load_keypairs +from .packet import Byte, PacketDecodeError, SSHPacket, String, UInt32 +from .public_key import ( + KeyPairListArg, + SSHCertificate, + SSHKeyPair, + load_default_keypairs, + load_keypairs, +) if TYPE_CHECKING: from tempfile import TemporaryDirectory diff --git a/asyncssh/agent_unix.py b/asyncssh/agent_unix.py index 63d9a6b1..6958499c 100644 --- a/asyncssh/agent_unix.py +++ b/asyncssh/agent_unix.py @@ -24,7 +24,6 @@ import errno from typing import TYPE_CHECKING, Tuple - if TYPE_CHECKING: # pylint: disable=cyclic-import from .agent import AgentReader, AgentWriter diff --git a/asyncssh/agent_win32.py b/asyncssh/agent_win32.py index f162f58a..77751a43 100644 --- a/asyncssh/agent_win32.py +++ b/asyncssh/agent_win32.py @@ -31,7 +31,6 @@ from .misc import open_file - if TYPE_CHECKING: # pylint: disable=cyclic-import from .agent import AgentReader, AgentWriter diff --git a/asyncssh/asn1.py b/asyncssh/asn1.py index 6a7293bc..95c7a103 100644 --- a/asyncssh/asn1.py +++ b/asyncssh/asn1.py @@ -32,9 +32,7 @@ """ -from typing import Dict, FrozenSet, Sequence, Set, Tuple, Type, TypeVar, Union -from typing import cast - +from typing import Dict, FrozenSet, Sequence, Set, Tuple, Type, TypeVar, Union, cast _DERClass = Type['DERType'] _DERClassVar = TypeVar('_DERClassVar', bound='_DERClass') diff --git a/asyncssh/auth.py b/asyncssh/auth.py index 8cfd0412..473a1b2d 100644 --- a/asyncssh/auth.py +++ b/asyncssh/auth.py @@ -20,25 +20,37 @@ """SSH authentication handlers""" -from typing import TYPE_CHECKING, Awaitable, Dict, List, Optional -from typing import Sequence, Tuple, Type, Union, cast +from typing import ( + TYPE_CHECKING, + Awaitable, + Dict, + List, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from .constants import DEFAULT_LANG from .gss import GSSBase, GSSError from .logging import SSHLogger -from .misc import ProtocolError, PasswordChangeRequired, get_symbol_names -from .misc import run_in_executor -from .packet import Boolean, String, UInt32, SSHPacket, SSHPacketHandler +from .misc import ( + PasswordChangeRequired, + ProtocolError, + get_symbol_names, + run_in_executor, +) +from .packet import Boolean, SSHPacket, SSHPacketHandler, String, UInt32 from .public_key import SigningKey -from .saslprep import saslprep, SASLPrepError - +from .saslprep import SASLPrepError, saslprep if TYPE_CHECKING: import asyncio # pylint: disable=cyclic-import - from .connection import SSHConnection, SSHClientConnection - from .connection import SSHServerConnection + from .connection import SSHClientConnection, SSHConnection, SSHServerConnection KbdIntPrompts = Sequence[Tuple[str, bool]] diff --git a/asyncssh/auth_keys.py b/asyncssh/auth_keys.py index c0b48906..8b782598 100644 --- a/asyncssh/auth_keys.py +++ b/asyncssh/auth_keys.py @@ -21,8 +21,7 @@ """Parser for SSH authorized_keys files""" from pathlib import PurePath -from typing import Dict, List, Mapping, Optional, Sequence -from typing import Set, Tuple, Union, cast +from typing import Dict, List, Mapping, Optional, Sequence, Set, Tuple, Union, cast try: # pylint: disable=unused-import @@ -33,11 +32,15 @@ from .misc import FilePath, OptionsParser, ip_address, read_file from .pattern import HostPatternList, WildcardPatternList -from .public_key import KeyImportError, SSHKey -from .public_key import SSHX509Certificate, SSHX509CertificateChain -from .public_key import import_public_key, import_certificate -from .public_key import import_certificate_subject - +from .public_key import ( + KeyImportError, + SSHKey, + SSHX509Certificate, + SSHX509CertificateChain, + import_certificate, + import_certificate_subject, + import_public_key, +) _EntryOptions = Mapping[str, object] diff --git a/asyncssh/channel.py b/asyncssh/channel.py index 28f13a8f..88372160 100644 --- a/asyncssh/channel.py +++ b/asyncssh/channel.py @@ -28,46 +28,84 @@ import signal as _signal import sys from types import MappingProxyType -from typing import TYPE_CHECKING, Any, AnyStr, Awaitable, Callable -from typing import Dict, Generic, Iterable, List, Mapping, Optional -from typing import Set, Tuple, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Awaitable, + Callable, + Dict, + Generic, + Iterable, + List, + Mapping, + Optional, + Set, + Tuple, + Union, + cast, +) from . import constants -from .constants import DEFAULT_LANG, EXTENDED_DATA_STDERR -from .constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_WINDOW_ADJUST -from .constants import MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA -from .constants import MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MSG_CHANNEL_REQUEST -from .constants import MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE -from .constants import OPEN_CONNECT_FAILED, PTY_OP_RESERVED, PTY_OP_END -from .constants import OPEN_REQUEST_X11_FORWARDING_FAILED -from .constants import OPEN_REQUEST_PTY_FAILED, OPEN_REQUEST_SESSION_FAILED - +from .constants import ( + DEFAULT_LANG, + EXTENDED_DATA_STDERR, + MSG_CHANNEL_CLOSE, + MSG_CHANNEL_DATA, + MSG_CHANNEL_EOF, + MSG_CHANNEL_EXTENDED_DATA, + MSG_CHANNEL_FAILURE, + MSG_CHANNEL_OPEN, + MSG_CHANNEL_REQUEST, + MSG_CHANNEL_SUCCESS, + MSG_CHANNEL_WINDOW_ADJUST, + OPEN_CONNECT_FAILED, + OPEN_REQUEST_PTY_FAILED, + OPEN_REQUEST_SESSION_FAILED, + OPEN_REQUEST_X11_FORWARDING_FAILED, + PTY_OP_END, + PTY_OP_RESERVED, +) from .editor import SSHLineEditorChannel, SSHLineEditorSession - from .logging import SSHLogger - -from .misc import ChannelOpenError, EnvMap, MaybeAwait, ProtocolError -from .misc import TermModes, TermSize, TermSizeArg -from .misc import decode_env, encode_env, get_symbol_names, map_handler_name - -from .packet import Boolean, Byte, String, UInt32, SSHPacket, SSHPacketHandler - -from .session import SSHSession, SSHClientSession, SSHServerSession -from .session import SSHTCPSession, SSHUNIXSession, SSHTunTapSession -from .session import SSHSessionFactory, SSHClientSessionFactory -from .session import SSHTCPSessionFactory, SSHUNIXSessionFactory -from .session import SSHTunTapSessionFactory - +from .misc import ( + ChannelOpenError, + EnvMap, + MaybeAwait, + ProtocolError, + TermModes, + TermSize, + TermSizeArg, + decode_env, + encode_env, + get_symbol_names, + map_handler_name, +) +from .packet import Boolean, Byte, SSHPacket, SSHPacketHandler, String, UInt32 +from .session import ( + SSHClientSession, + SSHClientSessionFactory, + SSHServerSession, + SSHSession, + SSHSessionFactory, + SSHTCPSession, + SSHTCPSessionFactory, + SSHTunTapSession, + SSHTunTapSessionFactory, + SSHUNIXSession, + SSHUNIXSessionFactory, +) from .stream import DataType - -from .tuntap import SSH_TUN_MODE_POINTTOPOINT, SSH_TUN_UNIT_ANY -from .tuntap import SSH_TUN_AF_INET, SSH_TUN_AF_INET6 - +from .tuntap import ( + SSH_TUN_AF_INET, + SSH_TUN_AF_INET6, + SSH_TUN_MODE_POINTTOPOINT, + SSH_TUN_UNIT_ANY, +) if TYPE_CHECKING: # pylint: disable=cyclic-import - from .connection import SSHConnection, SSHClientConnection - from .connection import SSHServerConnection + from .connection import SSHClientConnection, SSHConnection, SSHServerConnection _const_dict: Mapping[str, int] = constants.__dict__ diff --git a/asyncssh/client.py b/asyncssh/client.py index 8e52f9fb..1f684324 100644 --- a/asyncssh/client.py +++ b/asyncssh/client.py @@ -26,7 +26,6 @@ from .misc import MaybeAwait from .public_key import KeyPairListArg, SSHKey - if TYPE_CHECKING: # pylint: disable=cyclic-import from .connection import SSHClientConnection diff --git a/asyncssh/compression.py b/asyncssh/compression.py index e05ca740..4c51a23b 100644 --- a/asyncssh/compression.py +++ b/asyncssh/compression.py @@ -20,8 +20,8 @@ """SSH compression handlers""" -from typing import Callable, List, Optional import zlib +from typing import Callable, List, Optional _cmp_algs: List[bytes] = [] _default_cmp_algs: List[bytes] = [] diff --git a/asyncssh/config.py b/asyncssh/config.py index 96eb0a20..3a9d1dda 100644 --- a/asyncssh/config.py +++ b/asyncssh/config.py @@ -25,12 +25,22 @@ import shlex import socket import subprocess - from hashlib import sha1 from pathlib import Path, PurePath from subprocess import DEVNULL -from typing import Callable, Dict, Iterator, List, NoReturn, Optional -from typing import Sequence, Set, Tuple, Union, cast +from typing import ( + Callable, + Dict, + Iterator, + List, + NoReturn, + Optional, + Sequence, + Set, + Tuple, + Union, + cast, +) from .constants import DEFAULT_PORT from .logging import logger diff --git a/asyncssh/connection.py b/asyncssh/connection.py index 8e4feb31..2c950f84 100644 --- a/asyncssh/connection.py +++ b/asyncssh/connection.py @@ -32,148 +32,269 @@ import sys import tempfile import time - from collections import OrderedDict from functools import partial from pathlib import Path from types import TracebackType -from typing import TYPE_CHECKING, Any, AnyStr, Awaitable, Callable, Dict -from typing import Generic, List, Mapping, Optional, Protocol, Sequence -from typing import Set, Tuple, Type, TypeVar, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Awaitable, + Callable, + Dict, + Generic, + List, + Mapping, + Optional, + Protocol, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, +) + from typing_extensions import Self from .agent import SSHAgentClient, SSHAgentListener - -from .auth import Auth, ClientAuth, KbdIntChallenge, KbdIntPrompts -from .auth import KbdIntResponse, PasswordChangeResponse -from .auth import get_supported_client_auth_methods, lookup_client_auth -from .auth import get_supported_server_auth_methods, lookup_server_auth - +from .auth import ( + Auth, + ClientAuth, + KbdIntChallenge, + KbdIntPrompts, + KbdIntResponse, + PasswordChangeResponse, + get_supported_client_auth_methods, + get_supported_server_auth_methods, + lookup_client_auth, + lookup_server_auth, +) from .auth_keys import SSHAuthorizedKeys, read_authorized_keys - -from .channel import SSHChannel, SSHClientChannel, SSHServerChannel -from .channel import SSHTCPChannel, SSHUNIXChannel, SSHTunTapChannel -from .channel import SSHX11Channel, SSHAgentChannel - +from .channel import ( + SSHAgentChannel, + SSHChannel, + SSHClientChannel, + SSHServerChannel, + SSHTCPChannel, + SSHTunTapChannel, + SSHUNIXChannel, + SSHX11Channel, +) from .client import SSHClient - -from .compression import Compressor, Decompressor, get_compression_algs -from .compression import get_default_compression_algs, get_compression_params -from .compression import get_compressor, get_decompressor - -from .config import ConfigPaths, SSHConfig, SSHClientConfig, SSHServerConfig - -from .constants import DEFAULT_LANG, DEFAULT_PORT -from .constants import DISC_BY_APPLICATION -from .constants import EXTENDED_DATA_STDERR -from .constants import MSG_DISCONNECT, MSG_IGNORE, MSG_UNIMPLEMENTED, MSG_DEBUG -from .constants import MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT, MSG_EXT_INFO -from .constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_CONFIRMATION -from .constants import MSG_CHANNEL_OPEN_FAILURE -from .constants import MSG_CHANNEL_FIRST, MSG_CHANNEL_LAST -from .constants import MSG_KEXINIT, MSG_NEWKEYS, MSG_KEX_FIRST, MSG_KEX_LAST -from .constants import MSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE -from .constants import MSG_USERAUTH_SUCCESS, MSG_USERAUTH_BANNER -from .constants import MSG_USERAUTH_FIRST, MSG_USERAUTH_LAST -from .constants import MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS -from .constants import MSG_REQUEST_FAILURE -from .constants import OPEN_ADMINISTRATIVELY_PROHIBITED, OPEN_CONNECT_FAILED -from .constants import OPEN_UNKNOWN_CHANNEL_TYPE - -from .encryption import Encryption, get_encryption_algs -from .encryption import get_default_encryption_algs -from .encryption import encryption_needs_mac -from .encryption import get_encryption_params, get_encryption - +from .compression import ( + Compressor, + Decompressor, + get_compression_algs, + get_compression_params, + get_compressor, + get_decompressor, + get_default_compression_algs, +) +from .config import ConfigPaths, SSHClientConfig, SSHConfig, SSHServerConfig +from .constants import ( + DEFAULT_LANG, + DEFAULT_PORT, + DISC_BY_APPLICATION, + EXTENDED_DATA_STDERR, + MSG_CHANNEL_FIRST, + MSG_CHANNEL_LAST, + MSG_CHANNEL_OPEN, + MSG_CHANNEL_OPEN_CONFIRMATION, + MSG_CHANNEL_OPEN_FAILURE, + MSG_DEBUG, + MSG_DISCONNECT, + MSG_EXT_INFO, + MSG_GLOBAL_REQUEST, + MSG_IGNORE, + MSG_KEX_FIRST, + MSG_KEX_LAST, + MSG_KEXINIT, + MSG_NEWKEYS, + MSG_REQUEST_FAILURE, + MSG_REQUEST_SUCCESS, + MSG_SERVICE_ACCEPT, + MSG_SERVICE_REQUEST, + MSG_UNIMPLEMENTED, + MSG_USERAUTH_BANNER, + MSG_USERAUTH_FAILURE, + MSG_USERAUTH_FIRST, + MSG_USERAUTH_LAST, + MSG_USERAUTH_REQUEST, + MSG_USERAUTH_SUCCESS, + OPEN_ADMINISTRATIVELY_PROHIBITED, + OPEN_CONNECT_FAILED, + OPEN_UNKNOWN_CHANNEL_TYPE, +) +from .encryption import ( + Encryption, + encryption_needs_mac, + get_default_encryption_algs, + get_encryption, + get_encryption_algs, + get_encryption_params, +) from .forward import SSHForwarder - -from .gss import GSSBase, GSSClient, GSSServer, GSSError - -from .kex import Kex, get_kex_algs, get_default_kex_algs -from .kex import expand_kex_algs, get_kex - -from .keysign import KeySignPath, SSHKeySignKeyPair -from .keysign import find_keysign, get_keysign_keys - +from .gss import GSSBase, GSSClient, GSSError, GSSServer +from .kex import Kex, expand_kex_algs, get_default_kex_algs, get_kex, get_kex_algs +from .keysign import KeySignPath, SSHKeySignKeyPair, find_keysign, get_keysign_keys from .known_hosts import KnownHostsArg, match_known_hosts - -from .listener import ListenKey, SSHListener -from .listener import SSHTCPClientListener, SSHUNIXClientListener -from .listener import TCPListenerFactory, UNIXListenerFactory -from .listener import create_tcp_forward_listener, create_unix_forward_listener -from .listener import create_socks_listener - +from .listener import ( + ListenKey, + SSHListener, + SSHTCPClientListener, + SSHUNIXClientListener, + TCPListenerFactory, + UNIXListenerFactory, + create_socks_listener, + create_tcp_forward_listener, + create_unix_forward_listener, +) from .logging import SSHLogger, logger - -from .mac import get_mac_algs, get_default_mac_algs - -from .misc import BytesOrStr, BytesOrStrDict, DefTuple, Env, EnvSeq, FilePath -from .misc import HostPort, IPNetwork, MaybeAwait, OptExcInfo, Options, SockAddr -from .misc import ChannelListenError, ChannelOpenError, CompressionError -from .misc import DisconnectError, ConnectionLost, HostKeyNotVerifiable -from .misc import KeyExchangeFailed, IllegalUserName, MACError -from .misc import PasswordChangeRequired, PermissionDenied, ProtocolError -from .misc import ProtocolNotSupported, ServiceNotAvailable -from .misc import TermModesArg, TermSizeArg -from .misc import async_context_manager, construct_disc_error, encode_env -from .misc import get_symbol_names, ip_address, lookup_env, map_handler_name -from .misc import parse_byte_count, parse_time_interval, split_args - -from .packet import Boolean, Byte, NameList, String, UInt32, PacketDecodeError -from .packet import SSHPacket, SSHPacketHandler, SSHPacketLogger - +from .mac import get_default_mac_algs, get_mac_algs +from .misc import ( + BytesOrStr, + BytesOrStrDict, + ChannelListenError, + ChannelOpenError, + CompressionError, + ConnectionLost, + DefTuple, + DisconnectError, + Env, + EnvSeq, + FilePath, + HostKeyNotVerifiable, + HostPort, + IllegalUserName, + IPNetwork, + KeyExchangeFailed, + MACError, + MaybeAwait, + OptExcInfo, + Options, + PasswordChangeRequired, + PermissionDenied, + ProtocolError, + ProtocolNotSupported, + ServiceNotAvailable, + SockAddr, + TermModesArg, + TermSizeArg, + async_context_manager, + construct_disc_error, + encode_env, + get_symbol_names, + ip_address, + lookup_env, + map_handler_name, + parse_byte_count, + parse_time_interval, + split_args, +) +from .packet import ( + Boolean, + Byte, + NameList, + PacketDecodeError, + SSHPacket, + SSHPacketHandler, + SSHPacketLogger, + String, + UInt32, +) from .pattern import WildcardPattern, WildcardPatternList - from .pkcs11 import load_pkcs11_keys - -from .process import PIPE, ProcessSource, ProcessTarget -from .process import SSHServerProcessFactory, SSHCompletedProcess -from .process import SSHClientProcess, SSHServerProcess - -from .public_key import CERT_TYPE_HOST, CERT_TYPE_USER, KeyImportError -from .public_key import CertListArg, IdentityListArg, KeyListArg, SigningKey -from .public_key import KeyPairListArg, X509CertPurposes, SSHKey, SSHKeyPair -from .public_key import SSHCertificate, SSHOpenSSHCertificate -from .public_key import SSHX509Certificate, SSHX509CertificateChain -from .public_key import decode_ssh_public_key, decode_ssh_certificate -from .public_key import get_public_key_algs, get_default_public_key_algs -from .public_key import get_certificate_algs, get_default_certificate_algs -from .public_key import get_x509_certificate_algs -from .public_key import get_default_x509_certificate_algs -from .public_key import load_keypairs, load_default_keypairs -from .public_key import load_public_keys, load_default_host_public_keys -from .public_key import load_certificates -from .public_key import load_identities, load_default_identities - -from .saslprep import saslprep, SASLPrepError - +from .process import ( + PIPE, + ProcessSource, + ProcessTarget, + SSHClientProcess, + SSHCompletedProcess, + SSHServerProcess, + SSHServerProcessFactory, +) +from .public_key import ( + CERT_TYPE_HOST, + CERT_TYPE_USER, + CertListArg, + IdentityListArg, + KeyImportError, + KeyListArg, + KeyPairListArg, + SigningKey, + SSHCertificate, + SSHKey, + SSHKeyPair, + SSHOpenSSHCertificate, + SSHX509Certificate, + SSHX509CertificateChain, + X509CertPurposes, + decode_ssh_certificate, + decode_ssh_public_key, + get_certificate_algs, + get_default_certificate_algs, + get_default_public_key_algs, + get_default_x509_certificate_algs, + get_public_key_algs, + get_x509_certificate_algs, + load_certificates, + load_default_host_public_keys, + load_default_identities, + load_default_keypairs, + load_identities, + load_keypairs, + load_public_keys, +) +from .saslprep import SASLPrepError, saslprep from .server import SSHServer - -from .session import DataType, SSHClientSession, SSHServerSession -from .session import SSHTCPSession, SSHUNIXSession, SSHTunTapSession -from .session import SSHClientSessionFactory, SSHTCPSessionFactory -from .session import SSHUNIXSessionFactory, SSHTunTapSessionFactory - -from .sftp import MIN_SFTP_VERSION, SFTPClient, SFTPServer -from .sftp import start_sftp_client - -from .stream import SSHReader, SSHWriter, SFTPServerFactory -from .stream import SSHSocketSessionFactory, SSHServerSessionFactory -from .stream import SSHClientStreamSession, SSHServerStreamSession -from .stream import SSHTCPStreamSession, SSHUNIXStreamSession -from .stream import SSHTunTapStreamSession - -from .subprocess import SSHSubprocessTransport, SSHSubprocessProtocol -from .subprocess import SubprocessFactory, SSHSubprocessWritePipe - -from .tuntap import SSH_TUN_MODE_POINTTOPOINT, SSH_TUN_MODE_ETHERNET -from .tuntap import SSH_TUN_UNIT_ANY, create_tuntap - +from .session import ( + DataType, + SSHClientSession, + SSHClientSessionFactory, + SSHServerSession, + SSHTCPSession, + SSHTCPSessionFactory, + SSHTunTapSession, + SSHTunTapSessionFactory, + SSHUNIXSession, + SSHUNIXSessionFactory, +) +from .sftp import MIN_SFTP_VERSION, SFTPClient, SFTPServer, start_sftp_client +from .stream import ( + SFTPServerFactory, + SSHClientStreamSession, + SSHReader, + SSHServerSessionFactory, + SSHServerStreamSession, + SSHSocketSessionFactory, + SSHTCPStreamSession, + SSHTunTapStreamSession, + SSHUNIXStreamSession, + SSHWriter, +) +from .subprocess import ( + SSHSubprocessProtocol, + SSHSubprocessTransport, + SSHSubprocessWritePipe, + SubprocessFactory, +) +from .tuntap import ( + SSH_TUN_MODE_ETHERNET, + SSH_TUN_MODE_POINTTOPOINT, + SSH_TUN_UNIT_ANY, + create_tuntap, +) from .version import __version__ - -from .x11 import SSHX11ClientForwarder -from .x11 import SSHX11ClientListener, SSHX11ServerListener -from .x11 import create_x11_client_listener, create_x11_server_listener +from .x11 import ( + SSHX11ClientForwarder, + SSHX11ClientListener, + SSHX11ServerListener, + create_x11_client_listener, + create_x11_server_listener, +) if TYPE_CHECKING: # pylint: disable=unused-import diff --git a/asyncssh/crypto/__init__.py b/asyncssh/crypto/__init__.py index 081f5db4..ca9fbed4 100644 --- a/asyncssh/crypto/__init__.py +++ b/asyncssh/crypto/__init__.py @@ -20,31 +20,28 @@ """A shim for accessing cryptographic primitives needed by asyncssh""" -from .cipher import BasicCipher, GCMCipher, register_cipher, get_cipher_params - -from .dsa import DSAPrivateKey, DSAPublicKey - +# Import chacha20-poly1305 cipher if available +from .chacha import ChachaCipher, chacha_available +from .cipher import BasicCipher, GCMCipher, get_cipher_params, register_cipher from .dh import DH - -from .ec import ECDSAPrivateKey, ECDSAPublicKey, ECDH - -from .ed import ed25519_available, ed448_available -from .ed import curve25519_available, curve448_available -from .ed import EdDSAPrivateKey, EdDSAPublicKey, Curve25519DH, Curve448DH - +from .dsa import DSAPrivateKey, DSAPublicKey +from .ec import ECDH, ECDSAPrivateKey, ECDSAPublicKey from .ec_params import lookup_ec_curve_by_params - +from .ed import ( + Curve448DH, + Curve25519DH, + EdDSAPrivateKey, + EdDSAPublicKey, + curve448_available, + curve25519_available, + ed448_available, + ed25519_available, +) from .kdf import pbkdf2_hmac - from .misc import CryptoKey, PyCAKey - +from .pq import MLKEM, SNTRUP, PQClass, mlkem_available, sntrup_available from .rsa import RSAPrivateKey, RSAPublicKey -from .pq import mlkem_available, sntrup_available, PQClass, MLKEM, SNTRUP - -# Import chacha20-poly1305 cipher if available -from .chacha import ChachaCipher, chacha_available - # Import umac cryptographic hash if available try: from .umac import umac32, umac64, umac96, umac128 @@ -53,8 +50,13 @@ # Import X.509 certificate support if available try: - from .x509 import X509Certificate, X509Name, X509NamePattern - from .x509 import generate_x509_certificate, import_x509_certificate + from .x509 import ( + X509Certificate, + X509Name, + X509NamePattern, + generate_x509_certificate, + import_x509_certificate, + ) except (ImportError, AttributeError): # pragma: no cover pass diff --git a/asyncssh/crypto/chacha.py b/asyncssh/crypto/chacha.py index 44b82b15..e60c33c2 100644 --- a/asyncssh/crypto/chacha.py +++ b/asyncssh/crypto/chacha.py @@ -30,7 +30,6 @@ from .cipher import register_cipher - chacha_available = backend.poly1305_supported() diff --git a/asyncssh/crypto/cipher.py b/asyncssh/crypto/cipher.py index cdbba6a1..1a1a48db 100644 --- a/asyncssh/crypto/cipher.py +++ b/asyncssh/crypto/cipher.py @@ -20,17 +20,16 @@ """A shim around PyCA for accessing symmetric ciphers needed by AsyncSSH""" +import warnings from types import ModuleType from typing import Any, MutableMapping, Optional, Tuple -import warnings +import cryptography.hazmat.primitives.ciphers.algorithms as _algs from cryptography.exceptions import InvalidTag from cryptography.hazmat.primitives.ciphers import Cipher, CipherContext from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.ciphers.modes import CBC, CTR -import cryptography.hazmat.primitives.ciphers.algorithms as _algs - _decrepit_algs: Optional[ModuleType] try: diff --git a/asyncssh/crypto/dsa.py b/asyncssh/crypto/dsa.py index befb5441..61967c36 100644 --- a/asyncssh/crypto/dsa.py +++ b/asyncssh/crypto/dsa.py @@ -27,7 +27,6 @@ from .misc import CryptoKey, PyCAKey, hashes - # Short variable names are used here, matching names in the spec # pylint: disable=invalid-name diff --git a/asyncssh/crypto/ec.py b/asyncssh/crypto/ec.py index c8626570..ba7e7a96 100644 --- a/asyncssh/crypto/ec.py +++ b/asyncssh/crypto/ec.py @@ -24,12 +24,10 @@ from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric import ec -from cryptography.hazmat.primitives.serialization import Encoding -from cryptography.hazmat.primitives.serialization import PublicFormat +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from .misc import CryptoKey, PyCAKey, hashes - # Short variable names are used here, matching names in the spec # pylint: disable=invalid-name diff --git a/asyncssh/crypto/ed.py b/asyncssh/crypto/ed.py index 319c932b..b02f8c16 100644 --- a/asyncssh/crypto/ed.py +++ b/asyncssh/crypto/ed.py @@ -24,12 +24,10 @@ from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends.openssl import backend -from cryptography.hazmat.primitives.asymmetric import ed25519, ed448 -from cryptography.hazmat.primitives.asymmetric import x25519, x448 +from cryptography.hazmat.primitives.asymmetric import ed448, ed25519, x448, x25519 from .misc import CryptoKey, PyCAKey - _EdPrivateKey = Union[ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey] _EdPublicKey = Union[ed25519.Ed25519PublicKey, ed448.Ed448PublicKey] diff --git a/asyncssh/crypto/misc.py b/asyncssh/crypto/misc.py index 4fc2ce2f..a70ba6a4 100644 --- a/asyncssh/crypto/misc.py +++ b/asyncssh/crypto/misc.py @@ -22,12 +22,16 @@ from typing import Callable, Mapping, Union -from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa -from cryptography.hazmat.primitives.asymmetric import ed25519, ed448 -from cryptography.hazmat.primitives.hashes import HashAlgorithm -from cryptography.hazmat.primitives.hashes import MD5, SHA1, SHA224 -from cryptography.hazmat.primitives.hashes import SHA256, SHA384, SHA512 - +from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed448, ed25519, rsa +from cryptography.hazmat.primitives.hashes import ( + MD5, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512, + HashAlgorithm, +) PyCAPrivateKey = Union[dsa.DSAPrivateKey, rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey, diff --git a/asyncssh/crypto/rsa.py b/asyncssh/crypto/rsa.py index 66a2774c..0aa94a67 100644 --- a/asyncssh/crypto/rsa.py +++ b/asyncssh/crypto/rsa.py @@ -23,13 +23,11 @@ from typing import Optional, cast from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP -from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP, PKCS1v15 from .misc import CryptoKey, PyCAKey, hashes - # Short variable names are used here, matching names in the spec # pylint: disable=invalid-name diff --git a/asyncssh/crypto/umac.py b/asyncssh/crypto/umac.py index 981be411..ad35b0f0 100644 --- a/asyncssh/crypto/umac.py +++ b/asyncssh/crypto/umac.py @@ -25,7 +25,6 @@ import ctypes.util from typing import TYPE_CHECKING, Callable, Optional - if TYPE_CHECKING: _ByteArray = ctypes.Array[ctypes.c_char] _SetKey = Callable[[_ByteArray, bytes], None] diff --git a/asyncssh/crypto/x509.py b/asyncssh/crypto/x509.py index 14f91ae2..5e2fe565 100644 --- a/asyncssh/crypto/x509.py +++ b/asyncssh/crypto/x509.py @@ -20,23 +20,19 @@ """A shim around PyCA and PyOpenSSL for X.509 certificates""" -from datetime import datetime, timezone import re import sys +from datetime import datetime, timezone from typing import Iterable, List, Optional, Sequence, Set, Union, cast -from cryptography.hazmat.primitives.serialization import Encoding -from cryptography.hazmat.primitives.serialization import PublicFormat from cryptography import x509 - +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from OpenSSL import crypto from ..asn1 import IA5String, der_decode, der_encode from ..misc import ip_address - from .misc import PyCAKey, PyCAPrivateKey, PyCAPublicKey, hashes - _Comment = Union[None, bytes, str] _Principals = Union[str, Sequence[str]] _Purposes = Union[None, str, Sequence[str]] diff --git a/asyncssh/dsa.py b/asyncssh/dsa.py index e312aa8f..63abfd3b 100644 --- a/asyncssh/dsa.py +++ b/asyncssh/dsa.py @@ -22,14 +22,18 @@ from typing import Optional, Tuple, Union, cast -from .asn1 import ASN1DecodeError, ObjectIdentifier, der_encode, der_decode +from .asn1 import ASN1DecodeError, ObjectIdentifier, der_decode, der_encode from .crypto import DSAPrivateKey, DSAPublicKey from .misc import all_ints -from .packet import MPInt, String, SSHPacket -from .public_key import SSHKey, SSHOpenSSHCertificateV01, KeyExportError -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_x509_certificate_alg - +from .packet import MPInt, SSHPacket, String +from .public_key import ( + KeyExportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_x509_certificate_alg, +) _PrivateKeyArgs = Tuple[int, int, int, int, int] _PublicKeyArgs = Tuple[int, int, int, int] diff --git a/asyncssh/ecdsa.py b/asyncssh/ecdsa.py index 9429deb3..ddd044cd 100644 --- a/asyncssh/ecdsa.py +++ b/asyncssh/ecdsa.py @@ -22,16 +22,30 @@ from typing import Dict, Optional, Tuple, Union, cast -from .asn1 import ASN1DecodeError, BitString, ObjectIdentifier, TaggedDERObject -from .asn1 import der_encode, der_decode -from .crypto import CryptoKey, ECDSAPrivateKey, ECDSAPublicKey -from .crypto import lookup_ec_curve_by_params -from .packet import MPInt, String, SSHPacket -from .public_key import SSHKey, SSHOpenSSHCertificateV01 -from .public_key import KeyImportError, KeyExportError -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_x509_certificate_alg - +from .asn1 import ( + ASN1DecodeError, + BitString, + ObjectIdentifier, + TaggedDERObject, + der_decode, + der_encode, +) +from .crypto import ( + CryptoKey, + ECDSAPrivateKey, + ECDSAPublicKey, + lookup_ec_curve_by_params, +) +from .packet import MPInt, SSHPacket, String +from .public_key import ( + KeyExportError, + KeyImportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_x509_certificate_alg, +) _PrivateKeyArgs = Tuple[bytes, Union[bytes, int], bytes] _PublicKeyArgs = Tuple[bytes, bytes] diff --git a/asyncssh/eddsa.py b/asyncssh/eddsa.py index c97c33aa..9a12ad1f 100644 --- a/asyncssh/eddsa.py +++ b/asyncssh/eddsa.py @@ -22,15 +22,19 @@ from typing import Optional, Tuple, Union, cast -from .asn1 import ASN1DecodeError, ObjectIdentifier, der_encode, der_decode -from .crypto import EdDSAPrivateKey, EdDSAPublicKey -from .crypto import ed25519_available, ed448_available -from .packet import String, SSHPacket -from .public_key import OMIT, SSHKey, SSHOpenSSHCertificateV01 -from .public_key import KeyImportError, KeyExportError -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_x509_certificate_alg - +from .asn1 import ASN1DecodeError, ObjectIdentifier, der_decode, der_encode +from .crypto import EdDSAPrivateKey, EdDSAPublicKey, ed448_available, ed25519_available +from .packet import SSHPacket, String +from .public_key import ( + OMIT, + KeyExportError, + KeyImportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_x509_certificate_alg, +) _PrivateKeyArgs = Tuple[bytes] _PublicKeyArgs = Tuple[bytes] diff --git a/asyncssh/editor.py b/asyncssh/editor.py index c202357b..3d8c5ae2 100644 --- a/asyncssh/editor.py +++ b/asyncssh/editor.py @@ -21,15 +21,22 @@ """Input line editor""" import re - from functools import partial -from typing import TYPE_CHECKING, Callable, Dict, List -from typing import Optional, Set, Tuple, Union, cast +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + List, + Optional, + Set, + Tuple, + Union, + cast, +) from unicodedata import east_asian_width from .session import DataType - if TYPE_CHECKING: # pylint: disable=cyclic-import from .channel import SSHServerChannel diff --git a/asyncssh/encryption.py b/asyncssh/encryption.py index 1a64d6b2..6199f3e2 100644 --- a/asyncssh/encryption.py +++ b/asyncssh/encryption.py @@ -22,11 +22,10 @@ from typing import Dict, List, Optional, Tuple, Type -from .crypto import BasicCipher, GCMCipher, ChachaCipher, get_cipher_params -from .mac import MAC, get_mac_params, get_mac +from .crypto import BasicCipher, ChachaCipher, GCMCipher, get_cipher_params +from .mac import MAC, get_mac, get_mac_params from .packet import UInt64 - _EncParams = Tuple[int, int, int, int, int, bool] _EncParamsMap = Dict[bytes, Tuple[Type['Encryption'], str]] diff --git a/asyncssh/forward.py b/asyncssh/forward.py index 8470c000..526da1d7 100644 --- a/asyncssh/forward.py +++ b/asyncssh/forward.py @@ -23,13 +23,12 @@ import asyncio import socket from types import TracebackType -from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional -from typing import Type, cast +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Type, cast + from typing_extensions import Self from .misc import ChannelOpenError, SockAddr - if TYPE_CHECKING: # pylint: disable=cyclic-import from .connection import SSHConnection diff --git a/asyncssh/gss.py b/asyncssh/gss.py index 1a4b45e4..14d9d7dd 100644 --- a/asyncssh/gss.py +++ b/asyncssh/gss.py @@ -21,19 +21,17 @@ """GSSAPI wrapper""" import sys - from typing import Optional from .misc import BytesOrStrDict - try: # pylint: disable=unused-import if sys.platform == 'win32': # pragma: no cover - from .gss_win32 import GSSBase, GSSClient, GSSServer, GSSError + from .gss_win32 import GSSBase, GSSClient, GSSError, GSSServer else: - from .gss_unix import GSSBase, GSSClient, GSSServer, GSSError + from .gss_unix import GSSBase, GSSClient, GSSError, GSSServer gss_available = True except ImportError: # pragma: no cover diff --git a/asyncssh/gss_unix.py b/asyncssh/gss_unix.py index 145dec20..a59d4abb 100644 --- a/asyncssh/gss_unix.py +++ b/asyncssh/gss_unix.py @@ -22,8 +22,7 @@ from typing import Optional, Sequence, SupportsBytes, cast -from gssapi import Credentials, Name, NameType, OID -from gssapi import RequirementFlag, SecurityContext +from gssapi import OID, Credentials, Name, NameType, RequirementFlag, SecurityContext from gssapi.exceptions import GSSError from .asn1 import OBJECT_IDENTIFIER diff --git a/asyncssh/gss_win32.py b/asyncssh/gss_win32.py index 0159762e..fd098366 100644 --- a/asyncssh/gss_win32.py +++ b/asyncssh/gss_win32.py @@ -27,17 +27,22 @@ from sspi import ClientAuth, ServerAuth from sspi import error as SSPIError - -from sspicon import ISC_REQ_DELEGATE, ISC_REQ_INTEGRITY, ISC_REQ_MUTUAL_AUTH -from sspicon import ISC_RET_INTEGRITY, ISC_RET_MUTUAL_AUTH -from sspicon import ASC_REQ_INTEGRITY, ASC_REQ_MUTUAL_AUTH -from sspicon import ASC_RET_INTEGRITY, ASC_RET_MUTUAL_AUTH -from sspicon import SECPKG_ATTR_NATIVE_NAMES +from sspicon import ( + ASC_REQ_INTEGRITY, + ASC_REQ_MUTUAL_AUTH, + ASC_RET_INTEGRITY, + ASC_RET_MUTUAL_AUTH, + ISC_REQ_DELEGATE, + ISC_REQ_INTEGRITY, + ISC_REQ_MUTUAL_AUTH, + ISC_RET_INTEGRITY, + ISC_RET_MUTUAL_AUTH, + SECPKG_ATTR_NATIVE_NAMES, +) from .asn1 import ObjectIdentifier, der_encode from .misc import BytesOrStrDict - _krb5_oid = der_encode(ObjectIdentifier('1.2.840.113554.1.2.2')) diff --git a/asyncssh/kex.py b/asyncssh/kex.py index 699fa7cd..5f1342f6 100644 --- a/asyncssh/kex.py +++ b/asyncssh/kex.py @@ -28,7 +28,6 @@ from .misc import HashType from .packet import SSHPacketHandler - if TYPE_CHECKING: # pylint: disable=cyclic-import from .connection import SSHConnection diff --git a/asyncssh/kex_dh.py b/asyncssh/kex_dh.py index b5b66f70..2d060c5d 100644 --- a/asyncssh/kex_dh.py +++ b/asyncssh/kex_dh.py @@ -21,25 +21,37 @@ """SSH Diffie-Hellman, ECDH, and Edwards DH key exchange handlers""" from hashlib import sha1, sha224, sha256, sha384, sha512 -from typing import TYPE_CHECKING, Callable, Mapping, Optional -from typing import Protocol, Type, cast +from typing import TYPE_CHECKING, Callable, Mapping, Optional, Protocol, Type, cast from .constants import DEFAULT_LANG -from .crypto import Curve25519DH, Curve448DH, DH, ECDH, PQClass, MLKEM, SNTRUP -from .crypto import curve25519_available, curve448_available -from .crypto import mlkem_available, sntrup_available +from .crypto import ( + DH, + ECDH, + MLKEM, + SNTRUP, + Curve448DH, + Curve25519DH, + PQClass, + curve448_available, + curve25519_available, + mlkem_available, + sntrup_available, +) from .gss import GSSError -from .kex import Kex, register_kex_alg, register_gss_kex_alg -from .misc import HashType, KeyExchangeFailed, ProtocolError -from .misc import get_symbol_names, run_in_executor -from .packet import Boolean, MPInt, String, UInt32, SSHPacket +from .kex import Kex, register_gss_kex_alg, register_kex_alg +from .misc import ( + HashType, + KeyExchangeFailed, + ProtocolError, + get_symbol_names, + run_in_executor, +) +from .packet import Boolean, MPInt, SSHPacket, String, UInt32 from .public_key import SigningKey, VerifyingKey - if TYPE_CHECKING: # pylint: disable=cyclic-import - from .connection import SSHConnection, SSHClientConnection - from .connection import SSHServerConnection + from .connection import SSHClientConnection, SSHConnection, SSHServerConnection class _ECDHKey(Protocol): diff --git a/asyncssh/kex_rsa.py b/asyncssh/kex_rsa.py index 6f5ea465..564a3618 100644 --- a/asyncssh/kex_rsa.py +++ b/asyncssh/kex_rsa.py @@ -24,18 +24,25 @@ from typing import TYPE_CHECKING, Optional, cast from .kex import Kex, register_kex_alg -from .misc import HashType, KeyExchangeFailed, ProtocolError -from .misc import get_symbol_names, randrange -from .packet import MPInt, String, SSHPacket -from .public_key import KeyImportError, SSHKey -from .public_key import decode_ssh_public_key, generate_private_key +from .misc import ( + HashType, + KeyExchangeFailed, + ProtocolError, + get_symbol_names, + randrange, +) +from .packet import MPInt, SSHPacket, String +from .public_key import ( + KeyImportError, + SSHKey, + decode_ssh_public_key, + generate_private_key, +) from .rsa import RSAKey - if TYPE_CHECKING: # pylint: disable=cyclic-import - from .connection import SSHConnection, SSHClientConnection - from .connection import SSHServerConnection + from .connection import SSHClientConnection, SSHConnection, SSHServerConnection # SSH KEXRSA message values diff --git a/asyncssh/keysign.py b/asyncssh/keysign.py index ffb68a5f..dd69be2e 100644 --- a/asyncssh/keysign.py +++ b/asyncssh/keysign.py @@ -21,14 +21,13 @@ """SSH keysign client""" import asyncio -from pathlib import Path import subprocess +from pathlib import Path from typing import Iterable, Sequence, Union, cast from .misc import FilePath -from .packet import Byte, String, UInt32, PacketDecodeError, SSHPacket -from .public_key import SSHKey, SSHKeyPair, SSHCertificate - +from .packet import Byte, PacketDecodeError, SSHPacket, String, UInt32 +from .public_key import SSHCertificate, SSHKey, SSHKeyPair _KeySignKey = Union[SSHKey, SSHCertificate] KeySignPath = Union[None, bool, FilePath] diff --git a/asyncssh/known_hosts.py b/asyncssh/known_hosts.py index 161028c8..bc54da99 100644 --- a/asyncssh/known_hosts.py +++ b/asyncssh/known_hosts.py @@ -25,10 +25,9 @@ """Parser for SSH known_hosts files""" import binascii -from hashlib import sha1 import hmac -from typing import Callable, Dict, List, Optional -from typing import Sequence, Tuple, Union, cast +from hashlib import sha1 +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union, cast try: from .crypto import X509NamePattern @@ -38,12 +37,17 @@ from .misc import IPAddress, ip_address, read_file from .pattern import HostPatternList -from .public_key import KeyImportError -from .public_key import SSHKey, SSHCertificate, SSHX509Certificate -from .public_key import import_public_key, import_certificate -from .public_key import import_certificate_subject -from .public_key import load_public_keys, load_certificates - +from .public_key import ( + KeyImportError, + SSHCertificate, + SSHKey, + SSHX509Certificate, + import_certificate, + import_certificate_subject, + import_public_key, + load_certificates, + load_public_keys, +) _HostPattern = Union['_PlainHost', '_HashedHost'] _HostEntry = Tuple[Optional[str], Optional[SSHKey], diff --git a/asyncssh/listener.py b/asyncssh/listener.py index e9cc475b..53c44b05 100644 --- a/asyncssh/listener.py +++ b/asyncssh/listener.py @@ -24,21 +24,31 @@ import errno import socket from types import TracebackType -from typing import TYPE_CHECKING, AnyStr, Callable, Generic, List, Optional -from typing import Sequence, Set, Tuple, Type, Union +from typing import ( + TYPE_CHECKING, + AnyStr, + Callable, + Generic, + List, + Optional, + Sequence, + Set, + Tuple, + Type, + Union, +) + from typing_extensions import Self -from .forward import SSHForwarderCoro -from .forward import SSHLocalPortForwarder, SSHLocalPathForwarder +from .forward import SSHForwarderCoro, SSHLocalPathForwarder, SSHLocalPortForwarder from .misc import HostPort, MaybeAwait from .session import SSHTCPSession, SSHUNIXSession from .socks import SSHSOCKSForwarder - if TYPE_CHECKING: # pylint: disable=cyclic-import from .channel import SSHTCPChannel, SSHUNIXChannel - from .connection import SSHConnection, SSHClientConnection + from .connection import SSHClientConnection, SSHConnection _LocalListenerFactory = Callable[[], asyncio.BaseProtocol] diff --git a/asyncssh/logging.py b/asyncssh/logging.py index bdf87cad..cbcecb6a 100644 --- a/asyncssh/logging.py +++ b/asyncssh/logging.py @@ -24,7 +24,6 @@ import logging from typing import MutableMapping, Optional, Tuple, Union, cast - _LogArg = object _ObjDict = MutableMapping[str, object] diff --git a/asyncssh/mac.py b/asyncssh/mac.py index d6dc4af8..f96fe42d 100644 --- a/asyncssh/mac.py +++ b/asyncssh/mac.py @@ -20,9 +20,9 @@ """SSH message authentication handlers""" -from hashlib import md5, sha1, sha224, sha256, sha384, sha512 import hmac -from typing import Dict, Callable, List, Tuple +from hashlib import md5, sha1, sha224, sha256, sha384, sha512 +from typing import Callable, Dict, List, Tuple from .packet import UInt32, UInt64 diff --git a/asyncssh/misc.py b/asyncssh/misc.py index 0ef5f084..84c4cdfb 100644 --- a/asyncssh/misc.py +++ b/asyncssh/misc.py @@ -31,29 +31,54 @@ import socket import sys import time - from datetime import datetime, timezone from pathlib import Path, PurePath from random import SystemRandom from types import TracebackType -from typing import Any, AsyncContextManager, Awaitable, Callable, Dict -from typing import Generator, Generic, IO, Iterator, List, Literal, Mapping -from typing import Sequence, Optional, Protocol, Tuple, Type, TypeVar, Union -from typing import cast, overload - -from .constants import DEFAULT_LANG -from .constants import DISC_COMPRESSION_ERROR, DISC_CONNECTION_LOST -from .constants import DISC_HOST_KEY_NOT_VERIFIABLE, DISC_ILLEGAL_USER_NAME -from .constants import DISC_KEY_EXCHANGE_FAILED, DISC_MAC_ERROR -from .constants import DISC_NO_MORE_AUTH_METHODS_AVAILABLE -from .constants import DISC_PROTOCOL_ERROR, DISC_PROTOCOL_VERSION_NOT_SUPPORTED -from .constants import DISC_SERVICE_NOT_AVAILABLE +from typing import ( + IO, + Any, + AsyncContextManager, + Awaitable, + Callable, + Dict, + Generator, + Generic, + Iterator, + List, + Literal, + Mapping, + Optional, + Protocol, + Sequence, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) + +from .constants import ( + DEFAULT_LANG, + DISC_COMPRESSION_ERROR, + DISC_CONNECTION_LOST, + DISC_HOST_KEY_NOT_VERIFIABLE, + DISC_ILLEGAL_USER_NAME, + DISC_KEY_EXCHANGE_FAILED, + DISC_MAC_ERROR, + DISC_NO_MORE_AUTH_METHODS_AVAILABLE, + DISC_PROTOCOL_ERROR, + DISC_PROTOCOL_VERSION_NOT_SUPPORTED, + DISC_SERVICE_NOT_AVAILABLE, +) _pywin32_available = False if sys.platform == 'win32': # pragma: no cover try: import msvcrt + import win32file import winioctlcon _pywin32_available = True diff --git a/asyncssh/packet.py b/asyncssh/packet.py index d30d74b6..d249f5ee 100644 --- a/asyncssh/packet.py +++ b/asyncssh/packet.py @@ -20,13 +20,20 @@ """SSH packet encoding and decoding functions""" -from typing import Any, Awaitable, Callable, Iterable, Mapping, Optional -from typing import Sequence, Union +from typing import ( + Any, + Awaitable, + Callable, + Iterable, + Mapping, + Optional, + Sequence, + Union, +) from .logging import SSHLogger from .misc import MaybeAwait, plural - _LoggedPacket = Union[bytes, 'SSHPacket'] _PacketHandler = Callable[[Any, int, int, 'SSHPacket'], MaybeAwait[None]] diff --git a/asyncssh/pattern.py b/asyncssh/pattern.py index 7b02e421..627b1690 100644 --- a/asyncssh/pattern.py +++ b/asyncssh/pattern.py @@ -25,7 +25,6 @@ from .misc import IPAddress, ip_network - _HostPattern = Union['WildcardHostPattern', 'CIDRHostPattern'] _AnyPattern = Union['WildcardPattern', _HostPattern] diff --git a/asyncssh/pbe.py b/asyncssh/pbe.py index c536f516..d0d3835f 100644 --- a/asyncssh/pbe.py +++ b/asyncssh/pbe.py @@ -20,15 +20,14 @@ """Asymmetric key password based encryption functions""" -from hashlib import md5, sha1 import os +from hashlib import md5, sha1 from typing import Callable, Dict, Sequence, Tuple, Union -from .asn1 import ASN1DecodeError, ObjectIdentifier, der_encode, der_decode +from .asn1 import ASN1DecodeError, ObjectIdentifier, der_decode, der_encode from .crypto import BasicCipher, get_cipher_params, pbkdf2_hmac from .misc import BytesOrStr, HashType - _Cipher = Union[BasicCipher, '_RFC1423Pad'] _PKCS8CipherHandler = Callable[[object, BytesOrStr, Callable, str], _Cipher] diff --git a/asyncssh/pkcs11.py b/asyncssh/pkcs11.py index 07a6b010..13830e30 100644 --- a/asyncssh/pkcs11.py +++ b/asyncssh/pkcs11.py @@ -25,19 +25,22 @@ try: import pkcs11 - from pkcs11 import Attribute, KeyType, Mechanism, ObjectClass - from pkcs11 import PrivateKey, Token - from pkcs11.util.rsa import encode_rsa_public_key + from pkcs11 import Attribute, KeyType, Mechanism, ObjectClass, PrivateKey, Token from pkcs11.util.ec import encode_ec_public_key + from pkcs11.util.rsa import encode_rsa_public_key pkcs11_available = True except (ImportError, ModuleNotFoundError): # pragma: no cover pkcs11_available = False from .misc import BytesOrStr from .packet import MPInt, String -from .public_key import SSHCertificate, SSHKey, SSHKeyPair -from .public_key import import_certificate_chain, import_public_key - +from .public_key import ( + SSHCertificate, + SSHKey, + SSHKeyPair, + import_certificate_chain, + import_public_key, +) _AttrDict = Dict['Attribute', Union[bool, bytes, str, 'ObjectClass']] _TokenID = Tuple[str, bytes] diff --git a/asyncssh/process.py b/asyncssh/process.py index bf58ca58..c2616ac9 100644 --- a/asyncssh/process.py +++ b/asyncssh/process.py @@ -21,35 +21,65 @@ """SSH process handlers""" import asyncio -from asyncio.subprocess import DEVNULL, PIPE, STDOUT import codecs import inspect import io import os -from pathlib import PurePath import socket import stat +from asyncio.subprocess import DEVNULL, PIPE, STDOUT +from pathlib import PurePath from types import TracebackType -from typing import Any, AnyStr, Awaitable, Callable, Dict, Generic, IO -from typing import Iterable, List, Mapping, Optional, Protocol, Set -from typing import TextIO, Tuple, Type, TypeVar, Union, cast +from typing import ( + IO, + Any, + AnyStr, + Awaitable, + Callable, + Dict, + Generic, + Iterable, + List, + Mapping, + Optional, + Protocol, + Set, + TextIO, + Tuple, + Type, + TypeVar, + Union, + cast, +) + from typing_extensions import Self from .channel import SSHChannel, SSHClientChannel, SSHServerChannel - from .constants import DEFAULT_LANG, EXTENDED_DATA_STDERR - from .logging import SSHLogger - -from .misc import BytesOrStr, Error, MaybeAwait, TermModes, TermSize -from .misc import ProtocolError, Record, open_file, set_terminal_size -from .misc import BreakReceived, SignalReceived, TerminalSizeChanged - +from .misc import ( + BreakReceived, + BytesOrStr, + Error, + MaybeAwait, + ProtocolError, + Record, + SignalReceived, + TerminalSizeChanged, + TermModes, + TermSize, + open_file, + set_terminal_size, +) from .session import DataType - -from .stream import SSHReader, SSHWriter, SSHStreamSession -from .stream import SSHClientStreamSession, SSHServerStreamSession -from .stream import SFTPServerFactory +from .stream import ( + SFTPServerFactory, + SSHClientStreamSession, + SSHReader, + SSHServerStreamSession, + SSHStreamSession, + SSHWriter, +) _AnyStrContra = TypeVar('_AnyStrContra', bytes, str, contravariant=True) diff --git a/asyncssh/public_key.py b/asyncssh/public_key.py index f36111b5..e490cffb 100644 --- a/asyncssh/public_key.py +++ b/asyncssh/public_key.py @@ -26,20 +26,34 @@ import os import re import time - from hashlib import md5, sha1, sha256, sha384, sha512 from pathlib import Path, PurePath -from typing import Callable, Dict, List, Mapping, Optional, Protocol -from typing import Sequence, Set, Tuple, Type, Union, cast +from typing import ( + Callable, + Dict, + List, + Mapping, + Optional, + Protocol, + Sequence, + Set, + Tuple, + Type, + Union, + cast, +) -from .crypto import ed25519_available, ed448_available +from .crypto import ed448_available, ed25519_available from .encryption import Encryption from .sk import sk_available try: # pylint: disable=unused-import - from .crypto import X509Certificate - from .crypto import generate_x509_certificate, import_x509_certificate + from .crypto import ( + X509Certificate, + generate_x509_certificate, + import_x509_certificate, + ) _x509_available = True except ImportError: # pragma: no cover _x509_available = False @@ -50,20 +64,39 @@ except ImportError: # pragma: no cover _bcrypt_available = False -from .asn1 import ASN1DecodeError, BitString, ObjectIdentifier -from .asn1 import der_encode, der_decode, der_decode_partial +from .asn1 import ( + ASN1DecodeError, + BitString, + ObjectIdentifier, + der_decode, + der_decode_partial, + der_encode, +) from .crypto import CryptoKey, PyCAKey -from .encryption import get_encryption_params, get_encryption -from .misc import AbsTime, BytesOrStr, DefTuple, FilePath, IPNetwork -from .misc import ip_network, parse_time, read_file, write_file -from .misc import match_base64, wrap_base64 -from .packet import NameList, String, UInt32, UInt64 -from .packet import PacketDecodeError, SSHPacket -from .pbe import KeyEncryptionError, pkcs1_encrypt, pkcs8_encrypt -from .pbe import pkcs1_decrypt, pkcs8_decrypt +from .encryption import get_encryption, get_encryption_params +from .misc import ( + AbsTime, + BytesOrStr, + DefTuple, + FilePath, + IPNetwork, + ip_network, + match_base64, + parse_time, + read_file, + wrap_base64, + write_file, +) +from .packet import NameList, PacketDecodeError, SSHPacket, String, UInt32, UInt64 +from .pbe import ( + KeyEncryptionError, + pkcs1_decrypt, + pkcs1_encrypt, + pkcs8_decrypt, + pkcs8_encrypt, +) from .sk import SSH_SK_USER_PRESENCE_REQD, sk_get_resident - _Comment = Optional[BytesOrStr] _CertPrincipals = Union[str, Sequence[str]] diff --git a/asyncssh/rsa.py b/asyncssh/rsa.py index 8846a5a1..bcc29bdb 100644 --- a/asyncssh/rsa.py +++ b/asyncssh/rsa.py @@ -22,14 +22,18 @@ from typing import Optional, Tuple, Union, cast -from .asn1 import ASN1DecodeError, ObjectIdentifier, der_encode, der_decode +from .asn1 import ASN1DecodeError, ObjectIdentifier, der_decode, der_encode from .crypto import RSAPrivateKey, RSAPublicKey from .misc import all_ints -from .packet import MPInt, String, SSHPacket -from .public_key import SSHKey, SSHOpenSSHCertificateV01, KeyExportError -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_x509_certificate_alg - +from .packet import MPInt, SSHPacket, String +from .public_key import ( + KeyExportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_x509_certificate_alg, +) _hash_algs = {b'ssh-rsa': 'sha1', b'rsa-sha2-256': 'sha256', diff --git a/asyncssh/saslprep.py b/asyncssh/saslprep.py index b33e44ed..9e19cbb2 100644 --- a/asyncssh/saslprep.py +++ b/asyncssh/saslprep.py @@ -30,9 +30,9 @@ # The stringprep module should not be flagged as deprecated # pylint: disable=deprecated-module import stringprep + # pylint: enable=deprecated-module import unicodedata - from typing import Callable, Literal, Optional, Sequence diff --git a/asyncssh/scp.py b/asyncssh/scp.py index 50833450..7b65ede8 100644 --- a/asyncssh/scp.py +++ b/asyncssh/scp.py @@ -25,25 +25,52 @@ import argparse import asyncio import inspect -from pathlib import PurePath import posixpath import shlex import string import sys +from pathlib import PurePath from types import TracebackType -from typing import TYPE_CHECKING, AsyncIterator, List, NoReturn, Optional -from typing import Protocol, Sequence, Tuple, Type, Union, cast +from typing import ( + TYPE_CHECKING, + AsyncIterator, + List, + NoReturn, + Optional, + Protocol, + Sequence, + Tuple, + Type, + Union, + cast, +) + from typing_extensions import Self -from .constants import DEFAULT_LANG -from .constants import FILEXFER_TYPE_REGULAR, FILEXFER_TYPE_DIRECTORY +from .constants import DEFAULT_LANG, FILEXFER_TYPE_DIRECTORY, FILEXFER_TYPE_REGULAR from .logging import SSHLogger -from .misc import BytesOrStr, FilePath, HostPort, MaybeAwait -from .misc import async_context_manager, plural -from .sftp import SFTPAttrs, SFTPGlob, SFTPName, SFTPServer, SFTPServerFS -from .sftp import SFTPError, SFTPFailure, SFTPBadMessage, SFTPConnectionLost -from .sftp import SFTPErrorHandler, SFTPProgressHandler, local_fs - +from .misc import ( + BytesOrStr, + FilePath, + HostPort, + MaybeAwait, + async_context_manager, + plural, +) +from .sftp import ( + SFTPAttrs, + SFTPBadMessage, + SFTPConnectionLost, + SFTPError, + SFTPErrorHandler, + SFTPFailure, + SFTPGlob, + SFTPName, + SFTPProgressHandler, + SFTPServer, + SFTPServerFS, + local_fs, +) if TYPE_CHECKING: # pylint: disable=cyclic-import diff --git a/asyncssh/server.py b/asyncssh/server.py index 2e033e48..2750ec58 100644 --- a/asyncssh/server.py +++ b/asyncssh/server.py @@ -26,17 +26,23 @@ from .listener import SSHListener from .misc import MaybeAwait from .public_key import SSHKey -from .stream import SSHSocketSessionFactory, SSHServerSessionFactory - +from .stream import SSHServerSessionFactory, SSHSocketSessionFactory if TYPE_CHECKING: # pylint: disable=cyclic-import - from .connection import SSHClientConnection, SSHServerConnection - from .connection import SSHAcceptHandler - from .channel import SSHServerChannel, SSHTCPChannel, SSHUNIXChannel - from .channel import SSHTunTapChannel - from .session import SSHServerSession, SSHTCPSession, SSHUNIXSession - from .session import SSHTunTapSession + from .channel import ( + SSHServerChannel, + SSHTCPChannel, + SSHTunTapChannel, + SSHUNIXChannel, + ) + from .connection import SSHAcceptHandler, SSHClientConnection, SSHServerConnection + from .session import ( + SSHServerSession, + SSHTCPSession, + SSHTunTapSession, + SSHUNIXSession, + ) _NewSession = Union[ diff --git a/asyncssh/session.py b/asyncssh/session.py index 329975cc..0d1b3843 100644 --- a/asyncssh/session.py +++ b/asyncssh/session.py @@ -20,14 +20,26 @@ """SSH session handlers""" -from typing import TYPE_CHECKING, Any, AnyStr, Callable, Generic -from typing import Mapping, Optional, Tuple - +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Callable, + Generic, + Mapping, + Optional, + Tuple, +) if TYPE_CHECKING: # pylint: disable=cyclic-import - from .channel import SSHClientChannel, SSHServerChannel - from .channel import SSHTCPChannel, SSHUNIXChannel, SSHTunTapChannel + from .channel import ( + SSHClientChannel, + SSHServerChannel, + SSHTCPChannel, + SSHTunTapChannel, + SSHUNIXChannel, + ) DataType = Optional[int] diff --git a/asyncssh/sftp.py b/asyncssh/sftp.py index c2c82982..a8b85873 100644 --- a/asyncssh/sftp.py +++ b/asyncssh/sftp.py @@ -24,95 +24,192 @@ import asyncio import errno -from fnmatch import fnmatch import inspect import os -from os import SEEK_SET, SEEK_CUR, SEEK_END -from pathlib import PurePath import posixpath import stat import sys import time +from fnmatch import fnmatch +from os import SEEK_CUR, SEEK_END, SEEK_SET +from pathlib import PurePath from types import TracebackType -from typing import TYPE_CHECKING, AnyStr, AsyncIterator, Awaitable, Callable -from typing import Dict, Generic, IO, Iterable, List, Literal, Mapping -from typing import Optional, Protocol, Sequence, Set, Tuple, Type, TypeVar -from typing import Union, cast, overload +from typing import ( + IO, + TYPE_CHECKING, + AnyStr, + AsyncIterator, + Awaitable, + Callable, + Dict, + Generic, + Iterable, + List, + Literal, + Mapping, + Optional, + Protocol, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) + from typing_extensions import Self from . import constants -from .constants import DEFAULT_LANG - -from .constants import FXP_INIT, FXP_VERSION, FXP_OPEN, FXP_CLOSE, FXP_READ -from .constants import FXP_WRITE, FXP_LSTAT, FXP_FSTAT, FXP_SETSTAT -from .constants import FXP_FSETSTAT, FXP_OPENDIR, FXP_READDIR, FXP_REMOVE -from .constants import FXP_MKDIR, FXP_RMDIR, FXP_REALPATH, FXP_STAT, FXP_RENAME -from .constants import FXP_READLINK, FXP_SYMLINK, FXP_LINK, FXP_BLOCK -from .constants import FXP_UNBLOCK, FXP_STATUS, FXP_HANDLE, FXP_DATA -from .constants import FXP_NAME, FXP_ATTRS, FXP_EXTENDED, FXP_EXTENDED_REPLY - -from .constants import FXR_OVERWRITE - -from .constants import FXRP_NO_CHECK, FXRP_STAT_IF_EXISTS, FXRP_STAT_ALWAYS - -from .constants import FXF_READ, FXF_WRITE, FXF_APPEND -from .constants import FXF_CREAT, FXF_TRUNC, FXF_EXCL - -from .constants import FXF_ACCESS_DISPOSITION, FXF_CREATE_NEW -from .constants import FXF_CREATE_TRUNCATE, FXF_OPEN_EXISTING -from .constants import FXF_OPEN_OR_CREATE, FXF_TRUNCATE_EXISTING -from .constants import FXF_APPEND_DATA - -from .constants import ACE4_READ_DATA, ACE4_WRITE_DATA, ACE4_APPEND_DATA -from .constants import ACE4_READ_ATTRIBUTES, ACE4_WRITE_ATTRIBUTES - -from .constants import FILEXFER_ATTR_SIZE, FILEXFER_ATTR_UIDGID -from .constants import FILEXFER_ATTR_PERMISSIONS, FILEXFER_ATTR_ACMODTIME -from .constants import FILEXFER_ATTR_EXTENDED, FILEXFER_ATTR_DEFINED_V3 - -from .constants import FILEXFER_ATTR_ACCESSTIME, FILEXFER_ATTR_CREATETIME -from .constants import FILEXFER_ATTR_MODIFYTIME, FILEXFER_ATTR_ACL -from .constants import FILEXFER_ATTR_OWNERGROUP, FILEXFER_ATTR_SUBSECOND_TIMES -from .constants import FILEXFER_ATTR_DEFINED_V4 - -from .constants import FILEXFER_ATTR_BITS, FILEXFER_ATTR_DEFINED_V5 - -from .constants import FILEXFER_ATTR_ALLOCATION_SIZE, FILEXFER_ATTR_TEXT_HINT -from .constants import FILEXFER_ATTR_MIME_TYPE, FILEXFER_ATTR_LINK_COUNT -from .constants import FILEXFER_ATTR_UNTRANSLATED_NAME, FILEXFER_ATTR_CTIME -from .constants import FILEXFER_ATTR_DEFINED_V6 - -from .constants import FX_OK, FX_EOF, FX_NO_SUCH_FILE, FX_PERMISSION_DENIED -from .constants import FX_FAILURE, FX_BAD_MESSAGE, FX_NO_CONNECTION -from .constants import FX_CONNECTION_LOST, FX_OP_UNSUPPORTED, FX_V3_END -from .constants import FX_INVALID_HANDLE, FX_NO_SUCH_PATH -from .constants import FX_FILE_ALREADY_EXISTS, FX_WRITE_PROTECT, FX_NO_MEDIA -from .constants import FX_V4_END, FX_NO_SPACE_ON_FILESYSTEM, FX_QUOTA_EXCEEDED -from .constants import FX_UNKNOWN_PRINCIPAL, FX_LOCK_CONFLICT, FX_V5_END -from .constants import FX_DIR_NOT_EMPTY, FX_NOT_A_DIRECTORY -from .constants import FX_INVALID_FILENAME, FX_LINK_LOOP, FX_CANNOT_DELETE -from .constants import FX_INVALID_PARAMETER, FX_FILE_IS_A_DIRECTORY -from .constants import FX_BYTE_RANGE_LOCK_CONFLICT, FX_BYTE_RANGE_LOCK_REFUSED -from .constants import FX_DELETE_PENDING, FX_FILE_CORRUPT, FX_OWNER_INVALID -from .constants import FX_GROUP_INVALID, FX_NO_MATCHING_BYTE_RANGE_LOCK -from .constants import FX_V6_END - -from .constants import FILEXFER_TYPE_REGULAR, FILEXFER_TYPE_DIRECTORY -from .constants import FILEXFER_TYPE_SYMLINK, FILEXFER_TYPE_SPECIAL -from .constants import FILEXFER_TYPE_UNKNOWN, FILEXFER_TYPE_SOCKET -from .constants import FILEXFER_TYPE_CHAR_DEVICE, FILEXFER_TYPE_BLOCK_DEVICE -from .constants import FILEXFER_TYPE_FIFO - +from .constants import ( + ACE4_APPEND_DATA, + ACE4_READ_ATTRIBUTES, + ACE4_READ_DATA, + ACE4_WRITE_ATTRIBUTES, + ACE4_WRITE_DATA, + DEFAULT_LANG, + FILEXFER_ATTR_ACCESSTIME, + FILEXFER_ATTR_ACL, + FILEXFER_ATTR_ACMODTIME, + FILEXFER_ATTR_ALLOCATION_SIZE, + FILEXFER_ATTR_BITS, + FILEXFER_ATTR_CREATETIME, + FILEXFER_ATTR_CTIME, + FILEXFER_ATTR_DEFINED_V3, + FILEXFER_ATTR_DEFINED_V4, + FILEXFER_ATTR_DEFINED_V5, + FILEXFER_ATTR_DEFINED_V6, + FILEXFER_ATTR_EXTENDED, + FILEXFER_ATTR_LINK_COUNT, + FILEXFER_ATTR_MIME_TYPE, + FILEXFER_ATTR_MODIFYTIME, + FILEXFER_ATTR_OWNERGROUP, + FILEXFER_ATTR_PERMISSIONS, + FILEXFER_ATTR_SIZE, + FILEXFER_ATTR_SUBSECOND_TIMES, + FILEXFER_ATTR_TEXT_HINT, + FILEXFER_ATTR_UIDGID, + FILEXFER_ATTR_UNTRANSLATED_NAME, + FILEXFER_TYPE_BLOCK_DEVICE, + FILEXFER_TYPE_CHAR_DEVICE, + FILEXFER_TYPE_DIRECTORY, + FILEXFER_TYPE_FIFO, + FILEXFER_TYPE_REGULAR, + FILEXFER_TYPE_SOCKET, + FILEXFER_TYPE_SPECIAL, + FILEXFER_TYPE_SYMLINK, + FILEXFER_TYPE_UNKNOWN, + FX_BAD_MESSAGE, + FX_BYTE_RANGE_LOCK_CONFLICT, + FX_BYTE_RANGE_LOCK_REFUSED, + FX_CANNOT_DELETE, + FX_CONNECTION_LOST, + FX_DELETE_PENDING, + FX_DIR_NOT_EMPTY, + FX_EOF, + FX_FAILURE, + FX_FILE_ALREADY_EXISTS, + FX_FILE_CORRUPT, + FX_FILE_IS_A_DIRECTORY, + FX_GROUP_INVALID, + FX_INVALID_FILENAME, + FX_INVALID_HANDLE, + FX_INVALID_PARAMETER, + FX_LINK_LOOP, + FX_LOCK_CONFLICT, + FX_NO_CONNECTION, + FX_NO_MATCHING_BYTE_RANGE_LOCK, + FX_NO_MEDIA, + FX_NO_SPACE_ON_FILESYSTEM, + FX_NO_SUCH_FILE, + FX_NO_SUCH_PATH, + FX_NOT_A_DIRECTORY, + FX_OK, + FX_OP_UNSUPPORTED, + FX_OWNER_INVALID, + FX_PERMISSION_DENIED, + FX_QUOTA_EXCEEDED, + FX_UNKNOWN_PRINCIPAL, + FX_V3_END, + FX_V4_END, + FX_V5_END, + FX_V6_END, + FX_WRITE_PROTECT, + FXF_ACCESS_DISPOSITION, + FXF_APPEND, + FXF_APPEND_DATA, + FXF_CREAT, + FXF_CREATE_NEW, + FXF_CREATE_TRUNCATE, + FXF_EXCL, + FXF_OPEN_EXISTING, + FXF_OPEN_OR_CREATE, + FXF_READ, + FXF_TRUNC, + FXF_TRUNCATE_EXISTING, + FXF_WRITE, + FXP_ATTRS, + FXP_BLOCK, + FXP_CLOSE, + FXP_DATA, + FXP_EXTENDED, + FXP_EXTENDED_REPLY, + FXP_FSETSTAT, + FXP_FSTAT, + FXP_HANDLE, + FXP_INIT, + FXP_LINK, + FXP_LSTAT, + FXP_MKDIR, + FXP_NAME, + FXP_OPEN, + FXP_OPENDIR, + FXP_READ, + FXP_READDIR, + FXP_READLINK, + FXP_REALPATH, + FXP_REMOVE, + FXP_RENAME, + FXP_RMDIR, + FXP_SETSTAT, + FXP_STAT, + FXP_STATUS, + FXP_SYMLINK, + FXP_UNBLOCK, + FXP_VERSION, + FXP_WRITE, + FXR_OVERWRITE, + FXRP_NO_CHECK, + FXRP_STAT_ALWAYS, + FXRP_STAT_IF_EXISTS, +) from .logging import SSHLogger - -from .misc import BytesOrStr, Error, FilePath, MaybeAwait, OptExcInfo, Record -from .misc import ConnectionLost -from .misc import async_context_manager, get_symbol_names, hide_empty -from .misc import make_sparse_file, plural - -from .packet import Boolean, Byte, String, UInt16, UInt32, UInt64 -from .packet import PacketDecodeError, SSHPacket, SSHPacketLogger - +from .misc import ( + BytesOrStr, + ConnectionLost, + Error, + FilePath, + MaybeAwait, + OptExcInfo, + Record, + async_context_manager, + get_symbol_names, + hide_empty, + make_sparse_file, + plural, +) +from .packet import ( + Boolean, + Byte, + PacketDecodeError, + SSHPacket, + SSHPacketLogger, + String, + UInt16, + UInt32, + UInt64, +) from .version import __author__, __version__ _pywin32_available = False @@ -120,6 +217,7 @@ if sys.platform == 'win32': # pragma: no cover try: import msvcrt + import pywintypes import win32file import winerror diff --git a/asyncssh/sk.py b/asyncssh/sk.py index 8889d5fe..97bc53d1 100644 --- a/asyncssh/sk.py +++ b/asyncssh/sk.py @@ -20,14 +20,22 @@ """U2F security key handler""" -from base64 import urlsafe_b64encode import ctypes -from hashlib import sha256 import hmac import time -from typing import Callable, List, Mapping, NoReturn, Optional -from typing import Sequence, Tuple, TypeVar, cast - +from base64 import urlsafe_b64encode +from hashlib import sha256 +from typing import ( + Callable, + List, + Mapping, + NoReturn, + Optional, + Sequence, + Tuple, + TypeVar, + cast, +) _PollResult = TypeVar('_PollResult') _SKResidentKey = Tuple[int, str, bytes, bytes] @@ -335,9 +343,8 @@ def sk_get_resident(application: str, user: Optional[str], try: from fido2.client import DefaultClientDataCollector from fido2.ctap import CtapError - from fido2.ctap1 import Ctap1, APDU, ApduError - from fido2.ctap2 import Ctap2, ClientPin, PinProtocolV1 - from fido2.ctap2 import CredentialManagement + from fido2.ctap1 import APDU, ApduError, Ctap1 + from fido2.ctap2 import ClientPin, CredentialManagement, Ctap2, PinProtocolV1 from fido2.hid import CtapHidDevice sk_available = True diff --git a/asyncssh/sk_ecdsa.py b/asyncssh/sk_ecdsa.py index 95790bae..a297753c 100644 --- a/asyncssh/sk_ecdsa.py +++ b/asyncssh/sk_ecdsa.py @@ -23,15 +23,25 @@ from hashlib import sha256 from typing import Optional, Tuple, cast -from .asn1 import der_encode, der_decode +from .asn1 import der_decode, der_encode from .crypto import ECDSAPublicKey -from .packet import Byte, MPInt, String, UInt32, SSHPacket -from .public_key import KeyExportError, SSHKey, SSHOpenSSHCertificateV01 -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_sk_alg -from .sk import SSH_SK_ECDSA, SSH_SK_USER_PRESENCE_REQD -from .sk import sk_enroll, sk_sign, sk_webauthn_prefix, sk_use_webauthn - +from .packet import Byte, MPInt, SSHPacket, String, UInt32 +from .public_key import ( + KeyExportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_sk_alg, +) +from .sk import ( + SSH_SK_ECDSA, + SSH_SK_USER_PRESENCE_REQD, + sk_enroll, + sk_sign, + sk_use_webauthn, + sk_webauthn_prefix, +) _PrivateKeyArgs = Tuple[bytes, bytes, str, int, bytes, bytes] _PublicKeyArgs = Tuple[bytes, bytes, str] diff --git a/asyncssh/sk_eddsa.py b/asyncssh/sk_eddsa.py index c25aad67..28201e5f 100644 --- a/asyncssh/sk_eddsa.py +++ b/asyncssh/sk_eddsa.py @@ -24,13 +24,17 @@ from typing import Optional, Tuple, cast from .crypto import EdDSAPublicKey, ed25519_available -from .packet import Byte, String, UInt32, SSHPacket -from .public_key import KeyExportError, SSHKey, SSHOpenSSHCertificateV01 -from .public_key import register_public_key_alg, register_certificate_alg -from .public_key import register_sk_alg +from .packet import Byte, SSHPacket, String, UInt32 +from .public_key import ( + KeyExportError, + SSHKey, + SSHOpenSSHCertificateV01, + register_certificate_alg, + register_public_key_alg, + register_sk_alg, +) from .sk import SSH_SK_ED25519, SSH_SK_USER_PRESENCE_REQD, sk_enroll, sk_sign - _PrivateKeyArgs = Tuple[bytes, str, int, bytes, bytes] _PublicKeyArgs = Tuple[bytes, str] diff --git a/asyncssh/socks.py b/asyncssh/socks.py index 960cda60..6c585472 100644 --- a/asyncssh/socks.py +++ b/asyncssh/socks.py @@ -26,7 +26,6 @@ from .forward import SSHForwarderCoro, SSHLocalForwarder from .session import DataType - if TYPE_CHECKING: # pylint: disable=cyclic-import from .connection import SSHConnection diff --git a/asyncssh/sshsig.py b/asyncssh/sshsig.py index 8a76a4b5..0b0c7f56 100644 --- a/asyncssh/sshsig.py +++ b/asyncssh/sshsig.py @@ -23,20 +23,33 @@ import binascii import time - from hashlib import sha256, sha512 from pathlib import PurePath from typing import List, Optional, Sequence, Union, cast -from .misc import BytesOrFilePath, FilePath, OptionsParser -from .misc import open_file, read_file, match_base64, wrap_base64, parse_time -from .packet import String, UInt32, PacketDecodeError, SSHPacket +from .misc import ( + BytesOrFilePath, + FilePath, + OptionsParser, + match_base64, + open_file, + parse_time, + read_file, + wrap_base64, +) +from .packet import PacketDecodeError, SSHPacket, String, UInt32 from .pattern import WildcardPatternList -from .public_key import CERT_TYPE_ANY, KeyImportError, KeyPairListArg -from .public_key import SSHKey, SSHOpenSSHCertificate -from .public_key import decode_ssh_public_key, decode_ssh_certificate -from .public_key import import_public_key, load_keypairs - +from .public_key import ( + CERT_TYPE_ANY, + KeyImportError, + KeyPairListArg, + SSHKey, + SSHOpenSSHCertificate, + decode_ssh_certificate, + decode_ssh_public_key, + import_public_key, + load_keypairs, +) _SSHSIG_MAGIC = b'SSHSIG' _SSHSIG_VERSION = 1 diff --git a/asyncssh/stream.py b/asyncssh/stream.py index 247a75da..52642dd7 100644 --- a/asyncssh/stream.py +++ b/asyncssh/stream.py @@ -23,19 +23,43 @@ import asyncio import inspect import re -from typing import TYPE_CHECKING, Any, AnyStr, AsyncIterator -from typing import Callable, Dict, Generic, Iterable, List -from typing import Optional, Pattern, Set, Tuple, Union, cast +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + AsyncIterator, + Callable, + Dict, + Generic, + Iterable, + List, + Optional, + Pattern, + Set, + Tuple, + Union, + cast, +) from .constants import EXTENDED_DATA_STDERR from .logging import SSHLogger -from .misc import MaybeAwait, BreakReceived, SignalReceived -from .misc import SoftEOFReceived, TerminalSizeChanged -from .session import DataType, SSHClientSession, SSHServerSession -from .session import SSHTCPSession, SSHUNIXSession, SSHTunTapSession -from .sftp import SFTPServer, run_sftp_server +from .misc import ( + BreakReceived, + MaybeAwait, + SignalReceived, + SoftEOFReceived, + TerminalSizeChanged, +) from .scp import run_scp_server - +from .session import ( + DataType, + SSHClientSession, + SSHServerSession, + SSHTCPSession, + SSHTunTapSession, + SSHUNIXSession, +) +from .sftp import SFTPServer, run_sftp_server if TYPE_CHECKING: # pylint: disable=cyclic-import diff --git a/asyncssh/subprocess.py b/asyncssh/subprocess.py index 3b1c30fb..5163867e 100644 --- a/asyncssh/subprocess.py +++ b/asyncssh/subprocess.py @@ -20,14 +20,21 @@ """SSH subprocess handlers""" -from typing import TYPE_CHECKING, Any, AnyStr, Callable -from typing import Dict, Generic, Iterable, Optional +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Callable, + Dict, + Generic, + Iterable, + Optional, +) from .constants import EXTENDED_DATA_STDERR from .process import SSHClientProcess from .session import DataType - if TYPE_CHECKING: # pylint: disable=cyclic-import from .channel import SSHChannel, SSHClientChannel diff --git a/asyncssh/tuntap.py b/asyncssh/tuntap.py index 63130ed3..c4765dd2 100644 --- a/asyncssh/tuntap.py +++ b/asyncssh/tuntap.py @@ -27,7 +27,6 @@ import struct import sys import threading - from typing import Callable, Optional, Tuple, cast if sys.platform != 'win32': # pragma: no branch diff --git a/asyncssh/x11.py b/asyncssh/x11.py index 5853ae7f..1ef800b7 100644 --- a/asyncssh/x11.py +++ b/asyncssh/x11.py @@ -22,11 +22,20 @@ import asyncio import os -from pathlib import Path import socket import time -from typing import TYPE_CHECKING, Callable, Dict, Iterable -from typing import NamedTuple, Optional, Sequence, Set, Tuple +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + Iterable, + NamedTuple, + Optional, + Sequence, + Set, + Tuple, +) from .constants import OPEN_CONNECT_FAILED from .forward import SSHForwarder, SSHForwarderCoro @@ -35,7 +44,6 @@ from .misc import ChannelOpenError from .session import DataType - if TYPE_CHECKING: # pylint: disable=cyclic-import from .channel import SSHChannel diff --git a/docs/conf.py b/docs/conf.py index f36e3e80..278b605c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -12,7 +12,8 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os +import os +import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the diff --git a/examples/callback_client.py b/examples/callback_client.py index 671011f9..142ff375 100755 --- a/examples/callback_client.py +++ b/examples/callback_client.py @@ -20,9 +20,13 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys from typing import Optional +import asyncssh + + class MySSHClientSession(asyncssh.SSHClientSession): def data_received(self, data: str, datatype: asyncssh.DataType) -> None: print(data, end='') diff --git a/examples/callback_client2.py b/examples/callback_client2.py index 131c1eca..a5a3d904 100755 --- a/examples/callback_client2.py +++ b/examples/callback_client2.py @@ -20,9 +20,13 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys from typing import Optional +import asyncssh + + class MySSHClientSession(asyncssh.SSHClientSession): def data_received(self, data: str, datatype: asyncssh.DataType) -> None: print(data, end='') diff --git a/examples/callback_client3.py b/examples/callback_client3.py index d76d3158..f353f063 100755 --- a/examples/callback_client3.py +++ b/examples/callback_client3.py @@ -20,9 +20,13 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys from typing import Optional +import asyncssh + + class MySSHClientSession(asyncssh.SSHClientSession): def data_received(self, data: str, datatype: asyncssh.DataType) -> None: if datatype == asyncssh.EXTENDED_DATA_STDERR: diff --git a/examples/callback_math_server.py b/examples/callback_math_server.py index 9827717d..3da87769 100755 --- a/examples/callback_math_server.py +++ b/examples/callback_math_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + class MySSHServerSession(asyncssh.SSHServerSession): def __init__(self): diff --git a/examples/chat_server.py b/examples/chat_server.py index 042dd211..e9fdad0c 100755 --- a/examples/chat_server.py +++ b/examples/chat_server.py @@ -27,9 +27,13 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys from typing import List, cast +import asyncssh + + class ChatClient: _clients: List['ChatClient'] = [] diff --git a/examples/check_exit_status.py b/examples/check_exit_status.py index c404695e..4f5d3e55 100755 --- a/examples/check_exit_status.py +++ b/examples/check_exit_status.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/chroot_sftp_server.py b/examples/chroot_sftp_server.py index eed52932..a70babb4 100755 --- a/examples/chroot_sftp_server.py +++ b/examples/chroot_sftp_server.py @@ -27,7 +27,12 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, os, sys +import asyncio +import os +import sys + +import asyncssh + class MySFTPServer(asyncssh.SFTPServer): def __init__(self, chan: asyncssh.SSHServerChannel): diff --git a/examples/direct_client.py b/examples/direct_client.py index 0de0bb89..d831b483 100755 --- a/examples/direct_client.py +++ b/examples/direct_client.py @@ -20,9 +20,13 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys from typing import Optional +import asyncssh + + class MySSHTCPSession(asyncssh.SSHTCPSession): def data_received(self, data: bytes, datatype: asyncssh.DataType) -> None: # We use sys.stdout.buffer here because we're writing bytes diff --git a/examples/direct_server.py b/examples/direct_server.py index daeda01b..cf63569f 100755 --- a/examples/direct_server.py +++ b/examples/direct_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + class MySSHTCPSession(asyncssh.SSHTCPSession): def connection_made(self, chan: asyncssh.SSHTCPChannel) -> None: diff --git a/examples/editor.py b/examples/editor.py index f87816cd..28d4bb89 100755 --- a/examples/editor.py +++ b/examples/editor.py @@ -27,9 +27,13 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys from typing import cast +import asyncssh + + async def handle_client(process: asyncssh.SSHServerProcess): channel = cast(asyncssh.SSHLineEditorChannel, process.channel) diff --git a/examples/gather_results.py b/examples/gather_results.py index 4ff519c5..c3b99f05 100755 --- a/examples/gather_results.py +++ b/examples/gather_results.py @@ -20,7 +20,10 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh +import asyncio + +import asyncssh + async def run_client(host, command: str) -> asyncssh.SSHCompletedProcess: async with asyncssh.connect(host) as conn: diff --git a/examples/listening_client.py b/examples/listening_client.py index 72c9b2f2..541d95b5 100755 --- a/examples/listening_client.py +++ b/examples/listening_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + class MySSHTCPSession(asyncssh.SSHTCPSession): def connection_made(self, chan: asyncssh.SSHTCPChannel) -> None: diff --git a/examples/local_forwarding_client.py b/examples/local_forwarding_client.py index 4466e98a..3e1dc6a1 100755 --- a/examples/local_forwarding_client.py +++ b/examples/local_forwarding_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/local_forwarding_client2.py b/examples/local_forwarding_client2.py index e8314030..a1e7fab4 100755 --- a/examples/local_forwarding_client2.py +++ b/examples/local_forwarding_client2.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/local_forwarding_server.py b/examples/local_forwarding_server.py index c32d58e4..69102bb1 100755 --- a/examples/local_forwarding_server.py +++ b/examples/local_forwarding_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + class MySSHServer(asyncssh.SSHServer): def connection_requested(self, dest_host: str, dest_port: int, diff --git a/examples/math_client.py b/examples/math_client.py index ecf3e2ab..5a0fd071 100755 --- a/examples/math_client.py +++ b/examples/math_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/math_server.py b/examples/math_server.py index bbc0b1af..8560398f 100755 --- a/examples/math_server.py +++ b/examples/math_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def handle_client(process: asyncssh.SSHServerProcess) -> None: process.stdout.write('Enter numbers one per line, or EOF when done:\n') diff --git a/examples/redirect_input.py b/examples/redirect_input.py index ef5cd7f2..b98f7d81 100755 --- a/examples/redirect_input.py +++ b/examples/redirect_input.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/redirect_local_pipe.py b/examples/redirect_local_pipe.py index 0daf8571..f08b9405 100755 --- a/examples/redirect_local_pipe.py +++ b/examples/redirect_local_pipe.py @@ -20,7 +20,12 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, subprocess, sys +import asyncio +import subprocess +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/redirect_remote_pipe.py b/examples/redirect_remote_pipe.py index b6aea2c3..604dc58e 100755 --- a/examples/redirect_remote_pipe.py +++ b/examples/redirect_remote_pipe.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/redirect_server.py b/examples/redirect_server.py index 7bd15f7f..36ad4e05 100755 --- a/examples/redirect_server.py +++ b/examples/redirect_server.py @@ -27,7 +27,12 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, subprocess, sys +import asyncio +import subprocess +import sys + +import asyncssh + async def handle_client(process: asyncssh.SSHServerProcess) -> None: bc_proc = subprocess.Popen('bc', shell=True, stdin=subprocess.PIPE, diff --git a/examples/remote_forwarding_client.py b/examples/remote_forwarding_client.py index 8d66b446..fd6ad4a3 100755 --- a/examples/remote_forwarding_client.py +++ b/examples/remote_forwarding_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/remote_forwarding_client2.py b/examples/remote_forwarding_client2.py index 0ae60ecb..bbaf0172 100755 --- a/examples/remote_forwarding_client2.py +++ b/examples/remote_forwarding_client2.py @@ -20,10 +20,14 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys from functools import partial from typing import Awaitable +import asyncssh + + def connection_requested(conn: asyncssh.SSHClientConnection, orig_host: str, orig_port: int) -> Awaitable[asyncssh.SSHForwarder]: if orig_host in ('127.0.0.1', '::1'): diff --git a/examples/remote_forwarding_server.py b/examples/remote_forwarding_server.py index 40e04e79..495704aa 100755 --- a/examples/remote_forwarding_server.py +++ b/examples/remote_forwarding_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + class MySSHServer(asyncssh.SSHServer): def server_requested(self, listen_host: str, listen_port: int) -> bool: diff --git a/examples/reverse_client.py b/examples/reverse_client.py index 1ac27a3e..3a8911be 100755 --- a/examples/reverse_client.py +++ b/examples/reverse_client.py @@ -30,9 +30,13 @@ # trusted to sign server keys if certificates are used. This file should # be in "authorized_keys" format. -import asyncio, asyncssh, sys +import asyncio +import sys from asyncio.subprocess import PIPE +import asyncssh + + async def handle_request(process: asyncssh.SSHServerProcess) -> None: """Run a command on the client, piping I/O over an SSH session""" diff --git a/examples/reverse_server.py b/examples/reverse_server.py index 69da48b1..44de63cf 100755 --- a/examples/reverse_server.py +++ b/examples/reverse_server.py @@ -30,7 +30,11 @@ # key trusted to sign client host keys if certificates are used. This file # should be in "known_hosts" format. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_commands(conn: asyncssh.SSHClientConnection) -> None: """Run a series of commands on the client which connected to us""" diff --git a/examples/scp_client.py b/examples/scp_client.py index 826d0444..c85c6a4b 100755 --- a/examples/scp_client.py +++ b/examples/scp_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: await asyncssh.scp('localhost:example.txt', '.') diff --git a/examples/set_environment.py b/examples/set_environment.py index 5b983ada..7468c0dd 100755 --- a/examples/set_environment.py +++ b/examples/set_environment.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/set_terminal.py b/examples/set_terminal.py index b7409844..0e5427fc 100755 --- a/examples/set_terminal.py +++ b/examples/set_terminal.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/sftp_client.py b/examples/sftp_client.py index 02e03b11..269ca0cf 100755 --- a/examples/sftp_client.py +++ b/examples/sftp_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/show_environment.py b/examples/show_environment.py index a71bf466..7686d82c 100755 --- a/examples/show_environment.py +++ b/examples/show_environment.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def handle_client(process: asyncssh.SSHServerProcess) -> None: if process.env: diff --git a/examples/show_terminal.py b/examples/show_terminal.py index d3a38257..e64a4baf 100755 --- a/examples/show_terminal.py +++ b/examples/show_terminal.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def handle_client(process: asyncssh.SSHServerProcess) -> None: width, height, pixwidth, pixheight = process.term_size diff --git a/examples/simple_cert_server.py b/examples/simple_cert_server.py index 6c447b21..8779b305 100755 --- a/examples/simple_cert_server.py +++ b/examples/simple_cert_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + def handle_client(process: asyncssh.SSHServerProcess) -> None: username = process.get_extra_info('username') diff --git a/examples/simple_client.py b/examples/simple_client.py index 462c57e7..eaa28d8d 100755 --- a/examples/simple_client.py +++ b/examples/simple_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/simple_keyed_server.py b/examples/simple_keyed_server.py index bd41ae79..649d0bd0 100755 --- a/examples/simple_keyed_server.py +++ b/examples/simple_keyed_server.py @@ -28,7 +28,11 @@ # files in it named based on the username containing the client keys # and certificate authority keys which are accepted for that user. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + def handle_client(process: asyncssh.SSHServerProcess) -> None: username = process.get_extra_info('username') diff --git a/examples/simple_scp_server.py b/examples/simple_scp_server.py index 28768d50..326f3eca 100755 --- a/examples/simple_scp_server.py +++ b/examples/simple_scp_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def start_server() -> None: await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], diff --git a/examples/simple_server.py b/examples/simple_server.py index 1d01f783..096711d2 100755 --- a/examples/simple_server.py +++ b/examples/simple_server.py @@ -24,9 +24,14 @@ # private key in it to use as a server host key. An SSH host certificate # can optionally be provided in the file ``ssh_host_key-cert.pub``. -import asyncio, asyncssh, bcrypt, sys +import asyncio +import sys from typing import Optional +import bcrypt + +import asyncssh + passwords = {'guest': b'', # guest account with no password 'user123': bcrypt.hashpw(b'secretpw', bcrypt.gensalt()), } diff --git a/examples/simple_sftp_server.py b/examples/simple_sftp_server.py index 682e8d41..7e787cc6 100755 --- a/examples/simple_sftp_server.py +++ b/examples/simple_sftp_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def start_server() -> None: await asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'], diff --git a/examples/stream_direct_client.py b/examples/stream_direct_client.py index 85febba5..22817f12 100755 --- a/examples/stream_direct_client.py +++ b/examples/stream_direct_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def run_client() -> None: async with asyncssh.connect('localhost') as conn: diff --git a/examples/stream_direct_server.py b/examples/stream_direct_server.py index 053e21fc..b336f83a 100755 --- a/examples/stream_direct_server.py +++ b/examples/stream_direct_server.py @@ -27,7 +27,11 @@ # The file ``ssh_user_ca`` must exist with a cert-authority entry of # the certificate authority which can sign valid client certificates. -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def handle_connection(reader: asyncssh.SSHReader, writer: asyncssh.SSHWriter) -> None: diff --git a/examples/stream_listening_client.py b/examples/stream_listening_client.py index 8285bef9..3fb64e8b 100755 --- a/examples/stream_listening_client.py +++ b/examples/stream_listening_client.py @@ -20,7 +20,11 @@ # Contributors: # Ron Frederick - initial implementation, API, and documentation -import asyncio, asyncssh, sys +import asyncio +import sys + +import asyncssh + async def handle_connection(reader, writer): while not reader.at_eof(): diff --git a/tests/keysign_stub.py b/tests/keysign_stub.py index db10addf..4b1ddb4b 100644 --- a/tests/keysign_stub.py +++ b/tests/keysign_stub.py @@ -22,7 +22,7 @@ import asyncssh from asyncssh.keysign import KEYSIGN_VERSION -from asyncssh.packet import Byte, String, SSHPacket +from asyncssh.packet import Byte, SSHPacket, String class SSHKeysignStub: diff --git a/tests/pkcs11_stub.py b/tests/pkcs11_stub.py index 472ed2bb..6dbc7aa2 100644 --- a/tests/pkcs11_stub.py +++ b/tests/pkcs11_stub.py @@ -23,6 +23,7 @@ import asyncssh from asyncssh.asn1 import der_decode from asyncssh.pkcs11 import pkcs11_available + from .util import get_test_key if pkcs11_available: # pragma: no branch diff --git a/tests/server.py b/tests/server.py index 58153f65..bda119d7 100644 --- a/tests/server.py +++ b/tests/server.py @@ -31,8 +31,14 @@ import asyncssh from asyncssh.misc import async_context_manager -from .util import AsyncTestCase, all_tasks, current_task, get_test_key -from .util import run, x509_available +from .util import ( + AsyncTestCase, + all_tasks, + current_task, + get_test_key, + run, + x509_available, +) class Server(asyncssh.SSHServer): diff --git a/tests/sk_stub.py b/tests/sk_stub.py index da935bea..7c024d45 100644 --- a/tests/sk_stub.py +++ b/tests/sk_stub.py @@ -24,15 +24,20 @@ from hashlib import sha256 import asyncssh -from asyncssh.asn1 import der_encode, der_decode +from asyncssh.asn1 import der_decode, der_encode from asyncssh.crypto import ECDSAPrivateKey, EdDSAPrivateKey from asyncssh.packet import Byte, UInt32 from asyncssh.sk import sk_available, sk_webauthn_prefix if sk_available: # pragma: no branch - from asyncssh.sk import SSH_SK_ECDSA, SSH_SK_ED25519 - from asyncssh.sk import SSH_SK_USER_PRESENCE_REQD - from asyncssh.sk import APDU, ApduError, CtapError + from asyncssh.sk import ( + APDU, + SSH_SK_ECDSA, + SSH_SK_ED25519, + SSH_SK_USER_PRESENCE_REQD, + ApduError, + CtapError, + ) class _Registration: diff --git a/tests/sspi_stub.py b/tests/sspi_stub.py index 99767ebd..862688fe 100644 --- a/tests/sspi_stub.py +++ b/tests/sspi_stub.py @@ -27,8 +27,12 @@ from .gss_stub import step if sys.platform == 'win32': # pragma: no cover - from asyncssh.gss_win32 import ASC_RET_INTEGRITY, ISC_RET_INTEGRITY - from asyncssh.gss_win32 import SECPKG_ATTR_NATIVE_NAMES, SSPIError + from asyncssh.gss_win32 import ( + ASC_RET_INTEGRITY, + ISC_RET_INTEGRITY, + SECPKG_ATTR_NATIVE_NAMES, + SSPIError, + ) class SSPIBuffer: diff --git a/tests/test_agent.py b/tests/test_agent.py index 322adec3..3754add3 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -23,19 +23,21 @@ import asyncio import functools import os -from pathlib import Path import signal import subprocess import unittest +from pathlib import Path import asyncssh - -from asyncssh.agent import SSH_AGENT_SUCCESS, SSH_AGENT_FAILURE -from asyncssh.agent import SSH_AGENT_IDENTITIES_ANSWER +from asyncssh.agent import ( + SSH_AGENT_FAILURE, + SSH_AGENT_IDENTITIES_ANSWER, + SSH_AGENT_SUCCESS, +) from asyncssh.crypto import ed25519_available from asyncssh.packet import Byte, String, UInt32 -from .sk_stub import sk_available, patch_sk +from .sk_stub import patch_sk, sk_available from .util import AsyncTestCase, asynctest, get_test_key, run, try_remove diff --git a/tests/test_asn1.py b/tests/test_asn1.py index bd905cbc..5cc2767d 100644 --- a/tests/test_asn1.py +++ b/tests/test_asn1.py @@ -23,10 +23,19 @@ import codecs import unittest -from asyncssh.asn1 import der_encode, der_decode -from asyncssh.asn1 import ASN1EncodeError, ASN1DecodeError -from asyncssh.asn1 import BitString, IA5String, ObjectIdentifier -from asyncssh.asn1 import RawDERObject, TaggedDERObject, PRIVATE +from asyncssh.asn1 import ( + PRIVATE, + ASN1DecodeError, + ASN1EncodeError, + BitString, + IA5String, + ObjectIdentifier, + RawDERObject, + TaggedDERObject, + der_decode, + der_encode, +) + class _TestASN1(unittest.TestCase): """Unit tests for ASN.1 module""" diff --git a/tests/test_auth.py b/tests/test_auth.py index d49f08b4..1686a361 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -25,17 +25,29 @@ import unittest import asyncssh - -from asyncssh.auth import MSG_USERAUTH_PK_OK, lookup_client_auth -from asyncssh.auth import get_supported_server_auth_methods, lookup_server_auth -from asyncssh.auth import MSG_USERAUTH_GSSAPI_RESPONSE -from asyncssh.constants import MSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE -from asyncssh.constants import MSG_USERAUTH_SUCCESS +from asyncssh.auth import ( + MSG_USERAUTH_GSSAPI_RESPONSE, + MSG_USERAUTH_PK_OK, + get_supported_server_auth_methods, + lookup_client_auth, + lookup_server_auth, +) +from asyncssh.constants import ( + MSG_USERAUTH_FAILURE, + MSG_USERAUTH_REQUEST, + MSG_USERAUTH_SUCCESS, +) from asyncssh.gss import GSSClient, GSSServer -from asyncssh.packet import SSHPacket, Boolean, Byte, NameList, String - -from .util import asynctest, gss_available, patch_gss -from .util import AsyncTestCase, ConnectionStub, get_test_key +from asyncssh.packet import Boolean, Byte, NameList, SSHPacket, String + +from .util import ( + AsyncTestCase, + ConnectionStub, + asynctest, + get_test_key, + gss_available, + patch_gss, +) class _AuthConnectionStub(ConnectionStub): diff --git a/tests/test_channel.py b/tests/test_channel.py index 9579f3db..95d59e68 100644 --- a/tests/test_channel.py +++ b/tests/test_channel.py @@ -25,24 +25,29 @@ import tempfile import unittest from signal import SIGINT - from unittest.mock import patch import asyncssh - -from asyncssh.constants import DEFAULT_LANG, MSG_USERAUTH_REQUEST -from asyncssh.constants import MSG_CHANNEL_OPEN_CONFIRMATION -from asyncssh.constants import MSG_CHANNEL_OPEN_FAILURE -from asyncssh.constants import MSG_CHANNEL_WINDOW_ADJUST -from asyncssh.constants import MSG_CHANNEL_DATA -from asyncssh.constants import MSG_CHANNEL_EXTENDED_DATA -from asyncssh.constants import MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE -from asyncssh.constants import MSG_CHANNEL_SUCCESS +from asyncssh.constants import ( + DEFAULT_LANG, + MSG_CHANNEL_CLOSE, + MSG_CHANNEL_DATA, + MSG_CHANNEL_EOF, + MSG_CHANNEL_EXTENDED_DATA, + MSG_CHANNEL_OPEN_CONFIRMATION, + MSG_CHANNEL_OPEN_FAILURE, + MSG_CHANNEL_SUCCESS, + MSG_CHANNEL_WINDOW_ADJUST, + MSG_USERAUTH_REQUEST, +) from asyncssh.packet import Byte, String, UInt32 from asyncssh.public_key import CERT_TYPE_USER -from asyncssh.stream import SSHTCPStreamSession, SSHUNIXStreamSession -from asyncssh.stream import SSHTunTapStreamSession -from asyncssh.tuntap import SSH_TUN_MODE_POINTTOPOINT, SSH_TUN_MODE_ETHERNET +from asyncssh.stream import ( + SSHTCPStreamSession, + SSHTunTapStreamSession, + SSHUNIXStreamSession, +) +from asyncssh.tuntap import SSH_TUN_MODE_ETHERNET, SSH_TUN_MODE_POINTTOPOINT from .server import Server, ServerTestCase from .util import asynctest, echo, make_certificate diff --git a/tests/test_compression.py b/tests/test_compression.py index 25052798..95735d47 100644 --- a/tests/test_compression.py +++ b/tests/test_compression.py @@ -23,8 +23,12 @@ import os import unittest -from asyncssh.compression import get_compression_algs, get_compression_params -from asyncssh.compression import get_compressor, get_decompressor +from asyncssh.compression import ( + get_compression_algs, + get_compression_params, + get_compressor, + get_decompressor, +) class TestCompression(unittest.TestCase): diff --git a/tests/test_config.py b/tests/test_config.py index 5db454b2..91a01df8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -23,12 +23,10 @@ import os import socket import unittest - from pathlib import Path from unittest.mock import patch import asyncssh - from asyncssh.config import SSHClientConfig, SSHServerConfig from .util import TempDirTestCase diff --git a/tests/test_connection.py b/tests/test_connection.py index f71b2e50..db759e6e 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -21,41 +21,59 @@ """Unit tests for AsyncSSH connection API""" import asyncio -from copy import copy import os -from pathlib import Path import socket import sys import unittest +from copy import copy +from pathlib import Path from unittest.mock import patch import asyncssh -from asyncssh.constants import MSG_IGNORE, MSG_DEBUG -from asyncssh.constants import MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT -from asyncssh.constants import MSG_KEXINIT, MSG_NEWKEYS -from asyncssh.constants import MSG_KEX_FIRST, MSG_KEX_LAST -from asyncssh.constants import MSG_USERAUTH_REQUEST, MSG_USERAUTH_SUCCESS -from asyncssh.constants import MSG_USERAUTH_FAILURE, MSG_USERAUTH_BANNER -from asyncssh.constants import MSG_USERAUTH_FIRST -from asyncssh.constants import MSG_GLOBAL_REQUEST -from asyncssh.constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_CONFIRMATION -from asyncssh.constants import MSG_CHANNEL_OPEN_FAILURE, MSG_CHANNEL_DATA from asyncssh.compression import get_compression_algs +from asyncssh.constants import ( + MSG_CHANNEL_DATA, + MSG_CHANNEL_OPEN, + MSG_CHANNEL_OPEN_CONFIRMATION, + MSG_CHANNEL_OPEN_FAILURE, + MSG_DEBUG, + MSG_GLOBAL_REQUEST, + MSG_IGNORE, + MSG_KEX_FIRST, + MSG_KEX_LAST, + MSG_KEXINIT, + MSG_NEWKEYS, + MSG_SERVICE_ACCEPT, + MSG_SERVICE_REQUEST, + MSG_USERAUTH_BANNER, + MSG_USERAUTH_FAILURE, + MSG_USERAUTH_FIRST, + MSG_USERAUTH_REQUEST, + MSG_USERAUTH_SUCCESS, +) from asyncssh.crypto.cipher import GCMCipher from asyncssh.encryption import get_encryption_algs from asyncssh.kex import get_kex_algs from asyncssh.kex_dh import MSG_KEX_ECDH_REPLY from asyncssh.mac import _HMAC, _mac_handler, get_mac_algs -from asyncssh.packet import SSHPacket, Boolean, NameList, String, UInt32 -from asyncssh.public_key import get_default_public_key_algs -from asyncssh.public_key import get_default_certificate_algs -from asyncssh.public_key import get_default_x509_certificate_algs +from asyncssh.packet import Boolean, NameList, SSHPacket, String, UInt32 +from asyncssh.public_key import ( + get_default_certificate_algs, + get_default_public_key_algs, + get_default_x509_certificate_algs, +) from .server import Server, ServerTestCase - -from .util import asynctest, patch_extra_kex, patch_getaddrinfo -from .util import patch_getnameinfo, patch_gss -from .util import gss_available, nc_available, x509_available +from .util import ( + asynctest, + gss_available, + nc_available, + patch_extra_kex, + patch_getaddrinfo, + patch_getnameinfo, + patch_gss, + x509_available, +) class _CheckAlgsClientConnection(asyncssh.SSHClientConnection): diff --git a/tests/test_connection_auth.py b/tests/test_connection_auth.py index 4554d929..7fd8b9dd 100644 --- a/tests/test_connection_auth.py +++ b/tests/test_connection_auth.py @@ -24,7 +24,6 @@ import os import sys import unittest - from unittest.mock import patch from cryptography.exceptions import UnsupportedAlgorithm @@ -32,13 +31,20 @@ import asyncssh from asyncssh.misc import async_context_manager, write_file from asyncssh.packet import String -from asyncssh.public_key import CERT_TYPE_USER, CERT_TYPE_HOST +from asyncssh.public_key import CERT_TYPE_HOST, CERT_TYPE_USER from .keysign_stub import create_subprocess_exec_stub from .server import Server, ServerTestCase -from .util import asynctest, gss_available, patch_getnameinfo -from .util import patch_getnameinfo_error, patch_gss -from .util import make_certificate, nc_available, x509_available +from .util import ( + asynctest, + gss_available, + make_certificate, + nc_available, + patch_getnameinfo, + patch_getnameinfo_error, + patch_gss, + x509_available, +) class _FailValidateHostSSHServerConnection(asyncssh.SSHServerConnection): diff --git a/tests/test_editor.py b/tests/test_editor.py index 32dd5ef6..d9bb10ce 100644 --- a/tests/test_editor.py +++ b/tests/test_editor.py @@ -21,6 +21,7 @@ """Unit tests for AsyncSSH line editor""" import asyncio + import asyncssh from .server import ServerTestCase diff --git a/tests/test_encryption.py b/tests/test_encryption.py index 4daf1c1d..c9eda041 100644 --- a/tests/test_encryption.py +++ b/tests/test_encryption.py @@ -24,8 +24,12 @@ import random import unittest -from asyncssh.encryption import register_encryption_alg, get_encryption_algs -from asyncssh.encryption import get_encryption_params, get_encryption +from asyncssh.encryption import ( + get_encryption, + get_encryption_algs, + get_encryption_params, + register_encryption_alg, +) from asyncssh.mac import get_mac_algs diff --git a/tests/test_forward.py b/tests/test_forward.py index dbfd792e..f8348be5 100644 --- a/tests/test_forward.py +++ b/tests/test_forward.py @@ -26,15 +26,18 @@ import socket import sys import unittest - from unittest.mock import patch import asyncssh from asyncssh.misc import maybe_wait_closed, write_file from asyncssh.packet import String, UInt32 from asyncssh.public_key import CERT_TYPE_USER -from asyncssh.socks import SOCKS5, SOCKS5_AUTH_NONE -from asyncssh.socks import SOCKS4_OK_RESPONSE, SOCKS5_OK_RESPONSE_HDR +from asyncssh.socks import ( + SOCKS4_OK_RESPONSE, + SOCKS5, + SOCKS5_AUTH_NONE, + SOCKS5_OK_RESPONSE_HDR, +) from .server import Server, ServerTestCase from .util import asynctest, echo, make_certificate, try_remove diff --git a/tests/test_kex.py b/tests/test_kex.py index 01c7ec83..405356b6 100644 --- a/tests/test_kex.py +++ b/tests/test_kex.py @@ -23,29 +23,49 @@ import asyncio import inspect import unittest - from hashlib import sha1 import asyncssh - -from asyncssh.crypto import curve25519_available, curve448_available -from asyncssh.crypto import mlkem_available, sntrup_available -from asyncssh.crypto import Curve25519DH, Curve448DH, ECDH, MLKEM, SNTRUP -from asyncssh.kex_dh import MSG_KEXDH_INIT, MSG_KEXDH_REPLY -from asyncssh.kex_dh import MSG_KEX_DH_GEX_REQUEST, MSG_KEX_DH_GEX_GROUP -from asyncssh.kex_dh import MSG_KEX_DH_GEX_INIT, MSG_KEX_DH_GEX_REPLY, _KexDHGex -from asyncssh.kex_dh import MSG_KEX_ECDH_INIT, MSG_KEX_ECDH_REPLY -from asyncssh.kex_dh import MSG_KEXGSS_INIT, MSG_KEXGSS_HOSTKEY -from asyncssh.kex_dh import MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR -from asyncssh.kex_rsa import MSG_KEXRSA_PUBKEY, MSG_KEXRSA_SECRET -from asyncssh.kex_rsa import MSG_KEXRSA_DONE +from asyncssh.crypto import ( + ECDH, + MLKEM, + SNTRUP, + Curve448DH, + Curve25519DH, + curve448_available, + curve25519_available, + mlkem_available, + sntrup_available, +) from asyncssh.gss import GSSClient, GSSServer -from asyncssh.kex import register_kex_alg, get_kex_algs, get_kex -from asyncssh.packet import SSHPacket, Boolean, Byte, MPInt, String +from asyncssh.kex import get_kex, get_kex_algs, register_kex_alg +from asyncssh.kex_dh import ( + MSG_KEX_DH_GEX_GROUP, + MSG_KEX_DH_GEX_INIT, + MSG_KEX_DH_GEX_REPLY, + MSG_KEX_DH_GEX_REQUEST, + MSG_KEX_ECDH_INIT, + MSG_KEX_ECDH_REPLY, + MSG_KEXDH_INIT, + MSG_KEXDH_REPLY, + MSG_KEXGSS_COMPLETE, + MSG_KEXGSS_ERROR, + MSG_KEXGSS_HOSTKEY, + MSG_KEXGSS_INIT, + _KexDHGex, +) +from asyncssh.kex_rsa import MSG_KEXRSA_DONE, MSG_KEXRSA_PUBKEY, MSG_KEXRSA_SECRET +from asyncssh.packet import Boolean, Byte, MPInt, SSHPacket, String from asyncssh.public_key import decode_ssh_public_key -from .util import asynctest, get_test_key, gss_available, patch_gss -from .util import AsyncTestCase, ConnectionStub +from .util import ( + AsyncTestCase, + ConnectionStub, + asynctest, + get_test_key, + gss_available, + patch_gss, +) class _KexConnectionStub(ConnectionStub): diff --git a/tests/test_logging.py b/tests/test_logging.py index 459d6320..2828ea32 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -21,7 +21,6 @@ """Unit tests for AsyncSSH logging API""" import asyncssh - from asyncssh.logging import logger from asyncssh.session import SSHClientSession from asyncssh.sftp import SFTPServer diff --git a/tests/test_mac.py b/tests/test_mac.py index 5a00e153..29b2e49c 100644 --- a/tests/test_mac.py +++ b/tests/test_mac.py @@ -23,7 +23,7 @@ import os import unittest -from asyncssh.mac import get_mac_algs, get_mac_params, get_mac +from asyncssh.mac import get_mac, get_mac_algs, get_mac_params class _TestMAC(unittest.TestCase): diff --git a/tests/test_packet.py b/tests/test_packet.py index 7789ba39..87f0d749 100644 --- a/tests/test_packet.py +++ b/tests/test_packet.py @@ -23,8 +23,17 @@ import codecs import unittest -from asyncssh.packet import Byte, Boolean, UInt32, UInt64, String, MPInt -from asyncssh.packet import NameList, PacketDecodeError, SSHPacket +from asyncssh.packet import ( + Boolean, + Byte, + MPInt, + NameList, + PacketDecodeError, + SSHPacket, + String, + UInt32, + UInt64, +) class _TestPacket(unittest.TestCase): diff --git a/tests/test_pkcs11.py b/tests/test_pkcs11.py index 8cc8bd46..8bfe3d8b 100644 --- a/tests/test_pkcs11.py +++ b/tests/test_pkcs11.py @@ -24,9 +24,13 @@ import asyncssh -from .pkcs11_stub import pkcs11_available -from .pkcs11_stub import get_pkcs11_public_keys, get_pkcs11_certs -from .pkcs11_stub import stub_pkcs11, unstub_pkcs11 +from .pkcs11_stub import ( + get_pkcs11_certs, + get_pkcs11_public_keys, + pkcs11_available, + stub_pkcs11, + unstub_pkcs11, +) from .server import ServerTestCase from .util import asynctest diff --git a/tests/test_process.py b/tests/test_process.py index 9a42a014..8e0bea7c 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -23,11 +23,11 @@ import asyncio import io import os -from pathlib import Path -from signal import SIGINT import socket import sys import unittest +from pathlib import Path +from signal import SIGINT import asyncssh diff --git a/tests/test_public_key.py b/tests/test_public_key.py index d556b12d..ff48c9ad 100644 --- a/tests/test_public_key.py +++ b/tests/test_public_key.py @@ -28,36 +28,44 @@ """ import binascii -from datetime import datetime import os -from pathlib import Path import shutil import subprocess import sys import unittest +from datetime import datetime +from pathlib import Path from cryptography.exceptions import UnsupportedAlgorithm import asyncssh - -from asyncssh.asn1 import der_encode, BitString, ObjectIdentifier -from asyncssh.asn1 import TaggedDERObject -from asyncssh.crypto import chacha_available, ed25519_available, ed448_available +from asyncssh.asn1 import BitString, ObjectIdentifier, TaggedDERObject, der_encode +from asyncssh.crypto import chacha_available, ed448_available, ed25519_available from asyncssh.misc import write_file from asyncssh.packet import MPInt, String, UInt32 from asyncssh.pbe import pkcs1_decrypt -from asyncssh.public_key import CERT_TYPE_USER, CERT_TYPE_HOST, SSHKey -from asyncssh.public_key import SSHX509CertificateChain -from asyncssh.public_key import decode_ssh_certificate -from asyncssh.public_key import get_public_key_algs, get_certificate_algs -from asyncssh.public_key import get_x509_certificate_algs -from asyncssh.public_key import import_certificate_subject -from asyncssh.public_key import load_identities +from asyncssh.public_key import ( + CERT_TYPE_HOST, + CERT_TYPE_USER, + SSHKey, + SSHX509CertificateChain, + decode_ssh_certificate, + get_certificate_algs, + get_public_key_algs, + get_x509_certificate_algs, + import_certificate_subject, + load_identities, +) from .sk_stub import sk_available, stub_sk, unstub_sk -from .util import bcrypt_available, get_test_key, x509_available -from .util import make_certificate, run, TempDirTestCase - +from .util import ( + TempDirTestCase, + bcrypt_available, + get_test_key, + make_certificate, + run, + x509_available, +) _ES1_SHA1_DES = ObjectIdentifier('1.2.840.113549.1.5.10') _P12_RC4_40 = ObjectIdentifier('1.2.840.113549.1.12.1.2') diff --git a/tests/test_saslprep.py b/tests/test_saslprep.py index ca29f3ac..ec852e4b 100644 --- a/tests/test_saslprep.py +++ b/tests/test_saslprep.py @@ -22,7 +22,8 @@ import unittest -from asyncssh.saslprep import saslprep, SASLPrepError +from asyncssh.saslprep import SASLPrepError, saslprep + class _TestSASLPrep(unittest.TestCase): """Unit tests for saslprep module""" diff --git a/tests/test_sftp.py b/tests/test_sftp.py index f887cf97..55b68b31 100644 --- a/tests/test_sftp.py +++ b/tests/test_sftp.py @@ -24,55 +24,105 @@ import errno import functools import os -from pathlib import Path import posixpath import shutil import stat import sys import time import unittest +from pathlib import Path from unittest.mock import patch import asyncssh - -from asyncssh import SFTPError, SFTPNoSuchFile, SFTPPermissionDenied -from asyncssh import SFTPFailure, SFTPBadMessage, SFTPNoConnection -from asyncssh import SFTPConnectionLost, SFTPOpUnsupported, SFTPInvalidHandle -from asyncssh import SFTPNoSuchPath, SFTPFileAlreadyExists, SFTPWriteProtect -from asyncssh import SFTPNoMedia, SFTPNoSpaceOnFilesystem, SFTPQuotaExceeded -from asyncssh import SFTPUnknownPrincipal, SFTPLockConflict, SFTPDirNotEmpty -from asyncssh import SFTPNotADirectory, SFTPInvalidFilename, SFTPLinkLoop -from asyncssh import SFTPCannotDelete, SFTPInvalidParameter -from asyncssh import SFTPFileIsADirectory, SFTPByteRangeLockConflict -from asyncssh import SFTPByteRangeLockRefused, SFTPDeletePending -from asyncssh import SFTPFileCorrupt, SFTPOwnerInvalid, SFTPGroupInvalid -from asyncssh import SFTPNoMatchingByteRangeLock -from asyncssh import SFTPAttrs, SFTPVFSAttrs, SFTPName, SFTPServer -from asyncssh import SEEK_CUR, SEEK_END -from asyncssh import FXP_INIT, FXP_VERSION, FXP_OPEN, FXP_READ -from asyncssh import FXP_WRITE, FXP_STATUS, FXP_HANDLE, FXP_DATA -from asyncssh import FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC -from asyncssh import FXF_CREATE_NEW, FXF_CREATE_TRUNCATE, FXF_OPEN_EXISTING -from asyncssh import FXF_OPEN_OR_CREATE, FXF_TRUNCATE_EXISTING -from asyncssh import FXF_APPEND_DATA, FXF_BLOCK_READ -from asyncssh import ACE4_READ_DATA, ACE4_WRITE_DATA, ACE4_APPEND_DATA -from asyncssh import FXR_OVERWRITE -from asyncssh import FXRP_STAT_IF_EXISTS, FXRP_STAT_ALWAYS -from asyncssh import FILEXFER_ATTR_UIDGID, FILEXFER_ATTR_OWNERGROUP -from asyncssh import FILEXFER_TYPE_REGULAR, FILEXFER_TYPE_DIRECTORY -from asyncssh import FILEXFER_TYPE_SYMLINK, FILEXFER_TYPE_SPECIAL -from asyncssh import FILEXFER_TYPE_UNKNOWN, FILEXFER_TYPE_SOCKET -from asyncssh import FILEXFER_TYPE_CHAR_DEVICE, FILEXFER_TYPE_BLOCK_DEVICE -from asyncssh import FILEXFER_TYPE_FIFO -from asyncssh import FILEXFER_ATTR_BITS_READONLY, FILEXFER_ATTR_KNOWN_TEXT -from asyncssh import FX_OK, scp - +from asyncssh import ( + ACE4_APPEND_DATA, + ACE4_READ_DATA, + ACE4_WRITE_DATA, + FILEXFER_ATTR_BITS_READONLY, + FILEXFER_ATTR_KNOWN_TEXT, + FILEXFER_ATTR_OWNERGROUP, + FILEXFER_ATTR_UIDGID, + FILEXFER_TYPE_BLOCK_DEVICE, + FILEXFER_TYPE_CHAR_DEVICE, + FILEXFER_TYPE_DIRECTORY, + FILEXFER_TYPE_FIFO, + FILEXFER_TYPE_REGULAR, + FILEXFER_TYPE_SOCKET, + FILEXFER_TYPE_SPECIAL, + FILEXFER_TYPE_SYMLINK, + FILEXFER_TYPE_UNKNOWN, + FX_OK, + FXF_APPEND, + FXF_APPEND_DATA, + FXF_BLOCK_READ, + FXF_CREAT, + FXF_CREATE_NEW, + FXF_CREATE_TRUNCATE, + FXF_OPEN_EXISTING, + FXF_OPEN_OR_CREATE, + FXF_TRUNC, + FXF_TRUNCATE_EXISTING, + FXF_WRITE, + FXP_DATA, + FXP_HANDLE, + FXP_INIT, + FXP_OPEN, + FXP_READ, + FXP_STATUS, + FXP_VERSION, + FXP_WRITE, + FXR_OVERWRITE, + FXRP_STAT_ALWAYS, + FXRP_STAT_IF_EXISTS, + SEEK_CUR, + SEEK_END, + SFTPAttrs, + SFTPBadMessage, + SFTPByteRangeLockConflict, + SFTPByteRangeLockRefused, + SFTPCannotDelete, + SFTPConnectionLost, + SFTPDeletePending, + SFTPDirNotEmpty, + SFTPError, + SFTPFailure, + SFTPFileAlreadyExists, + SFTPFileCorrupt, + SFTPFileIsADirectory, + SFTPGroupInvalid, + SFTPInvalidFilename, + SFTPInvalidHandle, + SFTPInvalidParameter, + SFTPLinkLoop, + SFTPLockConflict, + SFTPName, + SFTPNoConnection, + SFTPNoMatchingByteRangeLock, + SFTPNoMedia, + SFTPNoSpaceOnFilesystem, + SFTPNoSuchFile, + SFTPNoSuchPath, + SFTPNotADirectory, + SFTPOpUnsupported, + SFTPOwnerInvalid, + SFTPPermissionDenied, + SFTPQuotaExceeded, + SFTPServer, + SFTPUnknownPrincipal, + SFTPVFSAttrs, + SFTPWriteProtect, + scp, +) from asyncssh.misc import make_sparse_file - from asyncssh.packet import SSHPacket, String, UInt32 - -from asyncssh.sftp import SAFE_SFTP_READ_LEN, SAFE_SFTP_WRITE_LEN -from asyncssh.sftp import LocalFile, SFTPHandler, SFTPLimits, SFTPServerHandler +from asyncssh.sftp import ( + SAFE_SFTP_READ_LEN, + SAFE_SFTP_WRITE_LEN, + LocalFile, + SFTPHandler, + SFTPLimits, + SFTPServerHandler, +) from .server import ServerTestCase from .util import asynctest diff --git a/tests/test_sk.py b/tests/test_sk.py index 0b1786f4..f8a53aa1 100644 --- a/tests/test_sk.py +++ b/tests/test_sk.py @@ -25,7 +25,7 @@ import asyncssh from .server import ServerTestCase -from .sk_stub import sk_available, stub_sk, unstub_sk, patch_sk, sk_error +from .sk_stub import patch_sk, sk_available, sk_error, stub_sk, unstub_sk from .util import asynctest, get_test_key diff --git a/tests/test_sshsig.py b/tests/test_sshsig.py index 6c247da2..fc0ae0ee 100644 --- a/tests/test_sshsig.py +++ b/tests/test_sshsig.py @@ -24,7 +24,6 @@ import os import asyncssh - from asyncssh.packet import String, UInt32 from .util import TempDirTestCase, get_test_key diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py index 50745b23..65aa4a8c 100644 --- a/tests/test_subprocess.py +++ b/tests/test_subprocess.py @@ -28,6 +28,7 @@ from .server import Server, ServerTestCase from .util import asynctest, echo + class _SubprocessProtocol(asyncssh.SSHSubprocessProtocol): """Unit test SSH subprocess protocol""" diff --git a/tests/test_tuntap.py b/tests/test_tuntap.py index 9fc01351..4ebecee8 100644 --- a/tests/test_tuntap.py +++ b/tests/test_tuntap.py @@ -26,7 +26,6 @@ import socket import struct import sys - from unittest import skipIf, skipUnless from unittest.mock import patch diff --git a/tests/test_x11.py b/tests/test_x11.py index c002da0e..eabfbad0 100644 --- a/tests/test_x11.py +++ b/tests/test_x11.py @@ -23,20 +23,27 @@ import asyncio import os import socket - from unittest.mock import patch import asyncssh - from asyncssh.misc import maybe_wait_closed from asyncssh.packet import Boolean, String, UInt32 - -from asyncssh.x11 import XAUTH_FAMILY_IPV4, XAUTH_FAMILY_DECNET -from asyncssh.x11 import XAUTH_FAMILY_IPV6, XAUTH_FAMILY_HOSTNAME -from asyncssh.x11 import XAUTH_FAMILY_WILD, XAUTH_PROTO_COOKIE -from asyncssh.x11 import XAUTH_COOKIE_LEN, X11_BASE_PORT, X11_LISTEN_HOST -from asyncssh.x11 import SSHXAuthorityEntry, SSHX11ClientListener -from asyncssh.x11 import walk_xauth, lookup_xauth, update_xauth +from asyncssh.x11 import ( + X11_BASE_PORT, + X11_LISTEN_HOST, + XAUTH_COOKIE_LEN, + XAUTH_FAMILY_DECNET, + XAUTH_FAMILY_HOSTNAME, + XAUTH_FAMILY_IPV4, + XAUTH_FAMILY_IPV6, + XAUTH_FAMILY_WILD, + XAUTH_PROTO_COOKIE, + SSHX11ClientListener, + SSHXAuthorityEntry, + lookup_xauth, + update_xauth, + walk_xauth, +) from .server import Server, ServerTestCase from .util import asynctest diff --git a/tests/test_x509.py b/tests/test_x509.py index d923dd6c..f5d6ccfa 100644 --- a/tests/test_x509.py +++ b/tests/test_x509.py @@ -28,9 +28,12 @@ from .util import get_test_key, x509_available if x509_available: # pragma: no branch - from asyncssh.crypto import X509Name, X509NamePattern - from asyncssh.crypto import generate_x509_certificate - from asyncssh.crypto import import_x509_certificate + from asyncssh.crypto import ( + X509Name, + X509NamePattern, + generate_x509_certificate, + import_x509_certificate, + ) _purpose_secureShellClient = x509.ObjectIdentifier('1.3.6.1.5.5.7.3.21') diff --git a/tests/util.py b/tests/util.py index 5dc7d3e8..ee636239 100644 --- a/tests/util.py +++ b/tests/util.py @@ -30,7 +30,6 @@ import sys import tempfile import unittest - from unittest.mock import patch from asyncssh import set_default_skip_rsa_key_validation @@ -40,7 +39,6 @@ from asyncssh.packet import Byte, String, UInt32, UInt64 from asyncssh.public_key import generate_private_key - # pylint: disable=ungrouped-imports, unused-import try: @@ -173,8 +171,7 @@ def patch_gss(cls): cls = patch('asyncssh.gss_win32.ClientAuth', SSPIAuth)(cls) cls = patch('asyncssh.gss_win32.ServerAuth', SSPIAuth)(cls) else: - from .gssapi_stub import Name, Credentials, RequirementFlag - from .gssapi_stub import SecurityContext + from .gssapi_stub import Credentials, Name, RequirementFlag, SecurityContext cls = patch('asyncssh.gss_unix.Name', Name)(cls) cls = patch('asyncssh.gss_unix.Credentials', Credentials)(cls)