Contenu | Rechercher | Menus

Annonce

DVD, clés USB et t-shirts Ubuntu-fr disponibles sur la boutique En Vente Libre

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#1 Le 29/10/2021, à 04:02

Bwice

systemd / CRONTAB / vnstat: planifier un service avec deux configs

Bonjours,
les concepts sont un peu flous pour moi, et je voudrais trouver une solution élégante à mon problème.

J'utilise vnstat pour suivre ma consomation internet, mais j'aimerais faire tourner ce service avec deux configs différentes sur une plage horraire définie.
Une instance genre "vnstat-day" qui tourne de 08AM à minuit et une autre "vnstat-night" de minuit à 08AM.

j'ai fait un dossier .vnstat dans mon /home et deux sous-dossiers "vnstat-day" et "vnstat-night" qui contiennent leurs fichiers de configurations et base de données respectifs.

Maintenant, je ne suis pas certain du comment demander à mon système de faire tourner l'une ou l'autre configurations sur une plage précise. Via un alias, un script, systemctl, ou un CRON?

Ci-joint le man de vnstat:

VNSTAT
Section: User Manuals (1)
Updated: SEPTEMBER 2021
Index Return to Main Contents  
NAME
vnstat - a console-based network traffic monitor

 
SYNOPSIS

vnstat [-5bDedhlmqstvy?] [--add] [--begin date] [--config file] [--days [limit]] [--dbdir [directory]] [--dbiflist [mode]] [--debug] [--end date] [--fiveminutes [limit]] [--help] [-hg] [--hours [limit]] [--hoursgraph] [-i interface] [--iface interface] [--iflist [mode]] [--json [mode] [limit]] [--limit limit] [--live [mode]] [--locale locale] [--longhelp] [--months [limit]] [--oneline [mode]] [--query] [--rateunit [mode]] [--remove] [--rename name] [-ru [mode]] [--setalias alias] [--short] [--showconfig] [--style number] [--top [limit]] [-tr [time]] [--traffic [time]] [--version] [--xml [mode] [limit]] [--years [limit]] [interface]

 
DESCRIPTION

vnStat is a console-based network traffic monitor. It keeps a log of 5 minute interval, hourly, daily, monthly and yearly network traffic for the selected interface(s). However, it isn't a packet sniffer. The traffic information is read from the proc(5) or sys filesystems depending on availability resulting in light use of system resources regardless of network traffic rate. That way vnStat can be used even without root permissions on most systems.

Functionality is divided into two commands. The purpose of the vnstat command is to provide an interface for querying the traffic information stored in the database whereas the daemon vnstatd(8) is responsible for data retrieval, caching and storage. Although the daemon process is constantly running as a service, it is actually spending most of its time sleeping between data updates.

 
OPTIONS

--add
    Create database entry for interface specified with -i or --iface option. The daemon can be running during this operation and will automatically start monitoring the interface without a restart within SaveInterval minutes if configuration option RescanDatabaseOnSave is enabled. Otherwise the daemon needs to be restarted in order for the added interface to be monitored.

-b, --begin date
    Begin the list output with a specific date / time defined by date instead of the begin being selected based on the number of entries to be shown. If date isn't available in the database then the closest later date will be used. date supports the following formats: YYYY-MM-DD HH:MM and YYYY-MM-DD. This option can only be used with --json , --xml and list outputs.

--config file
    Use file as configuration file instead of using automatic configuration file search functionality.

-d, --days [limit]
    Show traffic statistics on a daily basis for the last days. The length of the list will be limited to 30 entries unless configured otherwise or unless the optional limit parameter is used. All entries stored in the database will be shown if limit is set to 0.

--dbdir directory
    Use directory as database directory instead of using the directory specified in the configuration file or the hardcoded default if no configuration file is available.

--dbiflist [mode]
    List interfaces currently in the database. If mode is not defined or is set to 0 then the output will use a one line verbose format. If mode is set to 1 then the output will contain one interface per line. See also --iflist.

-D, --debug
    Show additional debug output.

-e, --end date
    End the list output with a specific date / time defined by date instead of the latest date / time in the database. If date isn't available in the database then the closest earlier date will be used. date supports the following formats: YYYY-MM-DD HH:MM and YYYY-MM-DD. This option can only be used with --json , --xml and list outputs. The top list also requires --begin to be used at the same time with this option.

-5, --fiveminutes [limit]
    Show traffic statistics with a 5 minute resolution for the last hours. The length of the list will be limited to 24 entries unless configured otherwise or unless the optional limit parameter is used. All entries stored in the database will be shown if limit is set to 0.

-h, --hours [limit]
    Show traffic statistics on a hourly basis. The length of the list will be limited to 24 entries unless configured otherwise or unless the optional limit parameter is used. All entries store in the database will be shown if the limit is set to 0.

