It's a simple python script to take backup of directories (compressing) then the same to move your mentioned S3 bucket with the help of AWS IAM User.

Overview

Directory Backup Moved to S3 (Pyscript)

Build


Description

Here it's a python script that needs to use this script simply create a directory backup and moved that compressed backup file to a configured S3 bucket with the help of python script and AWS IAM User with S3 full access. So, let's roll down.


Feature

  • Easy to configure for anyone
  • It generates the directory compressed format
  • Which one we entered directory converted to a backup/compressed form to S3
  • All the steps I have provided including AWS IAM User and S3 Bucket Creation

Modules used


Pre-Requests

  • Basic Knowledge of python
  • Basic Knowledge of AWS IAM, S3 service
  • Need to change your IAM user creds and bucket name at var.py

IAM User Creation steps (with screenshot)

  1. log into your AWS account as a root user and go to IAM user
  2. goto Access Managment >> Users alt_txt
  3. Click Add User (top right corner) alt_txt
  4. Enter any username as you like and Choose "Programmatic access" >> Click Next Permissions alt_txt
  5. Set Permissions >> Select "Attach existing policies directly" >> Choose "AmazonS3FullAccess" >> Click Next Tags alt_txt
  6. Add Tags(Optional) >> Enter a key and value as you like either you can leave as blank alt_txt
  7. Review your user details and click "Create User" alt_txt
  8. Store your credentials to your local alt_txt

Reference URL:: IAM User creation article


S3 Bucket Creation (with screenshot)

  1. Go to S3 > Click Create Bucket alt_txt
  2. Any bucket name as you wish and then please enable versioning (that you upload same file multiple times or modified versions uploaded that the S3 stored as a version bases like Git) alt_txt
  3. Click create bucket

alt_txt

Reference URL:: Creating S3 bucket please use this doc and you can secure your bucket with IAM user using S3 bucket policy


Pre-Requested (Dependency packages)

yum install -y git
yum install -y python3
yum install -y python3-pip

How to get

git clone https://github.com/yousafkhamza/backup-to-s3-pyscript.git
cd backup-to-s3-pyscript
pip3 install -r requirements.txt

Change your creds and bucket name in at var.py file

Command to run the script::

python3 to-S3.py Python/test
# Pyhon/test               <------------ Directory to take backup and move the backup to S3

Output be like

$ $ python3 to-S3.py Python/httpd
Start to Upload that the httpd.tar.gz your S3 Bucket yousaf-test
Backup successfully uploaded to your S3 bucket yousaf-test

View of S3 bucket

Screenshot alt_txt


Behind the code

vim to-S3.py

import boto3
import tarfile
import os
import sys
import posixpath
import var
from boto3.s3.transfer import S3Transfer

directory = sys.argv[1]
dirname = os.path.split(directory)[-1]
if directory.endswith ('/'):
    print ('Please remove / after the directory path you have entered')
else:
    if posixpath.isdir(directory):
        tarname = '/tmp/{}.tar.gz'.format(dirname)
        tar = tarfile.open(tarname,'w:gz')
        tar.add(directory)
        tar.close()
        print('Start to Upload that the', dirname+'.tar.gz', 'your S3 Bucket', var.BUCKET_NAME)

# S3 uploading started
        client = boto3.client('s3', aws_access_key_id=var.AWS_ACCESS_KEY_ID,aws_secret_access_key=var.AWS_SECRET_ACCESS_KEY)
        transfer = S3Transfer(client)
        transfer.upload_file(tarname, var.BUCKET_NAME, 'backup/{}.tar.gz'.format(dirname))
        print('Backup succesfully uploaded to your S3 bucket', var.BUCKET_NAME)
    
# Remove temporary backup from local
        os.remove(tarname)
    else:
        print('Please enter a valid directory path')

var.py

AWS_ACCESS_KEY_ID = 'AKTBRI2N5IAT3ND'             <--------------   Replace your acess key
AWS_SECRET_ACCESS_KEY = 'asUNmMPrC99HoiiQPjehetFtVsPv'          <--------- Replace your secret key
BUCKET_NAME = 'yousaf-test'                <----------- Replace your bucket name

Conclusion

It's a simple python script to take backup of directories (compressing) then the same to move your mentioned S3 bucket with the help of AWS IAM User. this script may be helpful who had face issues moving backups to S3 so it might be useful for cloud engineers.

⚙️ Connect with Me


Owner
Yousaf K Hamza
Junior DevOps Enginner
Yousaf K Hamza
The Official Twilio SendGrid Led, Community Driven Python API Library

The default branch name for this repository has been changed to main as of 07/27/2020. This library allows you to quickly and easily use the SendGrid

Twilio SendGrid 1.4k Jan 07, 2023
ALIEN: idA Local varIables rEcogNizer

