xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Linux shell su command All In One

Linux shell su command All In One

su !== sudo

substitute user => su, 替换用户/切换用户

substitute user do => su do

superuser do => sudo, 执行超级管理员用户权限

su

su - run a command with substitute user and group ID
su - 使用替代用户组 ID运行命令

su - switch user 切换用户

sudo === super user do

  1. 生效一次
  2. 需要输入密码
$ man su

$ man su > ~/Desktop/man-su.md

$ cat ~/Desktop/man-su.md

image

$ cat ~/Desktop/man-su.md
SU(1)                                     User Commands                                    SU(1)

NAME
       su - run a command with substitute user and group ID

SYNOPSIS
       su [options] [-] [user [argument...]]

DESCRIPTION
       su allows commands to be run with a substitute user and group ID.

       When called with no user specified, su defaults to running an interactive shell as root.
       When user is specified, additional arguments can be supplied, in which case they are
       passed to the shell.

       For backward compatibility, su defaults to not change the current directory and to only
       set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is
       not root). It is recommended to always use the --login option (instead of its shortcut -)
       to avoid side effects caused by mixing environments.

       This version of su uses PAM for authentication, account and session management. Some
       configuration options found in other su implementations, such as support for a wheel
       group, have to be configured via PAM.

       su is mostly designed for unprivileged users, the recommended solution for privileged
       users (e.g., scripts executed by root) is to use non-set-user-ID command runuser(1) that
       does not require authentication and provides separate PAM configuration. If the PAM
       session is not required at all then the recommended solution is to use command
       setpriv(1).

       Note that su in all cases uses PAM (pam_getenvlist(3)) to do the final environment
       modification. Command-line options such as --login and --preserve-environment affect the
       environment before it is modified by PAM.

       Since version 2.38 su resets process resource limits RLIMIT_NICE, RLIMIT_RTPRIO,
       RLIMIT_FSIZE, RLIMIT_AS and RLIMIT_NOFILE.

OPTIONS
       -c, --command=command
           Pass command to the shell with the -c option.

       -f, --fast
           Pass -f to the shell, which may or may not be useful, depending on the shell.

       -g, --group=group
           Specify the primary group. This option is available to the root user only.

       -G, --supp-group=group
           Specify a supplementary group. This option is available to the root user only. The
           first specified supplementary group is also used as a primary group if the option
           --group is not specified.

       -, -l, --login
           Start the shell as a login shell with an environment similar to a real login:

           •   clears all the environment variables except TERM and variables specified by
               --whitelist-environment

           •   initializes the environment variables HOME, SHELL, USER, LOGNAME, and PATH

           •   changes to the target user’s home directory

           •   sets argv[0] of the shell to '-' in order to make the shell a login shell

       -m, -p, --preserve-environment
           Preserve the entire environment, i.e., do not set HOME, SHELL, USER or LOGNAME. This
           option is ignored if the option --login is specified.

       -P, --pty
           Create a pseudo-terminal for the session. The independent terminal provides better
           security as the user does not share a terminal with the original session. This can be
           used to avoid TIOCSTI ioctl terminal injection and other security attacks against
           terminal file descriptors. The entire session can also be moved to the background
           (e.g., su --pty - username -c application &). If the pseudo-terminal is enabled, then
           su works as a proxy between the sessions (sync stdin and stdout).

           This feature is mostly designed for interactive sessions. If the standard input is
           not a terminal, but for example a pipe (e.g., echo "date" | su --pty), then the ECHO
           flag for the pseudo-terminal is disabled to avoid messy output.

       -s, --shell=shell
           Run the specified shell instead of the default. The shell to run is selected
           according to the following rules, in order:

           •   the shell specified with --shell

           •   the shell specified in the environment variable SHELL, if the
               --preserve-environment option is used

           •   the shell listed in the passwd entry of the target user

           •   /bin/sh

       If the target user has a restricted shell (i.e., not listed in /etc/shells), the --shell
       option and the SHELL environment variables are ignored unless the calling user is root.

       --session-command=command
           Same as -c, but do not create a new session. (Discouraged.)

       -w, --whitelist-environment=list
           Don’t reset the environment variables specified in the comma-separated list when
           clearing the environment for --login. The whitelist is ignored for the environment
           variables HOME, SHELL, USER, LOGNAME, and PATH.

       -h, --help
           Display help text and exit.

       -V, --version
           Print version and exit.