-hg, --hoursgraph
    Show traffic statistics on a hourly basis for the last 24 hours using a bar graph followed by a table representing the numerical data.

-i, --iface interface
    Select one specific interface and apply actions to only it. For queries, it is possible to merge the information of two or more interfaces using the interface1+interface2+... syntax. All provided interfaces must be unique and must exist in the database when the merge syntax is used.

--iflist [mode]
    List currently available interfaces. If mode is not defined or is set to 0 then the output will use a one line verbose format. If mode is set to 1 then the output will contain one interface per line. See also --dbiflist.

--json [mode] [limit]
    Show database content for selected interface or all interfaces in json format. All traffic values in the output are in bytes. An optional mode parameter can be used for limiting the output to only selected information. Everything is shown by default. Setting mode to 'f' will output only 5 minute resolution entries, 'h' hours, 'd' days, 'm' months, 'y' years and 't' the top days. Alternatively or in combination with mode an optional limit parameter can be used to limit the number of entries in the output. The --json option can be used in combination with -l, --live and -tr options without mode or limit having any effect to the output. The jsonversion field in the output contains the API version information. It will be changed only when the names or structures of previously existing content gets changed. In comparison, the vnstatversion field exists only as extra information.

--limit limit
    Set the maximum number of shown entries in list outputs to limit. Usage of --limit overrides the default list entry limit values and the optional limit parameter given directly for a list query. All entries stored in the database will be shown if limit is set to 0. --limit can also be used to control the length of --json and --xml outputs.

-l, --live [mode]
    Display current transfer rate for the selected interface in real time until interrupted. Statistics will be shown after interruption if the runtime was more than 10 seconds. An optional mode parameter can be used to select between the displaying of packets per second (mode 0) and transfer counters (mode 1) during execution. --style can also be used to affect the layout of the output. The output will be in json format if used in combination with --json option.

--locale locale
    Use locale instead of using the locale setting specified in the configuration file or the system default if no configuration file is available.

--longhelp
    Show complete options list.

-m, --months [limit]
    Show traffic statistics on a monthly basis for the last months. The length of the list will be limited to 12 entries unless configured otherwise or unless the optional limit parameter is used. All entries stored in the database will be shown if limit is set to 0.

--oneline [mode]
    Show traffic summary for selected interface using one line with a parsable format. The output contains 15 fields with ; used as field delimiter. The 1st field contains the API version information of the output that will only be changed in future versions if the field content or structure changes. The following fields in order 2) interface name, 3) timestamp for today, 4) rx for today, 5) tx for today, 6) total for today, 7) average traffic rate for today, 8) timestamp for current month, 9) rx for current month, 10) tx for current month, 11) total for current month, 12) average traffic rate for current month, 13) all time total rx, 14) all time total tx, 15) all time total traffic. An optional mode parameter can be used to force all fields to output in bytes without the unit itself shown.

-q, --query
    Force database query mode.

--remove
    Delete the database entry for the interface specified with -i or --iface and stop monitoring it. The daemon can be running during this operation and will automatically detect the change.

--rename name
    Rename the interface specified with -i or --iface in the database with new name name. The new name cannot already exist in the database. This operation doesn't cause any data loss. The daemon should not be running during this operation.

-ru, --rateunit [mode]
    Swap the configured rate unit. If rate has been configured to be shown in bytes then rate will be shown in bits if this option is present. In the same way, if rate has been configured to be shown in bits then rate will be shown in bytes when this option is present. Alternatively, mode with either 0 or 1 can be used as parameter for this option in order to select between bytes (0) and bits (1) regardless of the configuration file setting.

--setalias alias
    Set alias as an alias for the selected interface to be shown in queries. The set alias can be removed by specifying an empty string for alias. The daemon can be running during this operation.

-s, --short
    Use short output mode. This mode is also used when more than one interface is available in the database and no specific interface is selected.

--showconfig
    Show current configuration using the same format as the configuration file itself uses.

--style number
    Modify the content and style of outputs. Set number to 0 for a narrower output, 1 for enabling bar column, 2 for same as previous but with average traffic rate visible in summary output and 3 for enabling average traffic rate in all outputs where it is supported. 4 disables the use of terminal control characters in -l / --live mode.

-t, --top [limit]
    Show all time top traffic days. The length of the list will be limited to 10 entries unless configured otherwise or unless the optional limit parameter is used. All entries stored in the database will be shown if limit is set to 0. When used with --begin and optionally with --end, the list will be generated using the daily data instead of separate top entries. The availability of daily data defines the boundaries the date specific query can access.

