如何在tar存档中重新映射uid / gid?

时间:2016-08-25 19:47:45

标签: linux shell terminal console tar

我有文件夹:

 UID     GID 
10000   10000   ./file1.txt
10000   10000   ./file2.txt
10400   10400   ./file3.txt
10402   10402   ./file4.txt
10052   10052   ./file5.txt

我想用下一个UID / GID创建tar.bz2档案:

UID     GID 
0   0    ./file1.txt
0   0    ./file2.txt
400 400  ./file3.txt
402 402  ./file4.txt
52  52   ./file5.txt

我想从所有uid和gid中减去10000并将结果保存为tar.bz2。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

据推测,您知道需要root权限才能更改UID / GID。以下脚本将起作用。可以通过使用命令行参数指定输入目录和输出.tar.bz2文件名来改进它。

#!/bin/bash

for file in `find . -type f -print`
do
    UID=`ls -lnd "$file" | awk '{print $3}'`
    GID=`ls -lnd "$file" | awk '{print $4}'`
    NEWUID=`expr $UID - 10000`
    NEWGID=`expr $GID - 10000`
    if [ "$NEWUID" -ge 0  -a "$NEWGID" -ge 0 ]; then
        echo chown ${NEWUID}:${NEWGID} "$file"
        chown ${NEWUID}:${NEWGID} "$file"
    fi
done
tar cvjSf /tmp/remap.tar.bz2 .

答案 1 :(得分:0)

以下Python脚本读取标准输入上的压缩包,并从其所有成员的uid和gid中减去10000:

#!/usr/bin/env python3
import tarfile
import sys

with tarfile.open(fileobj=sys.stdin.buffer, mode="r|*") as in_tar, \
    tarfile.open(fileobj=sys.stdout.buffer, mode="w|") as out_tar:
    for member in in_tar:
        member.uid = member.uid-10000
        member.gid = member.gid-10000
        if member.isfile():
            with in_tar.extractfile(member) as file:
                out_tar.addfile(member, file)
        else:
            out_tar.addfile(member)