Skip to content

Commit 16a159e

Browse files
committed
refactor: no long requires ECDSA key, also checks base folder struct exists.
1 parent 9270d60 commit 16a159e

File tree

1 file changed

+43
-30
lines changed

1 file changed

+43
-30
lines changed

janeway_ftp/sftp.py

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,47 +3,60 @@
33
import paramiko
44

55

6+
def ensure_remote_directory(sftp_client, remote_path):
7+
directories = remote_path.split('/')
8+
current_path = ''
9+
for directory in directories:
10+
if directory:
11+
current_path += f'/{directory}'
12+
try:
13+
sftp_client.stat(current_path)
14+
except FileNotFoundError:
15+
logging.info(f"Creating remote directory: {current_path}")
16+
sftp_client.mkdir(current_path)
17+
18+
619
def send_file_via_sftp(
720
ftp_server,
821
ftp_username,
922
ftp_password,
10-
ftp_server_key,
1123
remote_file_path,
1224
file_path,
13-
file_name
25+
file_name,
26+
known_hosts_file=None,
1427
):
28+
1529
ssh = paramiko.SSHClient()
16-
if ftp_server_key:
17-
key = paramiko.ecdsakey.ECDSAKey(
18-
data=paramiko.py3compat.decodebytes(ftp_server_key.encode("utf8"))
19-
)
20-
ssh.get_host_keys().add(
21-
hostname=ftp_server,
22-
keytype="ecdsa",
23-
key=key,
24-
)
30+
sftp = None # Ensure sftp is defined before usage
31+
32+
if known_hosts_file:
33+
try:
34+
ssh.load_host_keys(known_hosts_file)
35+
logging.info(f"Loaded known hosts from {known_hosts_file}")
36+
except IOError as e:
37+
logging.warning(f"Could not load known hosts file: {e}")
2538
else:
26-
logging.warning("No PORTICO_FTP_SERVER_KEY configured")
27-
ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
39+
logging.warning("No known hosts file supplied. Using auto-add policy.")
40+
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
2841

29-
ssh.connect(
30-
ftp_server,
31-
username=ftp_username,
32-
password=ftp_password,
33-
)
34-
sftp = ssh.open_sftp()
3542
try:
36-
sftp.mkdir(
37-
remote_file_path,
43+
ssh.connect(
44+
ftp_server,
45+
username=ftp_username,
46+
password=ftp_password,
3847
)
39-
except IOError:
40-
pass # folder exists already
41-
upload_path = "{}/{}".format(remote_file_path, file_name)
42-
sftp.put(
43-
file_path,
44-
upload_path,
45-
)
48+
sftp = ssh.open_sftp()
4649

47-
# Close SFTP Session and unlink the zip file
48-
ssh.close()
50+
# Ensure the remote directory structure exists
51+
ensure_remote_directory(sftp, remote_file_path)
4952

53+
upload_path = f"{remote_file_path}/{file_name}"
54+
sftp.put(file_path, upload_path)
55+
logging.info(f"File uploaded successfully to {upload_path}")
56+
except Exception as e:
57+
logging.error(f"Failed to send file via SFTP: {e}")
58+
raise
59+
finally:
60+
if sftp is not None:
61+
sftp.close()
62+
ssh.close()

0 commit comments

Comments
 (0)