一、前言

      s3cmd 是一款 Amazon S3 命令行工具。它不仅能上传、下载、同步,还能设置权限,下面是完整的安装使用指南。

二、安装与配置

1. 安装

pip install s3cmd
# 或
yum install python-s3cmd

2. 配置 

2.1 通过命令行传递参数配置

s3cmd --configure \
        --access_key=<access_key> \
        --secret_key=<secret_key> \
        --region=<region> \
        --host=<endpoint> \
        --host-bucket=<endpoint> \
        --no-ssl

2.2 通过配置文件配置

~/.s3cfg
[default]
access_key = <access_key>
secret_key = <secret_key>
bucket_location = <region>
host_base = <endpoint>
host_bucket = <endpoint>
use_https = False
human_readable_sizes = True
website_index = index.html

如果使用的是aws s3,配置可以精简为只有access_key和secret_key

[default]
access_key = <access_key>
secret_key = <secret_key>

三、使用 

1. 常用命令 

# 1、配置,主要是 Access Key ID 和 Secret Access Key
s3cmd --configure

# 2、列举所有 Buckets。(bucket 相当于根文件夹)
s3cmd ls

# 3、创建 bucket,且 bucket 名称是唯一的,不能重复,默认创建的 bucket 是公开的。
s3cmd mb s3://my-bucket-name

# 4、删除空 bucket
s3cmd rb s3://my-bucket-name

# 5、列举 Bucket 中的内容
s3cmd ls s3://my-bucket-name

# 6、上传
s3cmd put file.txt s3://my-bucket-name/file.txt

支持批量上传,直接指定多个文件,如
s3cmd put t.py s3://tccpoc/t.py up.py s3://tccpoc/up.py

如果上传终断,比如ctrl+c,会显示upload-id,按照指示,带上`--upload-id`就可以实现断点上传

# 7、上传并将权限设置为所有人可读
s3cmd put --acl-public file.txt s3://my-bucket-name/file.txt
--acl-private,也可以是私有

# 8、批量上传文件
s3cmd put ./* s3://my-bucket-name/

# 9、下载文件
s3cmd get s3://my-bucket-name/file.txt file.txt

支持批量下载,直接指定多个文件,如
s3cmd get s3://tccpoc/t.py s3://tccpoc/up.py

如果下载终断,比如ctrl+c,带上参数`--continue`,可以实现断点下载

# 10、批量下载
s3cmd get s3://my-bucket-name/* ./

# 11、删除文件,
s3cmd del s3://my-bucket-name/file.txt

支持批量删除,直接指定多个 bucket 对象,如
s3cmd del s3://my-bucket-name/file.txt s3://my-bucket-name/file2.txt

# 12、来获得对应的bucket所占用的空间大小
s3cmd du -H s3://my-bucket-name

上传大文件时,使用 --multipart-chunk-size-mb=size 指定的分片大小必须是4的倍数,否则上传会报 400(InvalidPartOrder)

2. 高级同步操作

  --exclude=GLOB				通配
  --exclude-from=FILE   从文件读取排除列表
  --rexclude=REGEXP     正则形式的匹配排除
  --rexclude-from=FILE  从文件读取正则形式的匹配排除
  
  --include=GLOB        通配
  --include-from=FILE   从文件读取文件列表
  --rinclude=REGEXP     正则匹配
  --rinclude-from=FILE  从文件读取正则匹配


示例1:排除、包含规则(--exclude 、--include),file1-1.txt被排除,file2-2.txt同样是txt格式却能被包含。
~/demo$ s3cmd sync --dry-run --exclude '*.txt' --include 'dir2/*' ./  s3://my-bucket-name/
exclude: dir1/file1-1.txt
upload: ./dir2/file2-2.txt -> s3://my-bucket-name/dir2/file2-2.txt

示例2:从文件中载入排除或包含规则。(--exclude-from、--include-from)
s3cmd sync  --exclude-from pictures.exclude ./  s3://my-bucket-name/

pictures.exclude 文件内容
# Hey, comments are allowed here ;-)
*.jpg
*.gif

3. 生命周期设置

# 设置文件1天后过期
# s3cmd modify s3://testabc/sqr.py --add-header x-delete-after:1

四、参考资料

1. https://s3tools.org/s3cmd

2. 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