-tr, --traffic [time]
    Calculate how much traffic goes through the selected interface during the given time seconds. The time will be 5 seconds if a number parameter isn't specified. The output will be in json format if used in combination with --json option. However, in that case, the countdown before results isn't shown.

-v, --version
    Show current version.

--xml [mode] [limit]
    Show database content for selected interface or all interfaces in xml format. All traffic values in the output are in bytes. An optional mode parameter can be used for limiting the output to only selected information. Everything is shown by default. Setting mode to 'f' will output only 5 minute resolution entries, 'h' hours, 'd' days, 'm' months, 'y' years and 't' the top days. Alternatively or in combination with mode an optional limit parameter can be used to limit the number of entries in the output. The xmlversion field in the output contains the API version information. It will be changed only when the names or structures of previously existing content gets changed. In comparison, the vnstatversion field exists only as extra information.

-y, --years [limit]
    Show traffic statistics on a yearly basis for the last years. The list will show all entries by default unless configured otherwise or unless the optional limit parameter is used. All entries stored in the database will also be shown if limit is set to 0.

-?, --help
    Show a command option summary.

 
FILES

/var/lib/vnstat/
    Default database directory.

/etc/vnstat.conf
    Config file that will be used unless $HOME/.vnstatrc exists. See vnstat.conf(5) for more information.

 
EXAMPLES

vnstat
    Display traffic summary for the default interface or multiple interfaces when more than one is monitored.

vnstat -i eth0+eth1+eth3
    Display traffic summary for a merge of interfaces eth0, eth1 and eth3.

vnstat -i eth2 --xml
    Output all information about interface eth2 in xml format.

vnstat --json
    Output all information of all monitored interfaces in json format.

vnstat -i eth0 --setalias local
    Give interface eth0 the alias "local". That information will be later visible as a label when eth0 is queried.

vnstat -i eth2 --remove
    Delete database entries for interface eth2 and stop monitoring it.

 
RESTRICTIONS

Updates need to be executed at least as often as it is possible for the interface to generate enough traffic to overflow the kernel interface traffic counter. Otherwise, it is possible that some traffic won't be seen. With 32-bit interface traffic counters, the maximum time between two updates depends on how fast the interface can transfer 4 GiB. Note that there is no guarantee that a 64-bit kernel has 64-bit interface traffic counters for all interfaces. Calculated theoretical times are:

    10 Mbit: 54 minutes	
    100 Mbit: 5 minutes	
    1000 Mbit: 30 seconds	

Virtual and aliased interfaces cannot be monitored because the kernel doesn't provide traffic information for that type of interfaces. Such interfaces are usually named eth0:0, eth0:1, eth0:2 etc. where eth0 is the actual interface being aliased.

Using long date output formats may cause misalignment in shown columns if the length of the date exceeds the fixed size allocation.

 
AUTHOR

Teemu Toivola <tst at iki dot fi>

 
SEE ALSO

vnstatd(8), vnstati(1), vnstat.conf(5), proc(5), ifconfig(8), units(7)

 
Index

NAME
SYNOPSIS
DESCRIPTION
OPTIONS
FILES
EXAMPLES
RESTRICTIONS
AUTHOR
SEE ALSO

This document was created by man2html, using the manual pages.
Time: 17:10:30 GMT, September 04, 2021

Et le fichier de configuration:

# vnStat 1.18 config file
##

# default interface
Interface "eth0"

# location of the database directory
DatabaseDir "/var/lib/vnstat"

# locale (LC_ALL) ("-" = use system locale)
Locale "-"

# on which day should months change
MonthRotate 1

# date output formats for -d, -m, -t and -w
# see 'man date' for control codes
DayFormat    "%x"
MonthFormat  "%b '%y"
TopFormat    "%x"

# characters used for visuals
RXCharacter       "%"
TXCharacter       ":"
RXHourCharacter   "r"
TXHourCharacter   "t"

# how units are prefixed when traffic is shown
# 0 = IEC standard prefixes (KiB/MiB/GiB/TiB)
# 1 = old style binary prefixes (KB/MB/GB/TB)
UnitMode 0

# how units are prefixed when traffic rate is shown
# 0 = IEC binary prefixes (Kibit/s...)
# 1 = SI decimal prefixes (kbit/s...)
RateUnitMode 1

# output style
# 0 = minimal & narrow, 1 = bar column visible
# 2 = same as 1 except rate in summary and weekly
# 3 = rate column visible
OutputStyle 3

# used rate unit (0 = bytes, 1 = bits)
RateUnit 1

# number of decimals to use in outputs
DefaultDecimals 2
HourlyDecimals 1

# spacer for separating hourly sections (0 = none, 1 = '|', 2 = '][', 3 = '[ ]')
HourlySectionStyle 2

# try to detect interface maximum bandwidth, 0 = disable feature
# MaxBandwidth will be used as fallback value when enabled
BandwidthDetection 1

