自动从S3存储桶中删除旧项目


15

有没有简单的方法在s3中设置存储桶以自动删除x天之前的文件?

Answers:




3

您可以使用s3cmd编写脚本以在存储桶中运行并根据前提条件删除文件。

您需要在其上面编写一些代码(bash,python)。

您可以从http://s3tools.org/s3cmd下载s3cmd


3

使用s3cmd实用程序
源删除旧存储桶的shell脚本:http : //shout.setfive.com/2011/12/05/deleting-files-older-than-specified-time-with-s3cmd-and-bash/

#!/bin/bash
# Usage: ./deleteOld "bucketname" "30 days"
s3cmd ls s3://$1 | while read -r line;  do

createDate=`echo $line|awk {'print $1" "$2'}`
createDate=`date -d"$createDate" +%s`
olderThan=`date -d"-$2" +%s`
if [[ $createDate -lt $olderThan ]]
  then 
    fileName=`echo $line|awk '{$1=$2=$3=""; print $0}' | sed 's/^[ \t]*//'`
    echo $fileName
    if [[ $fileName != "" ]]
      then
        s3cmd del "$fileName"
    fi
fi
done;

用法:./deleteOld“存储桶名称”“ 30天”,例如。s3:// dir1 / dir2 / dir3 / bucketname =“ dir1 / dir2 / dir3 /”永远不要忽略最后一个“ /”

如果文件名中有空格并且我需要在此之后打印所有列,该怎么办Video 1280x720 (2)13201781136780000000.mp4
Ramratan Gupta



1

我发现使用AWS CLI的解决方案删除批处理速度更快

#!/usr/bin/env php
<?php
//remove files which were created 24 hrs ago
$fcmd = 'aws s3 ls s3://<bucket>/<prefix>/ | awk \'{$3=""; print $0}\'';//remove file size and handle file with spaces

exec($fcmd, $output, $return_var);
$seconds_24_hour = 24 * 60 * 60;
$file_deleted_count = 0;
if (!empty($output)) {
    $deleted_keys = array();
    foreach ($output as $file) {
        $file_path = substr($file, 21);
        $file_time_stamp = substr($file, 0, 19); //2017-09-19 07:59:41
        if (time() - strtotime($file_time_stamp) > $seconds_24_hour) {
            $deleted_keys[]["Key"] = "<prefix>/" . $file_path;
            $file_deleted_count++;
        }
    }
    if (!empty($deleted_keys)) {
        $json_data_delete = array("Objects" => $deleted_keys);
        echo $cmd = ("aws s3api delete-objects --bucket <bucket> --delete '" . json_encode($json_data_delete) . "'");
        system($cmd);
    }
    echo "\n$file_deleted_count files deleted from content_media\n";
}

批量删除的参考/programming//a/41734090/1589444

使用100%通过案例处理具有空间的文件的参考/programming/36813327/how-to-display-only-files-from-aws-s3-ls-command

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.