I need to create a fastAPI endpoint that can convert a .ppk file to a .pem file. This conversion is necessary because I want to establish a connection to an SFTP server and download some files. Currently, I am able to connect and download files using a .pem file directly. However, I am unsure how to proceed when I only have a .ppk file available.
import paramiko
import tempfile
import subprocess
import shlex
use_host = 'testfile.random.com'
use_port = 22
use_username = 'tester123'
use_password = '1234567890'
use_ppk_path = '/home/ubuntu-test/Music/SFTP_Private_Key.ppk'
use_temp_pem_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".pem")
use_pem_path = use_temp_pem_file.name
use_cmd = f'puttygen "{use_ppk_path}" -O private-openssh -o "{use_pem_path}" --old-passphrase "{use_password}"'
use_process = subprocess.Popen(
use_cmd,
shell=True,
stdin=subprocess.PIPE
)
use_process.communicate(input=use_password.encode())
if use_process.returncode != 0:
print(f"Error executing command: {use_cmd}")
print(f"Command returned non-zero exit status: {use_process.returncode}")
print(f"Error output-stderr:\n{use_process.stderr}")
print(f"Error output-stdout:\n{use_process.stdout}")
with open(use_pem_path, 'r') as use_f:
use_f.seek(0)
use_file_contents = use_f.read()
print('file_contents', use_file_contents)
use_ssh = paramiko.SSHClient()
use_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
private_key = paramiko.RSAKey.from_private_key_file(filename=use_pem_path)
use_ssh.connect(use_host, port=use_port, username=use_username, password=use_password, key_filename=private_key)
use_sftp = use_ssh.open_sftp()
Errors:
use_f.read() is empty
private_key = paramiko.RSAKey.from_private_key_file(filename=use_pem_path) ----> paramiko.ssh_exception.SSHException: not a valid RSA private key file