# maximum bandwidth (Mbit) for all interfaces, 0 = disable feature
# (unless interface specific limit is given)
MaxBandwidth 1000

# interface specific limits
#  example 8Mbit limit for eth0 (remove # to activate):
#MaxBWeth0 8

# how many seconds should sampling for -tr take by default
Sampletime 5

# default query mode
# 0 = normal, 1 = days, 2 = months, 3 = top10
# 4 = exportdb, 5 = short, 6 = weeks, 7 = hours
QueryMode 0

# filesystem disk space check (1 = enabled, 0 = disabled)
CheckDiskSpace 1

# database file locking (1 = enabled, 0 = disabled)
UseFileLocking 1

# how much the boot time can variate between updates (seconds)
BootVariation 15

# log days without traffic to daily list (1 = enabled, 0 = disabled)
TrafficlessDays 1


# vnstatd
##

# switch to given user when started as root (leave empty to disable)
DaemonUser ""

# switch to given user when started as root (leave empty to disable)
DaemonGroup ""

# how many minutes to wait during daemon startup for system clock to
# sync time if most recent database update appears to be in the future
TimeSyncWait 5

# how often (in seconds) interface data is updated
UpdateInterval 30

# how often (in seconds) interface status changes are checked
PollInterval 5

# how often (in minutes) data is saved to file
SaveInterval 5

# how often (in minutes) data is saved when all interface are offline
OfflineSaveInterval 30

# how often (in minutes) bandwidth detection is redone when
# BandwidthDetection is enabled (0 = disabled)
BandwidthDetectionInterval 5

# force data save when interface status changes (1 = enabled, 0 = disabled)
SaveOnStatusChange 1

# enable / disable logging (0 = disabled, 1 = logfile, 2 = syslog)
UseLogging 2

# create dirs if needed (1 = enabled, 0 = disabled)
CreateDirs 1

# update ownership of files if needed (1 = enabled, 0 = disabled)
UpdateFileOwner 1

# file used for logging if UseLogging is set to 1
LogFile "/var/log/vnstat/vnstat.log"

# file used as daemon pid / lock file
PidFile "/var/run/vnstat/vnstat.pid"


# vnstati
##

# title timestamp format
HeaderFormat "%x %H:%M"

# show hours with rate (1 = enabled, 0 = disabled)
HourlyRate 1

# show rate in summary (1 = enabled, 0 = disabled)
SummaryRate 1

# layout of summary (1 = with monthly, 0 = without monthly)
SummaryLayout 1

# transparent background (1 = enabled, 0 = disabled)
TransparentBg 0

# image colors
CBackground     "FFFFFF"
CEdge           "AEAEAE"
CHeader         "606060"
CHeaderTitle    "FFFFFF"
CHeaderDate     "FFFFFF"
CText           "000000"
CLine           "B0B0B0"
CLineL          "-"
CRx             "92CF00"
CTx             "606060"
CRxD            "-"
CTxD            "-"

Merci de me mettre sur la bonne voie.
Cordialement.


Ubuntu-Mate 18.04 LTS 64-bit Debian Buster | HP-Pavilion-15-Notebook-PC | AMD A4-6210 apu with amd radeon r3 graphics × 4
Upgrade => 1x Crucial SO-DIMM DDR3L 8 Go 1600 MHz 1,35 Volts | SSD Corsair Force Series LE - 480 Go SATA 3 (6 Gb/s)

Hors ligne

#2 Le 26/11/2021, à 08:36

jepassaitparla

Re : systemd / CRONTAB / vnstat: planifier un service avec deux configs

bonjour,
ça sent l'internet par satellite wink
sans trop réfléchir (ni connaître vnstat) je te proposerais un truc de ce genre:

un script launch_vnstat.sh (que tu devras écrire) qui fait deux choses:
- il éteint vnstat
- il relance vnstat avec la config donnée en argument
     +
deux tâches cron:
minuit: launch_vnstat.sh config_de_la_nuit
8h      : laucnh_vnstat.sh config_du_jour


dans ton script quelque chose qui ressemble (grossièrement) à ça

ps aux | grep vnstat | awk '{print$1}'  

pour identifier le processus vnstat en cours d'éxecution (PID)

kill <le PID obtenu avec la commande au dessus>

pour tuer le(s) processus vnstat en cours

vnstat --config $1

pour relancer vnstat avec la config fournie en argument


amuses-toi bien,

sans vouloir préjuger de ton niveau:
les premiers scripts qu'on écrit sont toujours un peu difficiles mais c'est amusant et assez satisfaisant (quand ça fonctionne enfin wink ).

Dernière modification par jepassaitparla (Le 26/11/2021, à 08:37)

Hors ligne