Unit 4: Command Productivity, Scheduling, Performance, and ACLs

CSE493 — Linux System Administration 11 min read

I. Orientation: Linux Administration as Controlled Automation

Linux system administration combines efficient command use, repeatable automation, timed execution, resource management, and precise access control. The governing principle is to make system behavior predictable: commands should be reproducible, jobs should run under known conditions, performance changes should be measurable, and file access should follow least privilege.

  • Command interpretation: The shell reads a command line, expands variables and patterns, performs redirection, and starts a program.
  • Automation: A Bash script stores commands in an executable sequence, while loops repeat operations over files, users, or command output.
  • Scheduling: at runs a user job once in the future; cron runs recurring jobs according to a time specification.
  • Performance control: Tuning changes should be selected from measurable symptoms such as CPU saturation, memory pressure, or excessive I/O wait.
  • Permissions: Traditional permissions divide access among owner, group, and others; ACLs add named users and groups.
  • Least privilege: Users and processes receive only the access and resources required for their tasks.
  • Administrative context: Commands such as systemctl, tuned-adm, setfacl, and getfacl commonly require appropriate privileges.

II. Command-Line Productivity and Shell Automation

The command line is most productive when commands are composable, output is redirected deliberately, and repeated work is expressed as a script or loop.

A. Improving Command-line Productivity

This topic concerns reducing repetitive typing while preserving clear, inspectable command behavior.

  • History: Use history to inspect previous commands and !number to rerun a history entry; Ctrl+r searches interactively through command history.
  • Completion: Press Tab to complete commands, paths, usernames, and options. Completion reduces spelling errors and exposes available files.
  • Aliases: Define short command names, such as:
    BASH
      alias ll='ls -l'

    An alias affects interactive shell use and is not automatically available to scripts.
  • Pipelines: The pipe sends standard output to another command:
    BASH
      ps aux | grep sshd

    Here, ps aux produces process data and grep filters matching lines.
  • Redirection: > replaces a file, >> appends, and 2> redirects standard error:
    BASH
      command >output.txt 2>errors.txt
  • Command substitution: $(command) inserts command output into another command, as in echo "Kernel: $(uname -r)".
  • Safe inspection: Use man command, command --help, and type command to distinguish a binary, alias, function, or shell builtin.

B. Writing Simple Bash Scripts

A Bash script is a text file interpreted by Bash and used to make a sequence of administrative actions repeatable.

  • Interpreter declaration: Begin with:
    BASH
      #!/usr/bin/env bash

    This selects Bash through the environment path.
  • Variables: Assign without spaces and expand with $:
    BASH
      user_name="sam"
      echo "Account: $user_name"
  • Arguments: $1 is the first argument, $# is the argument count, and "$@" represents all arguments separately.
  • Conditions: Use if with a test such as [[ -f "$file" ]], where -f checks for a regular file.
  • Exit status: A successful command normally returns 0; failure returns a nonzero status. exit 1 explicitly signals failure.
  • Execution safety: Quote variables such as "$file" to preserve spaces and special characters. Make a script executable with chmod +x script.sh.
  • Defensive settings: set -euo pipefail makes many errors visible by stopping on failures, rejecting unset variables, and detecting pipeline failures; it should be used with awareness of commands that intentionally return nonzero statuses.

C. Running Commands More Efficiently Using Loops

