Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The usage of sudo Syntax in Linux system

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "the usage of sudo grammar in Linux system". In the daily operation, I believe that many people have doubts about the usage of sudo grammar in Linux system. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the usage of sudo grammar in Linux system". Next, please follow the editor to study!

Sudo

Sudo allows the user to execute commands as superuser or as another user specified by security policy. Sudo supports security policy plug-ins and input / output log plug-ins. Third parties can develop and distribute their own policies and Imax O logging plug-ins to work seamlessly with the sudo front end. The default security policy is sudoers, which is configured through the file / etc/sudoers or through LDAP.

The security policy determines what rights the user needs to run sudo. This policy may require users to authenticate using passwords or other authentication mechanisms. If authentication is required, sudo exits if the user's password is not entered within a configurable time limit. This limit is policy specific; the default password prompt timeout for sudoers security policy is 5 minutes.

The security policy may support credential caching, allowing users to run sudo again without authentication. The sudoers policy caches credentials for 5 minutes unless overridden in sudoers (5). By running sudo with the "- v" option, the user can update the cached credentials without running the command.

Security policies may record the success and failure of using sudo. The input and output of running commands may also be recorded if the Icano plug-in is configured.

The scope of this command: RedHat, RHEL, Ubuntu, CentOS, SUSE, openSUSE, Fedora.

1. Grammar

Sudo-h |-K |-k |-V

