sudoなしで他のユーザーでコマンドリストを実行できないのはなぜですか?

sudoなしで他のユーザーでコマンドリストを実行できないのはなぜですか?

この質問は、他のフォーラムでさまざまな方法で質問されました。ただし、bashで次のことができない理由の適切な説明はありません。

#!/bin/bash
command1
SWITCH_USER_TO rag
command2
command3

一般的に推奨される方法は

#!/bin/bash
command1
sudo -u rag command2
sudo -u rag command3

しかし、bashスクリプトの実行中にある時点で別のbashユーザーに変更し、残りのコマンドを他のユーザーとして実行できないのはなぜですか?

ベストアンサー1

情報はすでに出ています。私の他の答え、しかしそこに埋もれています。だからここに追加する必要があると思いました。

bashユーザーの変更に関する規定はありませんがzsh

zsh次の変数に値を割り当ててユーザーを変更できます。

  • $EUID:有効なユーザーIDを変更します(それ以上ではありません)。通常、実際のユーザーIDと保存されたセットユーザーID(setuid実行可能ファイルから呼び出された場合)の間、またはeuidが0の場合は、別のIDにeuidを変更できます。
  • $UID:有効ユーザーID、実ユーザーID、保存ユーザーIDを新しい値に変更します。新しい値がゼロ以外の場合、3つの値がすべて同じ値に設定されている場合は、他の値に変更できないため、戻りません。
  • $EGID$GID:同じですが、グループIDのものです。
  • $USERNAMEsudoまたはを使用するのと同じですsu。 euid、ruid、ssuidをそれぞれのユーザーのuidに設定します。また、ユーザーデータベースで定義されているグループメンバーシップに基づいて、egid、rgid、ssgid、および補足グループを設定します。 forと同様に$UID設定しないと何も返されませんが、forと同様にサブシェルのユーザーだけを変更できます。$USERNAMEroot$UID

このスクリプトを「root」として実行する場合:

#! /bin/zsh -
UID=0 # make sure all our uids are 0

id -u # run a command as root

EUID=1000

id -u # run a command as uid 1000 (but the real user id is still 0
      # so that command would be able to change its euid to that.
      # As for the gids, we only have those we had initially, so 
      # if started as "sudo the-script", only the groups root is a
      # member of.

EUID=0 # we're allowed to do that because our ruid is 0. We need to do
       # that because as a non-priviledged user, we can't set our euid
       # to anything else.

EUID=1001 # now we can change our euid since we're superuser again.

id -u # same as above

これで、ユーザーを変更するにはsudoサブシェルsuを使用する必要があります。それ以外の場合は一度だけ実行できます。

#! /bin/zsh -

id -u # run as root

(
  USERNAME=rag
  # that's a subshell running as "rag"

  id # see all relevant group memberships are applied
)
# now back to the parent shell process running as root

(
  USERNAME=stephane
  # another subshell this time running as "stephane"

  id
)

おすすめ記事