AWS CLI 命令行工具获取 Linode Object Storage 上的文件列表

文章目录

    在服务器上挂载了 Linode Object Storage 之后,想要获取某个 bucket 下的所有文件列表。
    发现用 ls 命令非常慢,尤其是文件数量非常多的时候。例如 2 万多个文件,ls 命令不知道要等待多久才能返回结果。
    因为 Linode Object Storage 兼容 S3 协议,所以我想试试用 AWS CLI 工具来获取文件列表,将结果保存到文本文件中。

    因为本机是 Windows,WSL 下的 Ubuntu 还是 18.04 版本,版本有点旧了。所以,我打算直接在 Windows 上安装 AWS CLI 工具来使用。

    下载安装

    https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

    直接使用里面 msi 安装包下载安装即可。

    确认安装完成

    打开 PowerShell 或 CMD,输入以下命令:

    > aws --version
    aws-cli/2.32.23 Python/3.13.11 Windows/11 exe/AMD64
    

    说明安装成功。

    登录、身份认证

    如果直接执行以下命令,会提示无法找到凭证:

    > aws s3 ls --endpoint=https://ap-south-1.linodeobjects.com
    
    Unable to locate credentials. You can configure credentials by running "aws login".
    

    但是 aws login 的输入提示,我完全看不懂。。。所以改用 aws configure 命令来配置身份认证信息,
    即,输入 Access Key 和 Secret Key。

    > aws configure
    AWS Access Key ID [None]: MY_ACCESS_KEY_ID
    AWS Secret Access Key [None]: MY_SECRET_ACCESS_KEY
    Default region name [None]: us-east-1
    Default output format [None]: json
    

    查看 bucket 列表

    配置完成后,执行 ls 命令来测试一下,注意,这里需要加上 –endpoint 参数,指定 Linode Object Storage 的 endpoint 地址,否则会默认连接到 AWS 的 S3 服务。
    后续的所有命令都需要加上这个参数。

    > aws s3 ls --endpoint=https://us-east-1.linodeobjects.com
    2024-04-03 14:49:24 a.sunzhongwei.com
    2025-04-12 11:36:26 b.sunzhongwei.com
    

    不加 –endpoint 参数的话,会报错:

    An error occurred (InvalidAccessKeyId) when calling the ListObjectsV2 operation: The AWS Access Key Id you provided does not exist in our records.

    或者:

    An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: Unknown

    换个 region 的 endpoint 地址试试

    例如,换成新加坡的 endpoint 地址:

    > aws s3 ls --endpoint=https://ap-south-1.linodeobjects.com
    

    导出某个目录下的所有文件列表

    例如,导出 a.sunzhongwei.com/cache/ 目录下的

    aws s3 ls s3://a.sunzhongwei.com/cache/ --recursive --endpoint=https://us-east-1.linodeobjects.com > filelist.txt
    

    recursive 参数表示递归列出所有子目录下的文件。

    注意,s3:// 后面是 bucket 名称,然后是目录路径。不要加上 endpoint 地址。endpoint 地址是通过 –endpoint 参数传递的。

    处理返回的文件列表数据格式

    注意,如果是 Windows 11 下的 PowerShell 执行上述命令,导出的文本文件 filelist.txt 会是 utf16le 编码格式的。
    utf16le 编码需要转成 utf8 才能继续使用 linux shell 工具处理。转换很简单,用记事本打开,然后另存为 utf8 编码格式即可。

    然后用 VSCode 打开文件,确认一下返回的数据格式,在 WSL Ubuntu 下使用 awk 命令处理数据,例如提取出文件路径:

    awk '{print $NF}' filelist.txt > result.txt
    

    $NF 代表每一行的最后一列。

    PowerShell 里面没有 awk,我即便用 AI 生成 PowerShell 命令,我也看不懂里面的参数格式,太抽象了,还是 Linux awk 命令更直观一些。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式