Top.Mail.Ru

How to Monitor User Activity on Linux Using psacct and acct

How to Monitor User Activity on Linux Using psacct and acct

When you’re administering a Linux server, especially one with many users, it’s important to understand what’s going on. Who is currently logged in? What commands does it execute? How much CPU time does it waste? And it’s not just a matter of curiosity. Such information is the basis for security, debugging, and proper resource management.

For such tasks, Linux has two classic utilities — psacct and acct. Both of them are open, running in the background and accurately recording what users do and what resources they use.

Many administrators use these tools where developers constantly work directly on the servers. This is a simple and reliable way to keep your finger on the pulse.

What exactly do psacct and acct do?

The psacct or acct package includes several utilities for monitoring processes and user activity:

  • ac — displays connection time statistics (logins/logouts) in hours.
  • lastcomm — shows information about previously executed commands.
  • accton — enables or disables process accounting.
  • sa — gives a summary of previously executed commands.
  • last and lastb — show a list of recently logged in users (and failed login attempts for lastb).

Next, we’ll look at how to install all this and use it in practice.

Installing psacct and acct on different distributions

Essentially psacct and acct do the same thing, but they are installed differently depending on the distribution family.

  • rpm distributions (RHEL, CentOS, Fedora) use the psacct package.
  • On Debian-like systems (Ubuntu, Linux Mint) — the acct package.

RHEL, CentOS, Fedora

Installing psacct:

sudo yum install psacct

# or on newer systems

sudo dnf install psacct

Ubuntu, Debian, Linux Mint

Installation acct:

sudo apt install acct

Other distributions

Examples for popular systems:

sudo apk add psacct          # Alpine Linux

sudo pacman -S acct          # Arch Linux

sudo zypper install acct     # OpenSUSE

Starting the psacct/acct service

By default on RHEL-like systems the service psacct is disabled, it must be started manually.

Let’s check the status:

sudo systemctl status psacct

Most likely, you will see that the service disabled. Then run it and add it to startup:

sudo systemctl start psacct

sudo systemctl enable psacct

sudo systemctl status psacct

After this, an accounting file will be created:

/var/account/pacct

IN Debian-like In distributions, the service usually starts automatically after installing the package, and nothing additional needs to be done.

ac: general connection time statistics

The ac command works with the current wtmp connection log file and shows how many hours users have been logged into the system.

The simplest call without arguments:

ac

Example output:

total     11299.15

This is the total number of hours that all users together spent in the system. This figure is useful for load analysis, resource planning and understanding the overall level of activity.

Statistics by day

If you add the -d switch, ac will show statistics by day:

ac -d

You will see a list of dates and the number of hours for each day. If, for example, on October 31 or November 3 there are unusual peaks of activity, this is a reason to look at what was happening these days: updates, tests, attack, backups, etc.

Uptime per user

To see how many hours you spent in the system every user, use:

ac -p

Working time of a specific user

You can view the total operating time of an individual user like this:

ac user

Example:

total      110.31

And to see the statistics by day only for this user:

ac -d user

If you are interested in a specific period, for example the last month, you can simply limit the output:

ac -d user | tail -n 31

This makes it convenient to track the activity of a specific developer or administrator.

sa: summary of executed commands

The sa command displays a summary of all previously executed commands:

sa

In the output, each line corresponds to a specific command and contains several indicators.

Decryption example:

  • 0.04re — real time execution in minutes according to the system clock (wall clock).
  • 0.04cp — total CPU time (user + system) in minutes.
  • 6546k — average memory usage during the command’s operation, in arbitrary units (1k).
  • fail2ban-client — command name.
  • An asterisk * after some command names means that they were executed with superuser rights.

This summary helps you quickly understand which commands are launched most often and which of them consume a significant share of resources.

sa -u: user statistics

If you add the -u switch, sa will show commands broken down by user:

sa -u

This is how you can see:

  • what commands a particular user ran;
  • how many resources each team “ate” from him;
  • than in general it loaded the system.

This is a convenient tool for productivity analysis, investigations and finding “heavy” tasks.

sa -m: number of processes and CPU time

The -m switch displays the total number of processes and CPU minutes:

sa -m

If these values ​​are constantly increasing day by day, it is worth checking to see if:

  • too resource-intensive tasks;
  • incorrectly configured services;
  • “leaks” in the form of looping processes.