ALIEN: idA Local varIables rEcogNizer ALIEN is an IDA Pro plugin that allows the user to get more information about ida local variables with the help

16 Nov 26, 2022
An open souce video/music streamer based on MPV and piped.

🎶 Harmony Music An easy way to stream videos or music from Youtube from the command line while regaining your privacy. 📖 Table Of Contents ❔ What's

Zingy Tomato 16 Nov 15, 2022
Python3 based bittrex rest api wrapper

bittrex-rest-api This open source project was created to give an understanding of the Bittrex Rest API v1.1/v3.0 in pearl language. The sample file sh

4 Nov 15, 2022
Auto filter bot for python

Media Search bot Index channel or group files for inline search. When you post file on telegram channel or group this bot will save that file in datab

1 Dec 22, 2021
An async-ready Python wrapper around FerrisChat's API.

FerrisWheel An async-ready Python wrapper around FerrisChat's API. Installation Instructions Linux: $ python3.9 -m pip install -U ferriswheel Python 3

FerrisChat 8 Feb 08, 2022
A python package to easy the integration with Direct Online Pay (Mpesa, TigoPesa, AirtelMoney, Card Payments)

A python package to easy the integration with Direct Online Pay (DPO) which easily allow you easily integrate with payment options once without having to deal with each of them individually;

Jordan Kalebu 2 Nov 25, 2021
Joshua McDonagh 1 Jan 24, 2022
A python crypto trading bot on Binance using RSI in 25 Lines 🚀

RSI Crypto Trading Bot - Binance A Crypto Trading Bot on Binance trading BTCUSDT and ETHUSDT using RSI in 25 Lines of Code Getting Started Note Python

Blankly Finance 10 Dec 26, 2022
Previewer for VapourSynth scripts.

Standalone previewer for VapourSynth scripts Fork of Endilll's vapoursynth-preview (not maintained anymore) This program is meant to be paired with a

Irrational Encoding Wizardry 26 Dec 16, 2022
AWS EC2 S3 Automated With python

AWS_EC2_S3_Automated Description This programme is a Python3 script that utilizes Boto3 to automate the process of creating an AWS EC2 instance with a

niall_crowe 2 Nov 16, 2021
Music bot for Discord

Treble Music bot for Discord Youtube is after music bots on Discord. So we are here to fill the void. Introducing Treble, the next generation of Disco

Aja Khanal 0 Sep 16, 2022
Jika ada pertanyaan lebih lanjut, hubungi kontak dibawah ini. Terimakasih...

⚡ Lynx Userbot ⚡ Userbot Used for Fun on Telegram, and for Maintianing Your Group. This is a Repo Lynx-Userbot. This is Repo was Created by Axel From

29 Aug 30, 2021
You can connect with Sanila Ranatunga using this bot😉😉

Sanila-Ranatunga-s-Assistant-Bot You can connect with Sanila Ranatunga using this bot 😉 😉 Reach me on Telegram Sanila's Assistant Bot What is Telegr

Sanila Ranatunga 5 Feb 01, 2022
A discord.py bot template with Cogs implemented.

discord-cogs-template A discord.py bot template with Cogs implemented. Instructions Before you start ⚠ Basic knowledge of python is required. Steps If

censor 2 Sep 02, 2022
A Pancakeswap and Uniswap trading client (and bot) with limit orders, marker orders, stop-loss, custom gas strategies, a GUI and much more.

Pancakeswap and Uniswap trading client Adam A A Pancakeswap and Uniswap trading client (and bot) with market orders, limit orders, stop-loss, custom g

570 Mar 09, 2022
A simple Discord Bot that uses the free CryptoCompare API to display cryptocurrency prices

What is this? This is a simple Discord Bot coded in Python that uses the free CryptoCompare API to display cryptocurrency prices Download Use git to c

Kevin 10 Apr 17, 2022
wrapper for facebook messenger

pyfacebook pyfacebook library for python. Requirements common Help Got a question? File a GitHub issue. Contributing Bug Reports & Feature Requests Pl

Luis Mayta 3 Nov 12, 2021
Anchor Protocol Script that can save you from being liquidated!

Why My day job requires a fairly good amount of automation from time to time. Besides, I do like computers to work on what I cannot while I'm sleeping

126 Oct 16, 2022
Asynchronous multi-platform robot framework written in Python

NoneBot ✨ 跨平台 Python 异步机器人框架 ✨ 文档 · 安装 · 开始使用 · 文档打不开? 简介 NoneBot2 是一个现代、跨平台、可扩展的 Python 聊天机器人框架,它基于 Python 的类型注解和异步特性,能够为你的需求实现提供便捷灵活的支持。

NoneBot 3.1k Jan 04, 2023