Systems and Operations

Create an Administrative User and Understand sudo Permissions

Compiled by the VPSMap Editorial Team · Updated 2026-09-26 · 19-minute read · Plain-Text Version

On newly provisioned Linux cloud servers, the vast majority of images default to root account as the initial login entry point.root has unrestricted highest-level system-call privileges. Any mistyped file overwrite or incorrect rm -rf paths or unusual permission changes (such as chmod -R 777 /), can directly cause irreversible system crashes or data loss. Meanwhile, in an open public IPv4 environment, attacks targeting root SSH brute-force attacks and weak-password scans against this username never stop.

The first step toward sound operations practices is to create a regular administrative account with clear ownership, using sudo elevate privileges as needed to run privileged commands, then block, after validation is complete, root direct remote access channel.


1. Why Administrators Must Separate root Access from Everyday Operations#

将日常 Details 与特权执行分离开来,核心价值体现在三个工程维度:

  1. Create an Operational Safety Margin: When regular users make system-level changes, they must explicitly prefix the command with sudo. This creates a mental pause and an opportunity to review the command, preventing mistyped wildcards from damaging system files during routine directory changes, application configuration edits, or cache cleanup.
  2. Command Auditing and Traceability: System logs (such as /var/log/auth.log or /var/log/secureaccurately records every sudo the execution time of each invocation, the initiating user, the working directory, and the full command. When multiple engineers maintain a system together or unexpected changes occur, tracing the root cause is far easier than if everyone directly shares root the terminal is clearer.
  3. Reduce the Exposed Attack Surface: Disable root remote login, external scanners can no longer guess credentials using a fixed username. Attackers must identify both the specific administrator username and a strong key or password, greatly increasing the difficulty of intrusion.

Provider Default Environment Differences and Out-of-Band Recovery Channels#

Before changing any account or authentication settings, understand the server's current initial state and available emergency access methods:

  • DMIT instance : DMIT system images use SSH key authentication by default during initialization, and their default security policy generally直接禁用远程 root 密码登录. To reset the password or update the public key, use the “Access” tab in the DMIT control panel. Note: under DMIT Docs rules, after changing an SSH key or password through the panel, you must reboot the instance there as instructed for the change to be written and take effect. DMIT also provides a web-based “Console,” a critical recovery entry point when configuration errors occur.
  • BandwagonHost( BandwagonHost ) instance : BandwagonHost's authentication system is clearly separated into the client area billing password, KiwiVM management panel password, and operating system's root 密码彼此独立。KiwiVM 面板内置了「Interactive Console」(交互式终端)和「VNC」,即使在 SSH 配置写错、防火墙规则阻断或 Networking 服务故障时,也能脱离 public network SSH 链路直接登录底层 Shell。

Core Principle: when creating an administrative user, configuring public keys, and adjusting sudoers throughout the entire process,Do Not Close the Original root SSH Connection. Perform all validation from a new local terminal window on your computer. If authentication fails there, the original root session remains available to correct the problem immediately.


2. Prerequisites: Check for and Install sudo#

Minimal Images of different distributions trim the basic toolset to varying degrees. For example, a minimal Debian system deployed on BandwagonHost or DMIT may not have the following installed by default: sudo tool; Ubuntu includes it by default.

在当前的 root 会话中,首先检测系统是否存在 sudo:

bash
which sudo

如果 Not returned 二进制路径(例如 /usr/bin/sudo),需立即 Passed 系统官方源进行补齐:

Debian / Ubuntu 系:

bash
apt update && apt install -y sudo

Rocky Linux / AlmaLinux / CentOS / Fedora family:

bash
dnf install -y sudo

安装完成后,可 Passed 查看 Version 确认组件完整性:

bash
sudo -V | head -n 1

3. Create an Administrative User and Configure the Admin Group#

The group name used to grant administrative privileges differs between distributions:

  • Debian / Ubuntu: The default privilege-elevation group is sudo group.
  • Rocky Linux / AlmaLinux / RHEL: The default privilege-elevation group is wheel group.

to create one named deploy as the example administration account (replace it with an identifiable username that follows your team's conventions):

3.1 创建用户#

On Debian and Ubuntu, the recommended high-level interactive tool is adduser, it automatically creates the home directory and copies the skeleton configuration (/etc/skel) and interactively prompts you to set the user's password:

bash
adduser deploy

On Rocky Linux, AlmaLinux, or a minimal Debian installation, if only the low-level useradd command, specify parameters to create the home directory and login Shell:

bash
useradd -m -s /bin/bash deploy
passwd deploy

Pay Special Attention to What the sudo Password Actually Is: When the user runs sudo <command> the system prompts by default for a password that is not the root password, butThe Regular User's Own Login Password. Even if passwordless SSH-key login is configured on a DMIT or BandwagonHost server, Linux's local PAM authentication module still relies on the user's password to validate sudo access. Therefore, you must use passwd Set a strong, unique password for this account.

3.2 Add the User to the Privileged Administration Group#

add the user to the system's predefined administrative group. Be sure to use -aG(Append to Groups) parameter; if you omit -a 仅输入 -G, the system will remove the user from all other existing supplementary groups, causing a permissions incident:

Debian / Ubuntu family (add to the sudo group):

bash
usermod -aG sudo deploy

Rocky Linux / AlmaLinux Systems (Add to the wheel Group):

bash
usermod -aG wheel deploy

检查该用户的 UID、GID 及所属组信息:

bash
id deploy

Normal output should look like this:

text
uid=1001(deploy) gid=1001(deploy) groups=1001(deploy),27(sudo)

4. 为新用户 deployment SSH 密钥认证#

Production environments should not expose password-based authentication on SSH ports. Since environments such as DMIT commonly use public-key authentication, install your local computer's SSH public key in the new user's home directory.

4.1 Standard Initialization .ssh Directory Structure#

The SSH server checks permissions on related files and directories very strictly. If permissions are too broad,sshd 的 StrictModes 机制会自动拒绝连接。

In the root terminal where you are already logged in, securely create the new user's key directory and credential storage file:

bash
mkdir -p /home/deploy/.ssh
touch /home/deploy/.ssh/authorized_keys

Take the public key generated on your local development machine (usually ~/.ssh/id_ed25519.pub or ~/.ssh/id_rsa.pub 的单行文本)写入该文件。可以 Passed 文本编辑器打开写入:

bash
nano /home/deploy/.ssh/authorized_keys

4.2 Correct Ownership and File Permission Modes#

因为该文件是由 root 代为建立的,其初始拥有者为 root:root,普 General Purpose 户无权读取或追加,会导致该用户登录时直接被服务端拒绝。必须立即修正所有权和最小权限位:

bash
# 变更属主归还给新用户
chown -R deploy:deploy /home/deploy/.ssh

# 目录必须且只能由所有者读写执行(700)
chmod 700 /home/deploy/.ssh

# 密钥文件必须且只能由所有者读写(600)
chmod 600 /home/deploy/.ssh/authorized_keys

4.3 Verify Login in Both Directions and Privilege Elevation#

On your local computer, open a全新的终端(remember to keep the original root connection open), then connect as the newly created user:

bash
ssh -p 22 deploy@你的服务器IP

After connecting, run these verification commands step by step:

bash
# 验证当前身份
whoami
# 输出应为:deploy

# 验证管理凭据缓存与提权状态(此时需输入 deploy 自身的密码)
sudo -v

# 验证能否成功获取 root 权限
sudo whoami
# 输出必须严格为:root

If sudo whoami outputs root, confirming that the administrative user has been created and system-group permissions are fully in place.


5. 深度掌握 sudo 规则与 visudo 定制#

管理组赋予的权限是全量系统管理(等同于 root)。但在复杂架构中,我们常常需要配置细粒度授权(如允许 CI/CD 账户免密重启 Nginx、允许开发人员读取系统日志等)。

All sudo Rules Are Centralized In /etc/sudoers and /etc/sudoers.d/ directory.

5.1 Never Edit sudoers Directly with an Ordinary Text Editor#

/etc/sudoers files have a special syntax structure. If someone uses vim、nano or similar tools and accidentally add a typo or semicolon, after saving and exiting the entire system's sudo will fail immediately, leaving all non-root users unable to elevate privileges again.

Use the Dedicated Validation Tool When Editing Rules:

bash
sudo visudo

visudo On saving, it performs an atomic syntax check of the modified content. If there is a syntax error, it blocks the exit process and identifies the exact line so the administrator can fix it. The changes are written to disk only when the syntax is fully valid.

To validate the syntax of the current rules after deploying a script without entering interactive mode, run:

bash
sudo visudo -c

5.2 Recommended Modular Configuration:/etc/sudoers.d/#

Do Not Put All Custom Rules into the Main File /etc/sudoers 内。最佳实践是在 /etc/sudoers.d/ create separate files in the directory for specific services or accounts.

Requirements:

  1. File permissions within the directory must be 0440(r--r-----)。
  2. Filenamecannot use . at the beginning, and must not contain ~ or ., otherwise sudo will ignore this configuration file outright, as required by the system's default ignore rules.

For example, configure a rule allowing an automated deployment account to restart a specific service without a password:

bash
sudo visudo -f /etc/sudoers.d/90-deploy-services

In the editor that opens, follow the standard syntax:

text
# 语法构成:
# 谁(用户或组) 主机=(运行身份:运行组) [选项] 允许执行的程序路径

# 示例 1:允许 deploy 用户免密管理网络与系统服务(适合特定编排运维)
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx

# 示例 2:全量免密提权(常用于自动化流水线,但对个人账户应极其审慎)
# deploy ALL=(ALL) NOPASSWD: ALL

5.3 Check Effective Permissions#

Under any user account, you can check your permissions instead of guessing by running:

bash
sudo -l

系统会逐条列出当前用户所匹配到的环境限制(Matching Defaults entries)以及被明确授权运行的具体命令列表。

5.4 Beware of Seemingly Safe Privilege-Escalation Traps#

For convenience, many administrators will, in sudoers to allow seemingly harmless commands, but without security precautions, ordinary users may bypass restrictions and obtain full root access:

  1. Editor Pitfalls: grants the user sudo /usr/bin/vim /etc/nginx/nginx.conf privileges, the user only needs to enter the following in vim: :!/bin/bash or :sh, immediately opening a root Shell without a password. To grant editing permissions, use sudoedit。
  2. 通配符与目录写权限陷阱: If you authorize sudo /opt/scripts/*.sh, while /opt/scripts the directory or scripts inside it are owned by deploy themselves, that user can modify the script to add arbitrary malicious commands and then use sudo 执行,实际上完全等同于拥有无限制的 root 权限。
  3. High-Risk Privilege Escalation Through Binaries: such as find、awk、less and other system tools with native Shell execution capabilities must never be casually added to a passwordless privilege-escalation list.

6. Reduce the Attack Surface: Safely Disable Remote SSH Access for root#

Once the new administrative user is confirmed to reliably execute ssh and sudo afterward, completely disable public-network access for the following in the SSH daemon: root 的访问。

6.1 Modify the SSH Server Configuration#

Edit the main configuration file (or /etc/ssh/sshd_config.d/ the supplementary configurations under it):

bash
sudo nano /etc/ssh/sshd_config

定位并确保以下关键指令生效(取消前面的 # comment):

text
# 彻底禁止 root 用户通过 SSH 协议登录
PermitRootLogin no

# 强制仅允许密钥登录,全面关闭密码认证(视团队情况,建议开启以消除暴力破解)
PasswordAuthentication no

6.2 语法校验与平滑重载#

在重启服务前,先对 SSH 服务配置进行语法检测:

bash
sudo sshd -t

如果未输出任何报错信息,代表配置安全。此时平滑重载 SSH 进程:

bash
sudo systemctl reload sshd

Note:systemctl reload 只会应用新配置,绝不会中断当前已经连入的活跃 SSH 会话。

6.3 救援预案与失联排障#

If a configuration mistake, such as pasting the wrong public key, reversing permissions, or accidentally disabling all authentication methods, locks you out of a newly opened terminal, do not panic. Recover using the underlying mechanisms of the two providers described earlier:

  • BandwagonHost 用户: Open the KiwiVM control panel and select “Interactive Console” or “Root shell - basic” in the left navigation. This out-of-band terminal connects directly at the virtualization layer and is unaffected by SSH service status. Use the initial system root password to enter the terminal and modify /etc/ssh/sshd_config will PermitRootLogin temporarily change it back to yes and restart sshd。
  • DMIT Users: open the instance list in the client area, find the affected VM, and click “Console” to enter the web rescue page. Enter the root credentials to access the underlying system. If password login is disabled and prevents access, first reset the credentials through “Access” in the DMIT panel, reboot through the panel as required, then log into the console to make repairs.

7. 账户生命周期的回收与注销#

运维人员变动或项目交接完成后,回收权限必须做到彻底与可控。需要明确:Revoking sudo Privileges, Terminating Active Sessions, and Deleting an Account Are Three Completely Separate Stages。

7.1 Revoke a User's Administrative Privileges (Demotion)#

Simply remove the user from the privileged group; their regular-user functions and data remain completely unaffected:

Debian / Ubuntu 系:

bash
sudo deluser deploy sudo

Rocky Linux / AlmaLinux family:

bash
sudo gpasswd -d deploy wheel

If this user, in /etc/sudoers.d/ contains a dedicated configuration file, remember to delete it as well:

bash
sudo rm -f /etc/sudoers.d/90-deploy-*

7.2 Revoke SSH Credentials and Lock the Account#

If an employee leaves or loses a device, first prevent further network authentication and immediately terminate existing connections:

bash
# 清空用户的授权公钥
sudo truncate -s 0 /home/deploy/.ssh/authorized_keys

# 锁定用户密码(阻止一切密码验证形式)
sudo usermod -L deploy

# 强制杀死属于该用户的所有存活进程与 SSH 建立的会话连接
sudo pkill -u deploy

7.3 Carefully and Completely Delete an Account#

Before final deletion, confirm that the user no longer owns any running systemd daemons, Nginx static resources, or critical database backups:

bash
# 检查该用户是否有名下的定时任务
sudo crontab -u deploy -l

# 删除账户,并连带清理其家目录(-r / --remove-home)
sudo userdel -r deploy

Warning:如果该账户的家目录存放了网站运行目录或代码仓库,切勿使用 -r parameter; first transfer ownership of important business files using chown -R transfer ownership to the new runtime user, such as www-data or another administrator), then remove obsolete account metadata after confirming everything is correct.