SIGNALS
       Upon receiving either SIGINT, SIGQUIT or SIGTERM, su terminates its child and afterwards
       terminates itself with the received signal. The child is terminated by SIGTERM, after
       unsuccessful attempt and 2 seconds of delay the child is killed by SIGKILL.

CONFIG FILES
       su reads the /etc/default/su and /etc/login.defs configuration files. The following
       configuration items are relevant for su:

       FAIL_DELAY (number)
           Delay in seconds in case of an authentication failure. The number must be a
           non-negative integer.

       ENV_PATH (string)
           Defines the PATH environment variable for a regular user. The default value is
           /usr/local/bin:/bin:/usr/bin.

       ENV_ROOTPATH (string), ENV_SUPATH (string)
           Defines the PATH environment variable for root. ENV_SUPATH takes precedence. The
           default value is /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin.

       ALWAYS_SET_PATH (boolean)
           If set to yes and --login and --preserve-environment were not specified su
           initializes PATH.

           The environment variable PATH may be different on systems where /bin and /sbin are
           merged into /usr; this variable is also affected by the --login command-line option
           and the PAM system setting (e.g., pam_env(8)).

EXIT STATUS
       su normally returns the exit status of the command it executed. If the command was killed
       by a signal, su returns the number of the signal plus 128.

       Exit status generated by su itself:

       1
           Generic error before executing the requested command

       126
           The requested command could not be executed

       127
           The requested command was not found

FILES
       /etc/pam.d/su
           default PAM configuration file

       /etc/pam.d/su-l
           PAM configuration file if --login is specified

       /etc/default/su
           command specific logindef config file

       /etc/login.defs
           global logindef config file

NOTES
       For security reasons, su always logs failed log-in attempts to the btmp file, but it does
       not write to the lastlog file at all. This solution can be used to control su behavior by
       PAM configuration. If you want to use the pam_lastlog(8) module to print warning message
       about failed log-in attempts then pam_lastlog(8) has to be configured to update the
       lastlog file as well. For example by:

          session required pam_lastlog.so nowtmp

HISTORY
       This su command was derived from coreutils' su, which was based on an implementation by
       David MacKenzie. The util-linux version has been refactored by Karel Zak.

SEE ALSO
       setpriv(1), login.defs(5), shells(5), pam(8), runuser(1)

REPORTING BUGS
       For bug reports, use the issue tracker at
       https://github.com/util-linux/util-linux/issues.

AVAILABILITY
       The su command is part of the util-linux package which can be downloaded from Linux
       Kernel Archive <https://www.kernel.org/pub/linux/utils/util-linux/>.

util-linux 2.38.1                          2022-05-11                                      SU(1)
eric@rpi3b:~ $ 

locale bugfix

$ man su
man: can't set the locale; make sure $LC_* and $LANG are correct
$ cat /etc/locale.gen

$ sudo vim /etc/locale.gen

$ sudo locale-gen
Generating locales (this might take a while)...
  en_GB.UTF-8... done
  zh_CN.UTF-8... done
Generation complete.

$ locale
LANG=zh_CN.UTF-8
LANGUAGE=
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_COLLATE="zh_CN.UTF-8"
LC_MONETARY="zh_CN.UTF-8"
LC_MESSAGES="zh_CN.UTF-8"
LC_PAPER="zh_CN.UTF-8"
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT="zh_CN.UTF-8"
LC_IDENTIFICATION="zh_CN.UTF-8"
LC_ALL=zh_CN.UTF-8

切到帐号

$ su do

demos

树莓派电源管理 / Raspberry Pi Power Management

# iw
$ /sbin/iw dev wlan0 get power_save
Power save: off

$ iw dev wlan0 get power_save
Power save: off

# iwconfig
$ iwconfig wlan0 power off

# iwconfig
eric@rpi3b:~ $ iwconfig
lo        no wireless extensions.

eth0      no wireless extensions.