Sudo-v [- AknS] [- g group name | # gid] [- p prompt] [- u user name | # uid]

Sudo-l [l] [- AknS] [- g group name | # gid] [- p prompt] [- U user name] [- u user name | # uid] [command]

Sudo [- AbEHnPS] [- C fd] [- g group name | # gid] [- p prompt] [- r role] [- t type] [- u user name | # uid] [VAR=value]-I |-s [command]

Sudoedit [- AnS] [- C fd] [- g group name | # gid] [- p prompt] [- u user name | # uid] file.

2. List of options

Option

Description

-h

Help information

-V

Display command version information

A

Typically, if the sudo requires a password, it reads the password from the user terminal. If the-A (Askpass) option is specified, a (possibly Graphi cal) helper is executed to read the user's password and output the password to standard output. If the SUDO_ASKPASS environment variable is set, specify the path to the helper. Otherwise, this value will be used if "/ etc/sudo.conf" contains the path to the askpass program. For example:

# Path to askpass helper program

Path askpass / usr/X11R6/bin/ssh-askpass

-b

Run the command in the background. Note that if you use the-b option, you cannot use the shell job control to manipulate the process. Most interactive commands do not work in background mode.

-C fd

Typically, sudo closes all open file descriptors except standard input, standard output, and standard error. The "- C" option allows the user to specify a starting point above standard error (file descriptor 3). Values less than 3 are not allowed. Security policies may limit users' ability to use the "- C" option. The sudoers policy only allows users to use the "- C" option only when "closefrom_override" is turned on.

-E

The run time preserves the user environment. The "- E" option indicates to the security policy that users want to save their existing environment variables. If the "- E" option is specified and the user does not have permission to retain the environment, the security policy may return an error

-e

Edit the command file instead of executing the command. When querying the security policy, use the string "sudoedit" instead of the command. If the user is authenticated by the policy, there are three steps to do: 1) make a temporary copy; 2) run the editor specified by the policy to edit the temporary file. The sudoers policy uses the environment variables SUDO_EDITOR, VISUAL, and EDITOR in turn. If these three environment variables are not set, the first program listed in the editor sudoers (5) option is used; 3) if the temporary file is modified, the temporary file is copied back to its original location and the temporary version is removed.

If the specified file does not exist, it will be created. Note that unlike most commands that sudo runs, the editor runs in the environment that invokes the user. If for some reason sudo cannot update the file with the specified editor, the user will be warned that the edited copy will remain in the temporary file.

-g group

The command is executed by the specified user group. Use # gid instead of the group name. Note that shell requires a backslash ('\') to escape'#'

-H

The-H (Home) option requires the security policy to set the "HOME" environment variable to the home directory of the target user specified in the password database. Depending on policy, this option is likely to be the default.

-I [command]

Simulates the initial login. The "- I" option runs the shell specified by the password database entry of the target user as the login shell. This means that shell will read login-specific resource files, such as ".profile" or ".login". If a command is specified, it is passed to shell for execution through the-c option of shell. If no command is specified, an interactive shell is executed. Sudo attempts to change to the user's home directory before running shell. The security policy should initialize the environment to a minimum set of variables, similar to the set of variables that exist when a user logs in.

-K

Delete user cached credentials and cannot be used with commands or other options. This option does not require a password. Not all security policies support credential caching.

-k [command]

When used alone, the sudo option invalidates the user's cached credentials. The next time you run sudo, you will need a password. This option does not require a password and is added to allow the user to revoke sudo permissions from the .logout file. Not all security policies support credential caching.

When used with commands or options that may require a password, the "- k" option causes sudo to ignore the user's cached credentials. Therefore, sudo prompts for a password (if the security policy requires a password) and does not update the user's cached credentials.

-l [l] [command]

Lists the commands that the user can execute. If no command is specified, the-l (List) option lists the commands allowed by the calling user (or the user specified by the-u option) on the current host. If a command is specified and allowed by security policy, the full path to the command and any command-line arguments are displayed. If a command is specified but execution is not allowed, sudo exits with a status value of 1. If you use the l parameter (that is,-ll), a longer list format is used.

-n

Non-interactive, the user will not be prompted. The-n option prevents sudo from prompting the user for a password. If a password is required to run the command, sudo displays an error message and exits.

-P

Save the group vector. The "- P" option makes sudo keep the calling user's group vector unchanged. By default, the sudoers policy initializes the group vector to the list of groups in which the target user resides. However, the actual valid group ID is still set to match the target user.

-p prompt

Use the specified password prompt statement:

% H, extend the host name, including the domain name

% h, extending the host name, excluding the domain name

% p, extended to the name of the user whose password was requested

% U, extended to the login of the user running the command

% u, extended to the login of the calling user

%%, two consecutive'% 'characters are folded into one'% 'character

-r role

The "- r" option causes the new security context to have the role specified by role.

-S

Read the password from the standard input, not from the terminal. The password must be followed by a newline character

-s [command]

If the shell environment variable is set, the "- s" option runs the shell specified by the shell environment variable, or the shell specified in the password database. If a command is specified, the command is passed to shell for execution through the "- c" option of shell. If no command is specified, an interactive shell is executed.

-t type

The "- t" option results in a new type of security context, or if no type is specified, the default type is derived from the specified role.

-U user

The "- U" option is used with the "- l" option to list the permissions of the specified user. Security policies may restrict the privileges of listing other users. The sudoers policy only allows users with full privileges on root or the current host to use this option.

-u user

Executes the instruction as the specified user. The "- u" option causes sudo to run the specified command as a user other than root. Specify # uid instead of a user name. When running the command as uid, many shell require that "#" be escaped with a backslash. Security policy may restrict UID to password databases. The sudoers policy allows UID that does not exist in the password database, as long as the targetpw option is not set. This may not be supported by other security policies.

-v

When the-v (authentication) option is given, sudo updates the user's cached credentials and authenticates the user's password if necessary. For the sudoers plug-in, this extends the sudo timeout by another 5 minutes (or the timeout set by the security policy), but does not run the command

--

This option indicates that sudo should stop processing command line arguments

Environment variables set for commands can also be passed to the command line in the form of var=value, such as LD_Library_path=/usr/local/pkg/lib. Variables passed to the command line are subject to the same restrictions as normal environment variables, with one important exception. If you set the setenv option in sudoers, the command to run has a SETENV tag set or a matching command.

3. Execute orders

When sudo executes a command, the security policy specifies the environment in which the command is executed. Typically, the actual valid uid and gid are set to match the target users specified in the password database, and the group vector is initialized based on the group database (unless the-p option is specified). The security policy may specify some parameters: real valid user ID, real valid group ID, supplementary group ID, environment list, current working directory, file creation mask, role and type of SELinux, scheduling level.

1) process model

When sudo runs a command, it calls fork (2), sets the execution environment described above, and invokes the execve system call in the child process. The main sudo process waits for the command to complete, and then passes the exit status of the command to the security policy's close method and exits. If the pty O log plug-in is configured, a new pseudo terminal ("pty") will be created, and a second sudo process will be used to pass job control signals between the user's existing pty and the new pty that is running. This extra process makes it possible to suspend and resume commands. Without it, the command uses the "orphaned process group" in POSIX terminology. And will not receive any job control signals.

2) signal processing

Because the command runs as a child of the sudo process, sudo relays the received signal to the command. Unless the command is run in the new pty, SIGHUP, SIGINT, and SIGQUIT signals will not be relayed unless they are sent by the user process rather than the kernel. Otherwise, the command will receive SIGINT. Ctrl+c twice when the user presses "SIGINT". Signal. Because SIGSTOP and SIGKILL cannot be captured, they are not relayed to the command. As a general rule, you should use SIGTSTP instead of SIGSTOP when you want to suspend commands that sudo runs.

