Amazon S3 Backup.py 1020 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import tarfile
  2. import boto3
  3. import lzma
  4. from botocore.exceptions import NoCredentialsError
  5. from zipfile import ZipFile
  6. aws_access_key = "AWS Key"
  7. secret_access_key = "AWS Secret Access Key"
  8. zip_file_name = "file_name.tar.xz"
  9. dirName = "Directory of items to compress"
  10. def upload_to_aws(local_file, bucket, s3_file):
  11. s3 = boto3.client('s3', aws_access_key_id=aws_access_key,
  12. aws_secret_access_key=secret_access_key)
  13. try:
  14. s3.upload_file(local_file, bucket, s3_file)
  15. print("Upload Successful")
  16. return True
  17. except FileNotFoundError:
  18. print("The file was not found")
  19. return False
  20. except NoCredentialsError:
  21. print("Credentials not available")
  22. return True
  23. if __name__ == '__main__':
  24. xz_file = lzma.LZMAFile(zip_file_name, mode='w')
  25. with tarfile.open(mode='w', fileobj=xz_file) as tar_xz_file:
  26. tar_xz_file.add(dirName)
  27. xz_file.close()
  28. uploaded = upload_to_aws("local_file.tar.xz", "bucket", "s3_file")