![bash 스크립트를 사용하여 스크립트/명령을 루트/sudo로 실행할지 여부를 결정하는 방법](https://linux55.com/image/174424/bash%20%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%2F%EB%AA%85%EB%A0%B9%EC%9D%84%20%EB%A3%A8%ED%8A%B8%2Fsudo%EB%A1%9C%20%EC%8B%A4%ED%96%89%ED%95%A0%EC%A7%80%20%EC%97%AC%EB%B6%80%EB%A5%BC%20%EA%B2%B0%EC%A0%95%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95.png)
나는 팔로우하고 있다https://lifehacker.com/add-a-handy-separator-Between-commands-in-your-terminal-5840450Linux 터미널에서 명령 사이에 멋진 구분 기호를 만듭니다. 특히 CentOS 8.
명령을 실행하는 사용자의 사용자 이름을 출력하도록 스크립트를 수정하려고 합니다.
여기이것이 내가 생각해 낸 것입니다.
# Fill with minuses
# (this is recalculated every time the prompt is shown in function prompt_command):
fill="--- "
reset_style='\[\033[00m\]'
if [ -z "$VIM" ];
then status_style=$reset_style'\[\033[0;90m\]' # gray color; use 0;37m for lighter color
else status_style=$reset_style'\[\033[0;90;107m\]'
fi
prompt_style=$reset_style
command_style=$reset_style'\[\033[1;29m\]' # bold black
# Prompt variable:
OLD_PS1="$PS1"
PS1="$status_style"'$fill $USER \t\n'"$prompt_style$OLD_PS1$command_style"
# Reset color for command output
# (this one is invoked every time before a command is executed):
trap 'echo -ne "\e[0m"' DEBUG
function prompt_command {
# create a $fill of all screen width minus the time string and a space and USER and a space:
let fillsize=${COLUMNS}-10-${#USER}
fill=""
while [ "$fillsize" -gt "0" ]
do
fill="-${fill}" # fill with underscores to work on
let fillsize=${fillsize}-1
done
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
bname=`basename "${PWD/$HOME/~}"`
echo -ne "\033]0;${bname}: ${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"
;;
*)
;;
esac
}
PROMPT_COMMAND=prompt_command
15행에서는 $USER
생성된 콘텐츠에 " " 및 " "를 추가합니다.
추가 공백과 변수 길이를 포함하도록 25행이 변경되었습니다.$USER
내가 원하는 것과 똑같아 보입니다.
그러나 명령을 실행하거나 실행하지 않을 경우 출력할 코드를 업데이트하고 싶습니다 sudo
. 이상적으로는 이름을 루트 또는 루트 사용자 이름으로 변경합니다.
나는 주로 를 사용하려고 시도했지만 whoami
항상 루트 대신 내 사용자 이름을 반환합니다. 실행하면 sudo whoami
루트 액세스 권한을 얻을 수 있지만 스크립트에서는 얻을 수 없습니다. 저도 EUID
주사위 없이 시도해 봤습니다.
이 시점에서는 코드를 참조가 있는 작동 상태로 두었지만 $USER
원하는 대로 변경할 의향이 있습니다.
솔루션 제공업체u/p루모
솔루션의 한계:
- sudo --user=some_user...와 같은 일부 사례는 다루지 않습니다. awk 스크립트를 추가로 향상시키는 것이 상당히 쉽다고 생각합니다.
- 히스토리에 의존하기 때문에 HISTControl=ignoreboth를 사용하고 앞에 공백이 있는 명령을 실행하는 경우와 같이 히스토리에 없는 명령에는 작동하지 않습니다.
# Fill with minuses
# (this is recalculated every time the prompt is shown in function prompt_command):
fill="--- "
reset_style='\[\033[00m\]'
if [ -z "$VIM" ];
then status_style=$reset_style'\[\033[0;90m\]' # gray color; use 0;37m for lighter color
else status_style=$reset_style'\[\033[0;90;107m\]'
fi
prompt_style=$reset_style
command_style=$reset_style'\[\033[1;29m\]' # bold black
# Prompt variable:
OLD_PS1="$PS1"
PS1="$status_style"'$fill $name \t\n'"$prompt_style$OLD_PS1$command_style"
# Reset color for command output
# (this one is invoked every time before a command is executed):
trap 'echo -ne "\e[0m"' DEBUG
function prompt_command {
# create a $fill of all screen width minus the time string and a space and USER and a space:
name=$(fc -l -1 | awk -v u="$USER" '{if ($2=="sudo") { if ($3=="-u") u=$4; else u="root"; }; printf "%s",u}')
let fillsize=${COLUMNS}-10-${#name}
fill=""
while [ "$fillsize" -gt "0" ]
do
fill="-${fill}" # fill with underscores to work on
let fillsize=${fillsize}-1
done
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
bname=`basename "${PWD/$HOME/~}"`
echo -ne "\033]0;${bname}: ${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"
;;
*)
;;
esac
}
PROMPT_COMMAND=prompt_command
답변1
prompt_command
어떤 사용자가 마지막 명령을 실행했는지 알 수 없습니다 . prompt_command
항상 일반 사용자 세션에서 실행하십시오.
해결 방법으로. 읽고 구문 분석할 수 있습니다 history
.
예를 들어 fc -l -1
마지막 명령을 인쇄 awk ...
하고 구문 분석하는 경우입니다.
온라인 으로 #15
변경$USER
$name
줄에 #23
다음을 추가합니다 .
name=$(fc -l -1 | awk -v u="$USER" '{if ($2=="sudo") { if ($3=="-u") u=$4; else u="root"; }; printf "%s",u}')
온라인 으로 변경하세요 #25
.${#USER}
${#name}
이는 및 에 대해 root
인쇄 됩니다 .sudo some command
some_user
sudo -u some_user some command
하지만 이 솔루션에는 몇 가지 제한 사항이 있습니다.
- 예를 들어, 일부 상황은 다루지 않습니다
sudo --user=some_user ...
. 나는 스크립트를 더욱 향상시키는 것이 상당히 쉽다고 생각합니다awk
. - 에 의존하기 때문에
history
에 존재하지 않는 명령을 사용할 수 없습니다history
. 예를 들어HISTCONTROL=ignoreboth
공백이 앞에 오는 명령을 사용하고 실행하는 경우입니다.
답변2
유효한 사용자 ID(euid) 인쇄
/bin/id -u