wlan0     IEEE 802.11  ESSID:"603"  
          Mode:Managed  Frequency:2.437 GHz  Access Point: 00:12:93:18:AF:AF   
          Bit Rate=57.7 Mb/s   Tx-Power=31 dBm   
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality=51/70  Signal level=-59 dBm  
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:1  Invalid misc:0   Missed beacon:0
# iwconfig wlan0
eric@rpi3b:~ $ iwconfig wlan0
wlan0     IEEE 802.11  ESSID:"603"  
          Mode:Managed  Frequency:2.437 GHz  Access Point: 00:12:93:18:AF:AF   
          Bit Rate=43.3 Mb/s   Tx-Power=31 dBm   
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off
          Link Quality=49/70  Signal level=-61 dBm  
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:1  Invalid misc:0   Missed beacon:0
# iwconfig wlan0 | grep "Power Management"
eric@rpi3b:~ $ iwconfig wlan0 | grep "Power Management"
          Power Management:off

image

Linux shell & shell script & parent shell & child shell

login shell
logout shell

Raspberry Pi 使用 /etc/rc.local 来禁用 Wi-Fi 的电源管理 Power Management:off

  1. 问题描述 ❓

明明在命令行测试/etc/rc.local 脚本没有问题,
但是为什么 reboot 重启系统后,在命令行中却没有输出 /etc/rc.local 脚本中的 echo 语句呢?

eric@rpi3b:~ $ /etc/rc.local
/etc/rc.local testing begin ✅
My IP address is 192.168.101.17 
Error for wireless request "Set Power Management" (8B2C) :
    SET failed on device wlan0 ; Operation not permitted.
eric@rpi3b:~ $ sudo /etc/rc.local
/etc/rc.local testing begin ✅
My IP address is 192.168.101.17 
/etc/rc.local testing end ✅
eric@rpi3b:~ $ 

image

image

/etc/rc.local

eric@rpi3b:~ $ cat /etc/rc.local
#!/bin/sh -e


# 可执行脚本

echo "/etc/rc.local testing begin ✅"


# add below line before exit 0 ✅
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

# 禁用电源关闭

# permition error ???
iwconfig wlan0 power off


echo "/etc/rc.local testing end ✅"

# sudo ??? need password ❌


# sudo /sbin/iw dev wlan0 set power_save off
# su eric -c "exec /sbin/iw dev wlan0 set power_save off"


# su eric -c "exec /home/eric/Desktop/echo-test.sh"


exit 0

~/.bashrc / /home/eric/.bashrc

$ cat ~/.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)


# .bashrc 测试

echo ".bashrc testing ✅"
# ... 省略



  1. 问题分析

使用 sudo 测试 shell 脚本可以成功,说明该 shell 脚本运行没有问题,即不存在脚本语法和权限问题!

/etc/rc.local/home/eric/.bashrc / ~/.bashrc 脚本文件的所有者权限不同, shell 脚本运行的 shell 进程也不同;

每次启动一个新 shell, 都会执行一次 .bashrc 脚本文件 ✅

  1. 总结

/etc/rc.local/home/eric/.bashrc / ~/.bashrc 脚本文件的所有者和权限不同,shell 脚本运行的 shell 进程也不同;

因为,用户 eric 使用 SSH 远程登录系统后,~/.bashrc 脚本运行在 eric 的子 shell 进程中, 命令行界面输出的 echo 语句仅仅是 /home/eric/.bashrc 中的;
/etc/rc.local 运行在 root 的子 shell 进程中,所以看不到 /etc/rc.local 脚本中的 echo 语句输出; ✅

即, 由于 /etc/rc.local 脚本的所有者是 root,输出的 echo 语句是对当前登录用户 eric 是不可见的,但是 /etc/rc.local 脚本会自动执行,当有用户登录到系统的时候;

# chmod +x 755 文件所有者和文件权限 ✅
eric@rpi3b:~ $ ls -al /etc/rc.local
-rwxr-xr-x 1 root root 530  3月 7日 00:09 /etc/rc.local
# chmod 644 文件所有者和文件权限 ✅
eric@rpi3b:~ $ ls -al ~/.bashrc
-rw-r--r-- 1 eric eric 3570  3月 6日 15:33 /home/eric/.bashrc

su vs sudo

鸟哥的 Linux 私房菜

https://linux.xgqfrms.xyz/linux_basic/0410accountmanager.htm#:~:text=的用法啦!-,su,-su 是最

https://linux.xgqfrms.xyz/linux_basic/0410accountmanager.htm#:~:text=來處理即可!-,sudo,-相對於 su

第十三章、Linux帐号管理与ACL权限设置

https://linux.vbird.org/linux_basic/centos7/0410accountmanager.php

13.4 使用者身份切換

https://linux.vbird.org/linux_basic/centos7/0410accountmanager.php#userswitch