Loops apply one operation to multiple values and eliminate manual repetition.

  • File iteration: A for loop can process matching files:
    BASH
      for file in /var/log/*.log; do
          printf '%s\n' "$file"
      done

    The variable file receives each pathname produced by the glob.
  • While loops: A while loop is suitable for reading input line by line:
    BASH
      while IFS= read -r line; do
          printf '%s\n' "$line"
      done < hosts.txt
  • Controlled repetition: break exits a loop, while continue skips to its next iteration.
  • Robust filenames: For arbitrary filenames, prefer null-delimited pipelines such as find ... -print0 with read -d ''; ordinary whitespace splitting can corrupt names containing spaces.
  • Efficiency: One loop can perform a consistent operation across hundreds of files, but commands should be quoted and tested on a small sample before broad execution.

D. Matching Text in Command Output with Regular Expressions

Regular expressions describe text patterns, allowing administrators to select, validate, or transform command output.

  • Basic matching: grep 'error' app.log selects lines containing error; grep -i ignores case.
  • Anchors: ^root matches lines beginning with root, while bash$ matches lines ending with bash.
  • Character and repetition patterns: [0-9] matches one digit, . matches one character, and * repeats the preceding expression zero or more times.
  • Extended expressions: grep -E 'sshd|httpd' services.txt matches either service name. + means one or more occurrences in extended regular expressions.
  • Structured output: awk is useful when fields matter, for example awk '$3 > 80 {print $1}', which prints field 1 when field 3 exceeds 80.
  • Limitations: Regular expressions match text, not semantic meaning; anchoring and field boundaries are necessary to avoid accidental matches.

III. Scheduling and Temporary Work

Linux scheduling separates one-time jobs from recurring jobs and provides controlled mechanisms for short-lived files.

A. Scheduling Future Tasks

Scheduling future tasks requires a command, execution time, environment, and account context.

  • One-time versus recurring: Use at for one execution and cron for repeated execution. A job scheduled with at does not repeat automatically.
  • Time expressions: at 23:00 schedules a job for a specified time; at now + 10 minutes expresses a relative delay.
  • Environment: Scheduled jobs may have a smaller PATH, no interactive terminal, and a different working directory. Use absolute command paths where practical.
  • Verification: atq lists pending at jobs, while atrm JOB_ID removes a queued job.
  • Permissions: /etc/at.allow and /etc/at.deny can restrict which users may submit at jobs.

B. Scheduling a Deferred User Job

A deferred user job is a single command or script submitted to at and executed later by the scheduling service.

  • Submission: Pipe a command into at:
    BASH
      echo "/home/sam/bin/backup.sh" | at 02:00

    The command is submitted immediately but runs at 02:00.
  • Interactive submission: Running at 02:00 opens an input prompt; enter commands and finish with Ctrl+d.
  • Output handling: Redirect output explicitly, for example:
    BASH
      echo "/usr/bin/df -h > /home/sam/disk-report.txt" | at now + 1 hour
  • Job identity: The returned job number identifies the task for atq and atrm.
  • Operational limitation: The job runs with the submitting user’s privileges, so it cannot modify protected system files without suitable authorization.

C. Scheduling Recurring System Jobs

Recurring jobs are defined in crontabs using five time fields followed by a command.

  • Field order: The fields are minute, hour, day of month, month, and day of week:
    TEXT
      0 2 * * * /usr/local/sbin/backup.sh

    This runs daily at 02:00.
  • Special values: * means every permitted value; */15 means every 15 units, such as every 15 minutes.
  • User crontab: crontab -e edits the current user’s jobs; crontab -l lists them.
  • System cron: /etc/crontab and files under /etc/cron.d/ include an additional username field:
    TEXT
      0 2 * * * root /usr/local/sbin/backup.sh
  • Reliability: Use absolute paths, redirect output, and avoid assumptions about interactive shell variables. The cron or crond service must be running.

D. Managing Temporary Files

Temporary files should be created safely, cleaned predictably, and protected from name collisions or unauthorized reading.

  • Secure creation: mktemp creates a unique temporary file or directory:
    BASH
      tmpdir=$(mktemp -d)
      trap 'rm -rf "$tmpdir"' EXIT
  • Cleanup: trap runs cleanup when the script exits; EXIT covers normal completion and many error paths.
  • Temporary directories: /tmp is generally writable by users and commonly uses the sticky bit, so users cannot remove other users’ files there.
  • System cleanup: systemd-tmpfiles applies policies from configuration files, including cleanup ages and permissions.
  • Security risk: Never construct predictable names such as /tmp/report.txt; an attacker may create a symbolic link before the administrator writes to it.

IV. Performance and Process Control

Performance administration measures resource behavior, applies an appropriate profile, and controls process priority according to operational need.

A. Tuning System Performance