sa -c: sort by resource consumption

With the -c switch, the sa command sorts the data by resource usage percentage:

sa -c

As a result, you get a list of commands, ordered by their “gluttony”. This is a quick way to see what exactly is loading the CPU and memory: some assembly, a database, a backup, or a randomly running process.

lastcomm: view executed commands

lastcomm command shows history executed commands taking into account the information collected by psacct/acct.

For example, to see what the user was running:

lastcomm user

You will receive a list of commands, their parameters, launch time and other service information.

The output contains the F flag — it means that the command did a fork, but did not execute an exec, that is, the process was spawned, but the actual command was not replaced by another executable (typical of shell initialization).

It is possible to limit the output to only the last lines. For example, show the user’s last 20 commands:

lastcomm user | head -n 20

Search by command logs

lastcomm allows you to search who ran certain commands and when. For example, to see who used ls:

lastcomm ls

And if you need to check, who accessed sensitive files, you can filter the results via grep:

lastcomm cat | grep -i "shadow|passwd"

This will show you which users have read shadow or passwd files — useful for audits and incident investigations.

last and lastb: who logged in

It is also worth remembering the commands:

  • last — shows a list of the last successful logins;
  • lastb — list of failed attempts (usually read by btmp).

Together with psacct/acct, this gives a fairly complete picture: who entered when and what they did after entering.

Practical use cases

In practice, these tools are especially useful in several common situations.

  1. Search for power hungry tasks. If the server starts running slower than usual, look at the output of sa -c: you will immediately see the commands that took the most CPU time.
  2. Security and audit. After a suspicious event, you can use lastcomm to see which commands were launched shortly before. Unlike regular shell command history, this data is more difficult to clean up.
  3. Accounting and billing. In environments where multiple clients share a single server (such as hosting), ac -p provides specific numbers for each user’s activity — this can be used for reporting and calculations.
  4. Analysis of incidents with users. When someone says, “I didn’t do anything,” you always have the opportunity to carefully check which commands were actually run on their behalf — and discuss the situation based on the facts.

Managing logs and their size

psacct/acct has one natural side effect: magazines grow over time. The main process accounting file is:

/var/account/pacct

To prevent it from growing uncontrollably, it makes sense to connect it to logrotate. Example configuration in the /etc/logrotate.d/psacct file:

/var/account/pacct {

    monthly

    rotate 12

    compress

    notifempty

    create 0600 root root}

What does this mean:

  • monthly — rotation once a month;
  • rotate 12 — store up to 12 archives (year of history);
  • compress — compress old files;
  • notifempty — do not touch the file if it is empty;
  • create 0600 root root — create a new file with the required rights and owner.

This way you preserve history, but at the same time keep the size of the logs under control.

Documentation and additional features

The psacct/acct utilities support many options and flags that were not discussed here. To choose the configuration for your needs, be sure to look at the manuals:

man ac

man sa

man lastcomm

man accton

They detail additional keys, output formats, and integration options with your monitoring system. By spending a little time studying the documentation, you can set up activity tracking so that it neatly complements your existing server monitoring tools.

CONTENT:

Similar

All news

Похожее

Все новости

Adaxa Suite: подробный обзор ERP-системы корпоративного класса

Adaxa Suite — комплексная ERP-платформа для компаний, которым уже тесно в рамках простых учётных систем, но которые при этом не готовы идти в сторону дорогих корпоративных решений уровня SAP или Oracle. Изначально продукт создавался для среднего бизнеса, которому нужна большой набор функций, сквозная автоматизация процессов и надёжная архитектура без чрезмерной стоимости владения. Архитектура и техническая […]

Как заказать дополнительные IP-адреса на UFO.Hosting: пошаговая инструкция

По мере роста проекта одного IP-адреса может стать недостаточно. Это типичная ситуация для компаний, которые масштабируют инфраструктуру, запускают новые сервисы или разделяют внутренние процессы. В UFO.Hosting подключение дополнительных IP-адресов выполняется через биллинговую панель и занимает всего несколько минут. Важно: возможность для заказа дополнительных IP-адресов доступна для тарифов VPS начиная с Haedus. Зачем нужны дополнительные IP-адреса […]