image
image

image

https://www.cnblogs.com/xgqfrms/p/16972247.html

shell script 2>&1 二合一 输出错误信息 log

image

eric@rpi3b:~ $ sudo vim /etc/rc.local
eric@rpi3b:~ $ cat /etc/rc.local

eric@rpi3b:~ $ sudo vim /etc/rc.local.md
eric@rpi3b:~ $ cat /etc/rc.local.md

#!/bin/sh -e


# 可执行脚本

# > 覆盖,重定向
# echo "/etc/rc.local testing begin ✅" > /etc/rc.local.md 2>&1
# >> 追加,重定向
echo "/etc/rc.local testing begin ✅" >> /etc/rc.local.md 2>&1

# ...


echo "/etc/rc.local testing end ✅" >> /etc/rc.local.md 2>&1

image

https://www.cnblogs.com/xgqfrms/p/16903732.html

shell 脚本获取当前系统的时间戳, 写入 log 文件 ?

# DATE

>
>>

2>&1


2>&1 二合一重定向标准错误输出到标准输出

标准输入 stdin
标准输出 stdout
标准错误输出 stderr

#!/bin/sh -e


# 可执行脚本
# 2>&1 重定向错误输出到标准输出
# >> 追加到文件末尾
echo "/etc/rc.local testing begin ✅" >> /etc/rc.local.md 2>&1


# add below line before exit 0 ✅
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

# 禁用电源关闭

# permition error ???
iwconfig wlan0 power off


echo "/etc/rc.local testing end ✅" >> /etc/rc.local.md 2>&1

# 测试需要 sudo & need password
# sudo /sbin/iw dev wlan0 set power_save off
# rc.local 脚本,login shell 自动执行时候,不需要
# /sbin/iw dev wlan0 set power_save off


# switch user
# su eric -c "exec /sbin/iw dev wlan0 set power_save off"


# su eric -c "exec /home/eric/Desktop/echo-test.sh"


exit 0

# https://www.cnblogs.com/xgqfrms/p/16481735.html
# https://www.cnblogs.com/xgqfrms/p/18756083.html

https://www.cnblogs.com/xgqfrms/p/16903732.html

父子 shell 与 环境变量

https://www.cnblogs.com/xgqfrms/p/17719773.html

rc.local

multiuser

runlevel

https://unix.stackexchange.com/questions/49626/purpose-and-typical-usage-of-etc-rc-local

whiptail --msgbox

https://stackoverflow.com/questions/73325002/handle-errors-in-whiptail-gauge-with-a-msgbox

.profile 用户级启动配置文件

Linux 系统中登录 shell 的时候,会从下面的 5 个启动文件里读取命令;

# 系统级,所有登录用户都会先启动这个文件
$ cat /etc/profile

# 用户级,按照Linux 发行版中实际存在的文件个数,依次进行启动
$ cat $HOME/.bash_profile
$ cat $HOME/.bashrc
$ cat $HOME/.bash_login
$ cat $HOME/.profile

# 系统级 ??? Raspberry Pi
$ cat /etc/rc.local

https://www.cnblogs.com/xgqfrms/p/17343088.html

image

image

.profile

~/.profile
~/.bash_profile
~/.bash_login

$ cat ~/.profile
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
	. "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi

echo "每次登录自动执行脚本 ✅"
bash /home/pi/Desktop/ip-program.sh

$ sudo vim .profile
$ source ~/.profile

the difference between boot or login

Running A Program At Start UP A Beginner's Guide.pdf / login-boot.pdf

https://github.com/xgqfrms/cdn/blob/gh-pages/Linux/login-boot.pdf

image

https://www.cnblogs.com/xgqfrms/p/17323041.html#5168612

refs

https://www.cnblogs.com/xgqfrms/p/16481735.html

https://www.atatus.com/blog/essential-guide-to-sudo-and-su-in-linux/

https://superuser.com/questions/408990/how-do-i-log-out-of-sudo-su



©xgqfrms 2012-2025

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(4)  评论(5编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2023-03-06 AOP 面向切面编程 All In One
2023-03-06 HTTP Status Code 307 All In One
2023-03-06 How DNS works comic All In One
2023-03-06 developer mind mapping All In One
2021-03-06 codesandbox & online vscode editor
2021-03-06 import component with rename All In One
2021-03-06 stackblitz & online vscode editor
点击右上角即可分享
微信分享提示