System tuning changes kernel and service behavior to improve throughput, latency, power use, or responsiveness.

  • CPU measurement: top and uptime show load and process activity; a high load average indicates runnable or uninterruptible tasks, not CPU percentage alone.
  • Memory measurement: free -h reports memory in human-readable units. Swap use and sustained reclaim can indicate memory pressure.
  • I/O measurement: iostat identifies device utilization and wait behavior; high %util or latency can point to storage saturation.
  • Network measurement: ss -tulpn displays listening sockets and owning processes, while sar -n DEV can show interface activity.
  • Change discipline: Measure a baseline, change one relevant setting, and measure again. A performance improvement must be evaluated against latency, reliability, and resource cost.

B. Adjusting Tuning Profiles

Tuning profiles provide coordinated settings for common workloads instead of requiring every parameter to be changed separately.

  • Profile manager: On systems using tuned, tuned-adm active displays the current profile and tuned-adm list lists available profiles.
  • Selection: Apply a profile with:
    BASH
      sudo tuned-adm profile throughput-performance

    The profile name should match the workload and hardware.
  • Common goals: throughput-performance favors bulk processing; latency-performance reduces latency at possible power cost; powersave prioritizes energy reduction.
  • Verification: Use tuned-adm verify to check whether the running system matches the selected profile.
  • Tradeoff: A profile is a coordinated policy, not a universal optimization; throughput, latency, energy use, and thermal behavior can conflict.

C. Influencing Process Scheduling

Process scheduling controls relative CPU preference and, for eligible tasks, scheduling class.

  • Nice value: Normal processes commonly use a nice value from -20 to 19; larger values mean lower CPU priority. Display values with ps -eo pid,ni,comm.
  • Starting priority: nice -n 10 command launches a command with a lower priority than default.
  • Changing priority: renice 10 -p PID changes an existing process. Increasing priority toward negative nice values normally requires root privileges.
  • Scheduling classes: chrt can inspect or set real-time policies such as SCHED_FIFO; real-time use can starve ordinary processes and requires strict control.
  • Correct interpretation: Nice values influence CPU competition; they do not reserve CPU time and do not improve I/O, memory, or application algorithm performance.

V. Access Control Lists

ACLs extend the traditional owner-group-other permission model when a file needs access rules for specific users or groups.

A. Controlling Access to Files with ACLs

This mechanism grants or removes permissions for named users and groups while retaining the traditional mode bits.

  • Granting a user: setfacl -m u:alex:rw file.txt grants user alex read and write access.
  • Granting a group: setfacl -m g:auditors:rX report/ grants the group read access and directory traversal where applicable.
  • Removing an entry: setfacl -x u:alex file.txt removes the named-user ACL entry.
  • Recursive changes: setfacl -R -m g:project:rX project/ applies rules recursively; review the result because files and directories may require different permissions.
  • ACL support: The filesystem must support POSIX ACLs, and mount or filesystem configuration can affect availability.

B. Interpreting File ACLs

ACL interpretation requires reading both named entries and the effective permission mask.

  • Display: getfacl file.txt may show:
    TEXT
      user::rw-
      user:alex:r--
      group::r--
      mask::r--
      other::---
  • Owner and other: user::rw- is the owning user’s permission; other::--- applies to everyone not matched by owner, named entries, or group rules.
  • Named entries: user:alex:r-- grants alex read access independently of the owning user.
  • Mask: mask::r-- limits effective permissions for named users, named groups, and the owning group. A nominal rw- entry is effectively r-- when the mask is read-only.
  • Mode display: ls -l shows a + after permissions when extended ACL entries exist, such as -rw-r-----+.

C. Securing Files with ACLs

ACL security depends on precise entries, restrictive defaults, and regular review.

  • Least privilege: Grant only required permissions, for example setfacl -m u:auditor:r-- confidential.log; avoid broad rwx grants.
  • Directory traversal: A user needs execute (x) permission on each directory in a path to reach a file, even when the file itself is readable.
  • Default ACLs: setfacl -m d:g:developers:rX shared/ establishes inherited permissions for newly created content under shared/.
  • Removing excess access: setfacl -b file.txt removes all extended ACL entries, returning the file to basic permissions; use only when that reset is intended.
  • Auditing: Use getfacl -R, inspect sensitive directories, and compare ACLs with the intended access policy.
  • Limitations: ACLs do not bypass mandatory access controls such as SELinux, file ownership restrictions, encryption, or application-level authorization.