# TrafficCop watches your VPS traffic and throttles the box before the bill arrives

> TrafficCop is a shell script suite that samples vnstat counters once a minute, applies per-port and machine level limits, and can cut the network or shut the machine down when a traffic quota is reached, with a correction for the 7 percent gap between binary and decimal gigabytes.

**ypq123456789/TrafficCop** — 监控VPS流量使用，到达限制自动限流/关机，保留SSH端口可用

- Repository: https://github.com/ypq123456789/TrafficCop
- Stars: 540 · Forks: 75
- Language: Shell
- License: not declared
- Published: 2026-10-22 · Updated: 2026-10-22 · Language: en
- Canonical page: https://hysenlabs.com/projects/ypq123456789-trafficcop

## It counts vnstat bytes and acts on the quota

TrafficCop is a shell script set for watching traffic usage on a VPS and reacting when a limit is reached, with two reaction modes: throttling the interface, and shutting the machine down. A third mode in the feature set is shutting down in a way that leaves the SSH port usable, which is the point of the whole design. A box that cuts its own network the moment the quota is hit is a box you cannot log into to fix, so keeping the management path alive matters more than the neatness of the cutoff.

The counters come from vnstat, and that dependency carries the first trap. vnstat only starts recording traffic after it is installed, so on a fresh machine the script has nothing to measure until the counters have accumulated. The script itself runs from cron once a minute, which is the cadence of the log writes and of the limit checks.

The scripts live in /root/TrafficCop, the log file is traffic_monitor.log in that directory, and the configuration is the plain text file traffic_monitor_config.txt. The default behaviour is to run as root, and the README notes that a non-root user needs sudo and every command prefixed accordingly.

## The 7 percent gap is a gigabyte definition problem

The most useful thing in the README is a table about the conversion base, because it explains why the number on your dashboard and the number on your invoice disagree. The script converts the byte counts vnstat reports into gigabytes, and the two conventions differ: 1024 means a gigabyte is 1,073,741,824 bytes, which is the standard most providers, control panels and vnstat itself use, and 1000 means a gigabyte is 1,000,000,000 bytes, which a minority of providers use.

The two differ by 7.4 percent, and the README gives a way to decide which one you have that is not guessing: note the figure the script shows, open the provider console or invoice for the same period, and if the script number is consistently about 7 percent lower, the provider counts in decimal and the setting should be 1000. If the two agree, leave 1024 alone. The README warns explicitly against guessing from a provider's name, since product lines within one company can bill differently.

The setting is called CONVERSION_BASE, and the recommended way to change it is a direct edit of the config file, which takes effect without re-running anything.

## Changing the conversion base without a fragile sed

The obvious one-liner of substituting a value in the config file does not work on every machine, because older configuration files do not contain the field at all. The README's snippet therefore checks first and appends when the key is missing:

```bash
config=/root/TrafficCop/traffic_monitor_config.txt
if grep -q '^CONVERSION_BASE=' "$config"; then
  sed -i 's/^CONVERSION_BASE=.*/CONVERSION_BASE=1000/' "$config"
else
  printf 'CONVERSION_BASE=1000\n' >> "$config"
fi
```

You can confirm what is in the file afterwards:

```bash
grep CONVERSION_BASE /root/TrafficCop/traffic_monitor_config.txt
```

The alternative is to re-run the script and pick the decimal option at the interactive prompt:

```bash
cd /root/TrafficCop && ./trafficcop.sh
```

Three details about the setting are worth knowing. It is read by the main script, the port limit script and the port view script, so one edit keeps all three consistent. An invalid value or a missing field falls back to 1024 rather than failing. And it only affects the conversion of bytes to gigabytes for display and comparison, not the throttling logic itself, and it takes effect on the next minute's run without a restart.

## Log rotation that keeps the archives queryable

The log grows without limit, since the script runs every minute and writes to it in many places, and it can reach hundreds of megabytes over time. That costs disk space, and it also slows down the notification scripts, which look for the most recent status record.

The built-in rotation keeps a bounded amount on disk: a single file limit of 10 MB, three archives numbered from .1 as the newest to .3 as the oldest, and a theoretical maximum of about 40 MB. The archives are numbered and the oldest is deleted when a new one is created.

The important detail is that rotation is not deletion. Downstream notifications, the throttling state and the daily report usage, search traffic_monitor.log, then .1, then .2, then .3 in order, so a throttling or unthrottling event that happened a long time ago is still findable after rotation. That is a deliberate design choice, and it is also a coupling: the log limit constants live at the top of the main script, and the notification side loads them from a shared helper, so the two must agree. If the archive count is reduced in only one of them, the reader keeps looking for archive files that no longer exist.

## A missing cron job is silent, and there is a repair script

The whole design depends on a cron entry that runs the script every minute, and when that entry is missing or the cron service is not running, the script stops working without any error. The symptom is always the same: the log stops updating and the traffic number freezes at its last value, and the log will contain a line saying the scheduled task was not found.

The repository ships a repair script for it, which checks five things in order and fixes what it can:

```bash
bash /root/TrafficCop/fix_crontab.sh
```

It verifies that the main script exists, is executable and is new enough, that the crontab contains an entry for it, that the cron service is running and tries to start it, that your other scheduled jobs are still present, and how long ago the log was last updated. A check-only mode exists:

```bash
bash /root/TrafficCop/fix_crontab.sh --check
```

A missing cron package and a full disk or permission problem are outside what it can repair, and it says so. From version 1.0.91 the main script's own setup check tries to start the cron service when it finds it stopped, and reports it as an error event when reporting is on.

