-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwireguardstats.ps1
178 lines (139 loc) · 5.13 KB
/
wireguardstats.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
<#
.SYNOPSIS Script for converting Wireguard into HTML-Report
.DESCRIPTION
.NOTES Author: Gill Bates, Last Update: 22.08.2021
#>
[string]$db = ".\wireguard.SQLite" # Path to DB
###### FUNCTION AREA ######
###########################
function Get-Traffic {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$TrafficinBytes,
[Parameter(Mandatory = $false)]
[switch]$Unit = $false
)
if (($TrafficinBytes / 1MB) -lt 1024) {
if ($Unit) {
return ([math]::Round($TrafficinBytes / 1MB, 2)).ToString() + (" (MB)").ToString()
}
else {
return [math]::Round($TrafficinBytes / 1MB, 2)
}
}
elseif (($TrafficinBytes / 1MB) -gt 1024) {
if ($Unit) {
return ([math]::Round($TrafficinBytes / 1GB, 2)).ToString() + (" (GB)").ToString()
}
else {
return [math]::Round($TrafficinBytes / 1GB, 2)
}
}
}
function Get-ClientName {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]$PreSharedKey
)
$Files = Get-ChildItem -Path "/etc/wireguard/clients" -Filter *.conf
foreach ($i in $Files) {
$tmp = Get-Content -Path $i.FullName
if ($tmp -Like "*$PreSharedKey*") {
return $i.BaseName
}
}
}
###### PROGRAM AREA #######
###########################
##### DATABASE SETUP ######
###########################
#region Database Check
if (Test-Path -Path $db -PathType leaf) {
Write-Output "[OK] Database found! Proceed ..."
}
if (!(Test-Path -Path $db -PathType leaf)) {
try {
Write-Warning "Database not found! Creating '$db' ..." -WarningAction Continue
$query = "CREATE TABLE wireguard (
Id INTEGER(6) PRIMARY KEY,
Client NVARCHAR(250),
PreSharedKey NVARCHAR(250),
LastSeen NVARCHAR(250),
RemoteIP NVARCHAR(250),
TrafficRX NVARCHAR(250),
TrafficTX NVARCHAR(250),
TrafficTotal NVARCHAR(250)
)"
Invoke-SqliteQuery -Query $query -DataSource $db
if ($?) { Write-Output "[OK] Database successfully created!" }
}
catch {
throw "[ERROR] Can't initialize Database: $($_.Exception.Message)!"
}
}
# Running on Linux
$OutputPath = "/var/www/html/admin/traffic.html"
$Json = /usr/local/bin/wg-json.sh | ConvertFrom-Json -AsHashtable
if (!$Json) {
throw "[ERROR] Don't get any Data from Wireguard Server!"
}
$Report = @()
($Json.wg0.peers).GetEnumerator() | ForEach-Object {
if ($_.Value.latestHandshake) {
[datetime]$latestHandshake = (Get-Date 01.01.1970) + ([System.TimeSpan]::fromseconds($_.Value.latestHandshake))
}
else {
[int]$latestHandshake = 0
}
$obj = [PSCustomObject]@{
Client = (Get-ClientName -PreSharedKey $_.Value.presharedKey)
PreSharedKey = $_.Value.presharedKey
LastSeen = $latestHandshake
RemoteIP = if ($_.Value.endpoint) { ($_.Value.endpoint) }
TrafficRX = if ($_.Value.transferRx) { Get-Traffic -TrafficinBytes $_.Value.transferRx }
TrafficTX = if ($_.Value.transferTx) { Get-Traffic -TrafficinBytes $_.Value.transferTx }
TrafficTotal = if ($_.Value.transferTx -and $_.Value.transferRx) { Get-Traffic -TrafficinBytes ($_.Value.transferTx + $_.Value.transferRx) -Unit }
}
$Report += $obj
}
$Report | Sort-Object -Property "TrafficTX" -Descending | Convertto-HTML -Title (Get-Date) | Out-File -FilePath $OutputPath
$Report | Sort-Object -Property "TrafficTX" -Descending | ft * -AutoSize
# Database & Restart
$Uptime = New-TimeSpan -Start (Get-Process | Where-Object { $_.Name -eq "wg-crypt-wg0" }).StartTime -End (Get-Date)
# Reset Statistic by Restaring Service
if ($Uptime.Minutes -ge 1440) {
# Open Database Connection
try {
Write-Output "Open Database Connection '$db' ..."
$conn = New-SQLiteConnection @Verbose -DataSource $db
$conn.ConnectionString | Out-Null
}
catch {
throw "[ERROR] Can't open Database Connection $($_.Exception.Message)!"
}
#endregion
Write-Output "Storing Records into Database ..."
$Report | ForEach-Object {
[int]$Id = Invoke-SqliteQuery -SQLiteConnection $conn -Query "SELECT Id FROM wireguard;" | Select-Object -ExpandProperty Id | Sort-Object -Descending | Select-Object -First 1
[int]$Id++ | Out-Null
Invoke-SqliteQuery -SQLiteConnection $conn -Query "INSERT INTO wireguard (
Id, Client, PreSharedKey, LastSeen, RemoteIP, TrafficRX, TrafficTX, TrafficTotal)
VALUES (
'$Id', '$($_.Client)', '$($_.PreSharedKey)', '$($_.LastSeen)', '$($_.RemoteIP)', '$($_.TrafficRX)', '$($_.TrafficTX)', '$($_.TrafficTotal)');"
}
# Closing Database
Write-Output "Closing Database Connection ..."
$conn.Close()
$conn.State
Write-Output "Restarting Wireguard Service ..."
systemctl restart [email protected]
}
else {
Write-Output "Wireguard Service is running since '$($Uptime.Hours)' hours. No Restart needed!"
}
Write-Output "[OK] All Jobs done! Exit here."
Write-Output ""
Exit
#End of Script