As an exception, sudo will not relay the signals sent by the commands it is running. This prevents orders from accidentally killing themselves. On some systems, the reboot (8) command sends SIGTERM to all non-system processes, not to itself, before restarting the system. This prevents the sudo from relaying the received SIGTERM signal back to reboot (8), which may then exit before the system is actually started, leaving it in a semi-dead state similar to single-user mode. Note, however, that this check applies only to commands that sudo runs, not to any other processes that may be created by the command. Therefore, running a script that calls re-reboot (8) or shutdown (8) through sudo may leave the system in this undefined state unless you run reboot (8) or shutdown (8) (which inserts a shell between the command and calling process) using the exec () function series instead of system ().

4. Plug-in

The plug-in loads dynamically based on the contents of the "/ etc/sudo.conf" file. If there is no "/ etc/sudo.conf" file, or if it does not contain plug-in lines, sudo will use the traditional sudoers security policy and Icano logging, which is equivalent to the following "/ etc/sudo.conf" file

#

# Default / etc/sudo.conf file

#

# Format:

# Plugin plugin_name plugin_path plugin_options...

# Path askpass / path/to/askpass

# Path noexec / path/to/sudo_noexec.so

# Debug sudo / var/log/sudo_debug all@warn

# Set disable_coredump true

#

# The plugin_path is relative to / usr/libexec unless

# fully qualified.

# The plugin_name corresponds to a global symbol in the plugin

# that contains the plugin interface structure.

# The plugin_options are optional.

#

Plugin policy_plugin sudoers.so

Plugin io_plugin sudoers.so

The plug-in line consists of plug-in keywords, followed by the symbolic name and the path to the shared object that contains the plug-in. The symbolic name is the name of the struct policy_plugin or struct io_plugin in the plug-in shared object. The path can be fully qualified or relative. If not fully qualified, it is relative to the "/ usr/libexec" directory. Any additional parameters after the path are open functions passed as parameters to the plug-in. Not with Plugin, Path,

Lines starting with Debug and Set are ignored by default.

5. Path

The path line consists of the Path keyword, followed by the name of the path to be set and its value. Example:

Path noexec / usr/libexec/sudo_noexec.so

Path askpass / usr/X11R6/bin/ssh-askpass

The following plug-in independent paths can be set in the "/ etc/sudo.conf" file

1) askpass, the fully qualified path of the helper, used to read the user's password when no terminal is available. This may be the case when sudo is executed from a graphical application. The program specified by askpass should display the parameters passed to it as a prompt and write the user's password to standard output. Askpass may be overridden by the environment variable SUDO_ASKPASS.

2) noexec, the fully qualified path to the shared library, contains virtual versions of execv (), execve (), and fexecve () library functions that only return errors, and are used to implement noexec functions on systems that support LD_PRELOAD or their equivalent. The default is "/ usr/libexec/sudo_noexec.so".

6. Debugging flag

Sudo version 1.8.4 and later supports a flexible debugging framework that, if there is a problem, can help track what sudo is doing internally.

The Debug line consists of the Debug keyword, followed by the name of the program to debug (sudo, visudo, sudoreplay), the debug file name, and a comma-separated list of debug flags. The debug flag syntax used by sudo and sudoers plug-ins is subsystem@priority, but plug-ins are free to use different formats, as long as it does not include commas. For example, the statement "Debug sudo / var/log/sudo_debug all@warn,plugin@info" will record all debug statements and information-level statements for the plug-in subsystem at the warning level and higher.

Currently, only one debug entry is supported per program. Sudo debug entries are shared by the sudo front end, sudodit, and plugins. Future versions may add support for each plug-in debug trial and / or multiple debug files for a single program.

The priority of sudo front end is crit, err, warn, notice, diag, info, trace, debug. When each priority is specified, all priorities higher than this priority are also included. For example, the priority of a notification will include debug messages recorded in the notification and a higher priority.

The sudo front end can use a subsystem at once:

Sub-system

Description

All

All the subsystems.

Args

Command line argument process.

Conv

User returns to session

Edit

Sudoedit .

Exec

Command execution process.

Main

The main function of sudo.

Netif

Network interface processing.

Pcomm

Plug-in session

Plugin

Plug-in configuration.

Pty

For tty related code.

Selinux

SELinux dedicated processing.

Util

Practical function.

Utmp

Utmp processing

7. Exit value