## The crontab rewrite that emptied other jobs

There is a specific past failure in this project worth understanding, because it explains why the repair script exists in its current form. Older versions of the script could wipe your crontab. If the machine had other scheduled jobs, backups or cleanup tasks, and they were gone, an earlier version of the write logic was the cause.

The reason is a two-step operation that is not atomic: remove the old entry first, then add the new one. If the second step fails, for instance because the disk is full, the entry is gone and not replaced. The current version assembles the crontab in memory, writes it once, rolls back on failure, and reads it back to verify. The README still warns against doing the manual two-step version, and recommends the repair script instead:

```bash
crontab -l 2>/dev/null | grep -v "trafficcop.sh" | crontab -
```

The important limit is that the repair script cannot recover jobs that were already lost. Those have to be re-added by hand, and there is no backup of a crontab that a script deleted.

## Throttling, shutdown, and the modes that cut you off

The script's behaviour has two axes of risk, and the README is unusually candid about both.

The first is the traffic policing mode, which shapes the interface with a rate limit. The README notes two limits: it cannot prevent a distributed denial of service style event from consuming traffic, because the traffic still flows at a rate the shaping does not change enough, and the achieved rate is not exact, so the real speed can drift from the configured one. If SSH feels slow under throttling, the documented remedy is to raise the rate limit.

The second is the shutdown mode, which cuts the network completely and is flagged as something to use carefully. That is the mode where the SSH-port-preserving behaviour matters.

Alongside the machine level behaviour, the repository has grown a per-port layer: the port limit script sets independent traffic limits for multiple ports, and a view script reports the current usage of each configured port. A separate machine limit manager handles enabling, disabling and restoring machine level limits, and there are notifiers for Telegram, PushPlus and a third service, plus a helper for per-port notifications and a script for removing limits that have been applied.

## One interactive installer, provider presets, and the honest limits

The entry point is an interactive manager downloaded and run in one command:

```bash
bash <(curl -sL https://raw.githubusercontent.com/ypq123456789/TrafficCop/main/trafficcop-manager.sh)
```

It presents a numbered menu with twelve options, covering installation of the traffic monitor, of the three notification channels, the per-port limiting and status views, the machine level limit controls, log and configuration viewing, applying presets tuned for different providers, stopping every service, and updating all components at once. The design goal is that a user has to remember one command, and each action asks for confirmation before it runs.

Alongside the main scripts sit a set of provider preset directories, named for the hosts and plans they target, which is the pragmatic part of the project: traffic accounting is not identical across providers, and the preset directories encode the differences for the ones the author has used.

The honest limits are these. The script is designed for a personal VPS with a metered plan, and it is not a general traffic analytics tool; if you want per-host history or a dashboard, that is a different project. The state is a handful of text files and counters, and the counters only exist after vnstat is installed. And the project states no licence, publishes no GitHub releases, and its last push was on 2026-10-06, so treat it as an operational script you read before running rather than a dependency you vendor.

## Conclusion

TrafficCop fits a VPS on a metered plan where the traffic window resets monthly and the provider charges for overage, and where you want the machine to protect itself without a monitor looking at it. It does not fit an unmetered box, a connection you cannot afford to have throttled, or a host where the traffic counter resets on a schedule the script does not know. Before you install it, check three things: that vnstat has been installed long enough to have real counters, since the script only starts counting after installation, that your provider's gigabyte is a decimal one, which the CONVERSION_BASE setting handles, and that the cron job is actually running, because a missing cron entry leaves the script silent with no error. The script runs as root by default, the repository states no licence, and the last push was on 2026-10-06.

## FAQ

### Why are my TrafficCop traffic numbers about 7 percent lower than my VPS invoice?

The difference is usually the gigabyte definition. TrafficCop defaults to CONVERSION_BASE 1024, where a gigabyte is 1,073,741,824 bytes, while some providers bill in decimal gigabytes of 1,000,000,000 bytes. Compare the script figure with the provider console for the same period and set the value to 1000 if the script is consistently lower.

### How do I change the CONVERSION_BASE setting in TrafficCop?

Edit the config file at `/root/TrafficCop/traffic_monitor_config.txt` directly, which takes effect on the next run, or re-run `cd /root/TrafficCop && ./trafficcop.sh` and pick the decimal option at the prompt. The field is read by the main script, the port limit script and the port view script, and an invalid value falls back to 1024.

### What should I do if TrafficCop stops updating its log?

A missing cron entry or a stopped cron service makes the script stop working silently. Run `bash /root/TrafficCop/fix_crontab.sh` to check and repair the scheduled task, or add `--check` to only diagnose without changing anything. A missing cron package or a full disk still needs manual attention.

### Can TrafficCop stop a denial of service attack from using up my traffic?

No. The README states that the traffic shaping mode cannot prevent a distributed denial of service style event from consuming traffic, and that the rate limit achieved is not exact, so the real speed can differ slightly from the configured one.

### How do I remove TrafficCop completely from a server?

The README gives three commands to kill the process, remove the directory and delete the traffic control queue on the default route interface. The shutdown mode is documented as cutting the network connection entirely, so be careful with it before you need to reach the machine.

## Sources

- [Issues](https://github.com/ypq123456789/TrafficCop/issues)
- [README](https://github.com/ypq123456789/TrafficCop/blob/main/README.md)
- [ypq123456789/TrafficCop on GitHub](https://github.com/ypq123456789/TrafficCop)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/ypq123456789-trafficcop
