How can I upload a Configuration file to EC2 Instance’ securely?

75    Asked by ConnorPeake in AWS , Asked on Apr 24, 2024

 I am a DevOps engineer and I am currently managing applications on an AWS EC2 Instance. In need to upload w Configuration file to an EC2 Instance securely. How can I do so? 

Answered by Csaba Toth

 In the context of AWS, here are the appropriate approaches given by using the example of Python coding snippet using paramiko, an SSH Library:-

Import paramiko

# Define EC2 instance details
Ec2_instance_ip = ‘EC2_INSTANCE_IP’
Username = ‘ec2-user’ # Replace with the appropriate username
Private_key_path = ‘PATH_TO_PRIVATE_KEY_FILE’
# Create SSH client
Ssh_client = paramiko.SSHClient()
# Load private key for authentication
Private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
# Connect to the EC2 instance
Ssh_client.connect(hostname=ec2_instance_ip, username=username, pkey=private_key)
# Upload file to EC2 instance
Local_file_path = ‘PATH_TO_LOCAL_FILE’
Sftp_client = ssh_client.open_sftp()
Sftp_client.put(local_file_path, remote_file_path)
# Close SSH and SFTP connections
Print(f”File uploaded successfully to {ec2_instance_ip}:{remote_file_path}”)

Below is the example given of java programming language by using the JSch library for uploading a file to an EC2 Instance securely by using the SSH protocol:-

Import com.jcraft.jsch.Channel;
Import com.jcraft.jsch.ChannelSftp;
Import com.jcraft.jsch.JSch;
Import com.jcraft.jsch.Session;
Public class SshFileUploader {
    Public static void main(String[] args) {
        String ec2InstanceIp = “EC2_INSTANCE_IP”;
        String username = “ec2-user”; // Replace with the appropriate username
        String privateKeyPath = “PATH_TO_PRIVATE_KEY_FILE”;
        String localFilePath = “PATH_TO_LOCAL_FILE”;
        String remoteDirectory = “PATH_TO_REMOTE_DIRECTORY”;
        String fileName = “FILE_NAME”;
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        Try {
            // Load private key
            // Establish SSH session
            Session = jsch.getSession(username, ec2InstanceIp, 22);
            Session.setConfig(“StrictHostKeyChecking”, “no”);
            // Open SFTP channel
            Channel = session.openChannel(“sftp”);
            channelSftp = (ChannelSftp) channel;
            // Change directory to remote directory
            // Upload file
            File file = new File(localFilePath);
            channelSftp.put(file.getAbsolutePath(), fileName);
            System.out.println(“File uploaded successfully.”);
        } catch (Exception e) {
        } finally {
            If (channelSftp != null) {
            If (channel != null) {
            If (session != null) {

Your Answer


Parent Categories