大网数据广告活动
服务器运维问答

How do untar as the current user by default?

· 52CE 我爱测

I have a batch of CentOS EC2 instances, which have an additional user added to them via ansible. Normally when unpacking a tarball, the owner is centos.centos (default login for EC2 Centos). When an additional user is created (vi…

问题原文

原帖链接 · SB. · CC BY-SA 4.0

I have a batch of CentOS EC2 instances, which have an additional user added to them via ansible. Normally when unpacking a tarball, the owner is centos.centos (default login for EC2 Centos). When an additional user is created (via ansible or manually) it no longer unpacks the tarball with the current user, but uses the uid/gid of the tarball creator. (9999.9999 on another system.)

I know there is a flag I can use when untarring (--no-same-owner) that removes the old permissions, but sets it as 0.0. Is there any way to get tar to automatically set permissions to the current user? I'm unsure if getting everyone untarring on these machines to add another step (chown) is a good idea.

社区高分解答

原帖链接 · ralz · CC BY-SA 4.0

If you run tar extract as non-root user it gets extracted as current user by default.

If you get root ownership on untared files you are running it as root user.

Regular user wouldn't be able to change ownership of extracted files to root, that would be a huge security issue (you could put setuid and 777 on any file and then get root privileges that way, by changing file ownership to root).

If you try to extract something from tar as regular user with --same-owner, in case it would try to extract files with ownership not same as user running untar command you will get "Cannot change ownership to uid x, gid x: Operation not permitted".

When you extract tar files as non-root user you extract them with the user running the untar command by default, because regular user cannot do chown to other users.

If you are running untar as root then they get extracted with same uid:gid ownership that they were packed with by default, because root user can do chown to any user.

If it gets run as root you can use sudo -u username or su username -c to run command as some other user, and you should get ownership as that user then.

You can also use cpio to extract from tar as some user:group

cpio -iR user:group -F file.tar

This is from tar manpage.

You should by default get same ownership as user running untar command when not root user.

   --no-same-owner
          Extract files as yourself (default for ordinary users).

   --same-owner
          Try extracting files with the same ownership as exists in
          the archive (default for superuser).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-12-24)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。