When the program executes successfully, the exit state of the sudo will only be the exit state of the program being executed. Otherwise, if there is a configuration / permission problem or if sudo fails to execute the given command, sudo exits as 1. In the latter case, the error string is printed to standard error. If sudo cannot call the stat function in the user path to count one or more entries, an error is printed on the stderr. (if the directory does not exist, or if it is not actually a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason stat (2) returns "deny permission" is if you are running an automatic listener and a directory in your path is on a computer that is currently inaccessible.

8. Safety instructions

Sudo tries to keep it safe when executing external commands. To prevent command spoofing, sudo finally checks "." when searching for commands in the user's path. And "". Note, however, that the actual path environment variable is not modified, but is passed to the program executed by sudo unchanged.

Note that sudo usually records only the commands it explicitly runs. If the user runs commands such as "sudo su" or "sudo sh", subsequent commands run from that shell are not bound by sudo's security policy, as are commands that provide shell escape. If Iwhite O logging is enabled, subsequent commands will have their input and output records, but these commands will not have traditional logging. Therefore, when a user accesses a command through sudo, care must be taken to verify that the command does not inadvertently give the user a valid root shell.

To prevent potentially sensitive information from being disclosed, sudo disables core dumps by default during execution. To help debug sudo crashes, you may want to re-enable core dumps by setting "disable_coredump" to false in the "/ etc/sudo.conf" file, as shown below

Set disable_coredump false

Note that by default, most operating systems disable core dumps from setuid programs, including sudo. To actually get the sudo core files, you may need to enable core dumps for the setuid process. On BSD and Linux systems, this is done through the "sysctl" command, and the "coreadm" command can be used on Solaris.

9. Environmental variables

Sudo uses the environment variable, and the security policy controls the actual content of the command environment.

Environment variable

Description

EDITOR

If SUDO_EDITOR or VISUAL is not set, the default editor uses the "- e" mode.

MAIL

When env_reset is enabled in "- I" mode or in sudoers, it is set as the mail spool for the target user.

HOME

If "- I" or "- H" is specified, a value is assigned to the target user's home directory in sudoers, or to env_reset or all_set_home. Or when the "- s" option is specified, the value is assigned to set_home in sudoers.

PATH

May be overridden by security policy

SEHLL

Execute the running shell using the "- s" option

SUDO_ASKPASS

If there is no terminal available, or if the-An option is specified, specify the path of the helper program used to read the password.

SUDO_COMMAND

Commands assigned to sudo to run

SUDO_EDITOR

Default editor in "- e" mode

SUDO_GID

Group ID assigned to the user calling sudo

SUDO_PROMPT

As the default password prompt statement

SUDO_PS1

If set, PS1 will be set to the value of the running program.

SUDO_UID

The ID assigned to the user who calls sudo

SUDO_USER

Assign a value to the login name of the user who calls sudo

USER

Assign to the target user (default is root, unless the "- u" option is specified)

VISUAL

If "SUDO_EDITOR" is not specified in "- e" mode, then this is the default editor

10. Examples

1) View the instructions supported by the current user

[weijie@192 /] $sudo-l / / current user does not have the right to execute any sudo instructions

[sudo] password for weijie:

Sorry, user weijie cannot run sudo on 192.

You have new mail in / var/spool/mail/root

[root@192 /] # sudo-l / / the current user is root, so all sudo instructions can be executed

Match the default entry for root on this host:

Requiretty,! visiblepw, always_set_home, env_reset, env_keep= "COLORS

DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS ", env_keep+=" MAIL PS1

PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE ", env_keep+=" LC_COLLATE

LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES ", env_keep+=" LC_MONETARY

LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE ", env_keep+=" LC_TIME LC_ALL

LANGUAGE LINGUAS _ XKB_CHARSET XAUTHORITY "

Secure_path=/sbin\: / bin\: / usr/sbin\: / usr/bin

User root can run the following command on this host:

(ALL) ALL

2) execute the command as the specified user, and root cannot be specified

[root@192 /] # sudo-u weijie ls / home/david/ it obviously has no right to view the home directory of user david as user weijie

Ls: unable to open directory / insufficient home/david/: permissions

[root@192 /] # sudo-u weijie ls / home/weijie/ View user weijie's home directory as user weijie. Of course, this is fine.

1.zip mail

[root@192 /] # sudo ls / home/david/ directly view the user's david home directory. Since you are currently in the root environment, you can

Mail

3) other example codes

$sudo-u yaz ls ~ yaz / / View the home directory of user yaz

$sudo-u www vi ~ www/htdocs/index.html / / Edit the file as user www

$sudo-g adm view / var/log/syslog / / View the log file as a group adm

$sudo-u jim-g audio vi ~ jim/sound.txt / / to run the editor as Jim with a different primary group

$sudo shutdown-r + 15 "quick reboot" / / shutdown

$sudo sh-c "cd / home; du-s * | sort-rn > USAGE" / / to use a list of directories in the / home partition, note that this will run the command in the child shell to make the cd and file redirect work.

At this point, the study of "the usage of sudo grammar in Linux system" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report