Skip to content

Commit c416032

Browse files
committed
Improve exception raised when failing to open SFTP sessions.
1 parent 8195500 commit c416032

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

pyinfra/api/connectors/ssh.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
)
1010

1111
import click
12+
import six
1213

1314
from paramiko import (
1415
AuthenticationException,
@@ -306,7 +307,14 @@ def run_shell_command(
306307
@memoize
307308
def _get_sftp_connection(host):
308309
transport = host.connection.get_transport()
309-
return SFTPClient.from_transport(transport)
310+
311+
try:
312+
return SFTPClient.from_transport(transport)
313+
except SSHException as e:
314+
six.raise_from(ConnectError((
315+
'Unable to establish SFTP connection. Check that the SFTP subsystem '
316+
'for the SSH service at {0} is enabled.'
317+
).format(host)), e)
310318

311319

312320
def _get_file(host, remote_filename, filename_or_io):

tests/test_connectors/test_ssh.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from pyinfra.api import Config, MaskString, State, StringCommand
2121
from pyinfra.api.connect import connect_all
2222
from pyinfra.api.connectors.ssh import _get_sftp_connection
23-
from pyinfra.api.exceptions import PyinfraError
23+
from pyinfra.api.exceptions import ConnectError, PyinfraError
2424

2525
from ..util import make_inventory
2626

@@ -650,3 +650,24 @@ def test_get_file_su_user(self, fake_sftp_client, fake_ssh_client):
650650
fake_sftp_client.from_transport().getfo.assert_called_with(
651651
'/tmp/pyinfra-e9c0d3c8ffca943daa0e75511b0a09c84b59c508', fake_open(),
652652
)
653+
654+
@patch('pyinfra.api.connectors.ssh.SSHClient')
655+
@patch('pyinfra.api.connectors.ssh.SFTPClient')
656+
def test_get_sftp_fail(self, fake_sftp_client, fake_ssh_client):
657+
inventory = make_inventory(hosts=('anotherhost',))
658+
State(inventory, Config())
659+
host = inventory.get_host('anotherhost')
660+
host.connect()
661+
662+
def raise_exception(*args, **kwargs):
663+
raise SSHException()
664+
665+
fake_sftp_client.from_transport.side_effect = raise_exception
666+
667+
fake_open = mock_open(read_data='test!')
668+
with patch('pyinfra.api.util.open', fake_open, create=True):
669+
with self.assertRaises(ConnectError):
670+
host.put_file(
671+
'not-a-file', 'not-another-file',
672+
print_output=True,
673+
)

0 commit comments

Comments
 (0)