From bcae4dfa7b26ffc162496cedf08994c1990460a1 Mon Sep 17 00:00:00 2001 From: Alex Kup <116945542+Lifailon@users.noreply.github.com> Date: Fri, 3 Nov 2023 16:25:24 +0300 Subject: [PATCH] add api scripts and telegram modules --- Scripts/Get-FromTelegram.psm1 | 31 +++++++ Scripts/Get-GoogleTranslate.psm1 | 21 +++++ Scripts/PerformanceTo-InfluxDB.ps1 | 27 ++++++ Scripts/PingTo-InfluxDB.ps1 | 10 +++ Scripts/Pode-WinMan.ps1 | 52 +++++++++++ Scripts/Send-ToTelegram.psm1 | 14 +++ Scripts/Telegram-Bot-Service.ps1 | 63 ++++++++++++++ Scripts/Zabbix-API-Last-Uptime-All-Hosts.ps1 | 92 ++++++++++++++++++++ 8 files changed, 310 insertions(+) create mode 100644 Scripts/Get-FromTelegram.psm1 create mode 100644 Scripts/Get-GoogleTranslate.psm1 create mode 100644 Scripts/PerformanceTo-InfluxDB.ps1 create mode 100644 Scripts/PingTo-InfluxDB.ps1 create mode 100644 Scripts/Pode-WinMan.ps1 create mode 100644 Scripts/Send-ToTelegram.psm1 create mode 100644 Scripts/Telegram-Bot-Service.ps1 create mode 100644 Scripts/Zabbix-API-Last-Uptime-All-Hosts.ps1 diff --git a/Scripts/Get-FromTelegram.psm1 b/Scripts/Get-FromTelegram.psm1 new file mode 100644 index 0000000..473b8e5 --- /dev/null +++ b/Scripts/Get-FromTelegram.psm1 @@ -0,0 +1,31 @@ +function Get-FromTelegram { +param ( + $token = "687...:AAF...", + [switch]$last, + [switch]$date +) +$endpoint = "getUpdates" +$url = "https://api.telegram.org/bot$token/$endpoint" +$result = Invoke-RestMethod -Uri $url +if ($date) { +$Collections = New-Object System.Collections.Generic.List[System.Object] +foreach ($r in $($result.result)) { + $EpochTime = [DateTime]"1/1/1970" + $TimeZone = Get-TimeZone + $UTCTime = $EpochTime.AddSeconds($r.message.date) + $d = $UTCTime.AddMinutes($TimeZone.BaseUtcOffset.TotalMinutes) + #$d + $Collections.Add([PSCustomObject]@{ + Message = $r.message.text; + Date = $d + }) +} +$Collections +} else { +if ($last) { + $result.result.message.text[-1] +} else { + $result.result.message.text +} +} +} \ No newline at end of file diff --git a/Scripts/Get-GoogleTranslate.psm1 b/Scripts/Get-GoogleTranslate.psm1 new file mode 100644 index 0000000..a90dd59 --- /dev/null +++ b/Scripts/Get-GoogleTranslate.psm1 @@ -0,0 +1,21 @@ +function Get-Translate { + param ( + $data, + $key = "KEY" # Get https://cloud.google.com/translate/docs/reference/rest + ) + $url = "https://translation.googleapis.com/language/translate/v2?key=$key" + $body = @{ + q = $data + target = "ru" + source = "en" + } | ConvertTo-Json + try { + $response = Invoke-RestMethod -Uri $url -Method POST -ContentType "application/json" -Body $body + $translation = $response.data.translations[0].translatedText + return $translation + } catch { + Write-Output "Error: $($_.Exception.Message)" + } +} + +# Get-Translate -data "What is your name" \ No newline at end of file diff --git a/Scripts/PerformanceTo-InfluxDB.ps1 b/Scripts/PerformanceTo-InfluxDB.ps1 new file mode 100644 index 0000000..6ffa3b0 --- /dev/null +++ b/Scripts/PerformanceTo-InfluxDB.ps1 @@ -0,0 +1,27 @@ +function ConvertTo-Encoding ([string]$From, [string]$To) { + Begin { + $encFrom = [System.Text.Encoding]::GetEncoding($from) + $encTo = [System.Text.Encoding]::GetEncoding($to) + } + Process { + $bytes = $encTo.GetBytes($_) + $bytes = [System.Text.Encoding]::Convert($encFrom, $encTo, $bytes) + $encTo.GetString($bytes) + } +} + +$localization = (Get-Culture).LCID # текущая локализация +if ($localization -eq 1049) { + $performance = "\\$(hostname)\Процессор(_Total)\% загруженности процессора" | ConvertTo-Encoding UTF-8 windows-1251 +} else { + $performance = "\Processor(_Total)\% Processor Time" +} + +$tz = (Get-TimeZone).BaseUtcOffset.TotalMinutes +while ($true) { + $unixtime = (New-TimeSpan -Start (Get-Date "01/01/1970") -End ((Get-Date).AddMinutes(-$tz))).TotalSeconds + $timestamp = ([string]$unixtime -replace "\..+") + "000000000" + [double]$value = (Get-Counter $performance).CounterSamples.CookedValue.ToString("0.00").replace(",",".") + Invoke-RestMethod -Method POST -Uri "http://192.168.3.104:8086/write?db=powershell" -Body "performance,host=$(hostname),counter=CPU value=$value $timestamp" + sleep 5 +} \ No newline at end of file diff --git a/Scripts/PingTo-InfluxDB.ps1 b/Scripts/PingTo-InfluxDB.ps1 new file mode 100644 index 0000000..f352e13 --- /dev/null +++ b/Scripts/PingTo-InfluxDB.ps1 @@ -0,0 +1,10 @@ +while ($true) { + $tz = (Get-TimeZone).BaseUtcOffset.TotalMinutes + $unixtime = (New-TimeSpan -Start (Get-Date "01/01/1970") -End ((Get-Date).AddMinutes(-$tz))).TotalSeconds # -3h UTC + $timestamp = ([string]$unixtime -replace "\..+") + "000000000" + $tnc = tnc 8.8.8.8 + $Status = $tnc.PingSucceeded + $RTime = $tnc.PingReplyDetails.RoundtripTime + Invoke-RestMethod -Method POST -Uri "http://192.168.3.104:8086/write?db=powershell" -Body "ping,host=$(hostname) status=$status,rtime=$RTime $timestamp" + sleep 1 +} \ No newline at end of file diff --git a/Scripts/Pode-WinMan.ps1 b/Scripts/Pode-WinMan.ps1 new file mode 100644 index 0000000..fc9806d --- /dev/null +++ b/Scripts/Pode-WinMan.ps1 @@ -0,0 +1,52 @@ +Start-PodeServer { + Add-PodeEndpoint -Address localhost -Port "8080" -Protocol "HTTP" + ### Get info endpoints + Add-PodeRoute -Path "/" -Method "GET" -ScriptBlock { + Write-PodeJsonResponse -Value @{ + "service"="/api/service"; + "process"="/api/process" + } + } + ### GET + Add-PodeRoute -Path "/api/service" -Method "GET" -ScriptBlock { + Write-PodeJsonResponse -Value $( + Get-Service | Select-Object Name,@{ + Name="Status"; Expression={[string]$_.Status} + },@{ + Name="StartType"; Expression={[string]$_.StartType} + } | ConvertTo-Json + ) + } + Add-PodeRoute -Path "/api/process" -Method "GET" -ScriptBlock { + Write-PodeJsonResponse -Value $( + Get-Process | Sort-Object -Descending CPU | Select-Object -First 15 ProcessName, + @{Name="ProcessorTime"; Expression={$_.TotalProcessorTime -replace "\.\d+$"}}, + @{Name="Memory"; Expression={[string]([int]($_.WS / 1024kb))+"MB"}}, + @{Label="RunTime"; Expression={((Get-Date) - $_.StartTime) -replace "\.\d+$"}} + ) + } + Add-PodeRoute -Path "/api/process-html" -Method "GET" -ScriptBlock { + Write-PodeHtmlResponse -Value ( + Get-Process | Sort-Object -Descending CPU | Select-Object -First 15 ProcessName, + @{Name="ProcessorTime"; Expression={$_.TotalProcessorTime -replace "\.\d+$"}}, + @{Name="Memory"; Expression={[string]([int]($_.WS / 1024kb))+"MB"}}, + @{Label="RunTime"; Expression={((Get-Date) - $_.StartTime) -replace "\.\d+$"}} # Auto ConvertTo-Html + ) + } + ### POST + Add-PodeRoute -Path "/api/service" -Method "POST" -ScriptBlock { + # https://pode.readthedocs.io/en/latest/Tutorials/WebEvent/ + # $WebEvent | Out-Default + $Value = $WebEvent.Data["ServiceName"] + $Status = (Get-Service -Name $Value).Status + Write-PodeJsonResponse -Value @{ + "Name"="$Value"; + "Status"="$Status"; + } + } +} + +# irm http://localhost:8080/api/service -Method Get +# irm http://localhost:8080/api/process -Method Get +# irm http://localhost:8080/api/process-html -Method Get +# irm http://localhost:8080/api/service -Method Post -Body @{"ServiceName" = "AnyDesk"} \ No newline at end of file diff --git a/Scripts/Send-ToTelegram.psm1 b/Scripts/Send-ToTelegram.psm1 new file mode 100644 index 0000000..e25084a --- /dev/null +++ b/Scripts/Send-ToTelegram.psm1 @@ -0,0 +1,14 @@ +function Send-ToTelegram { +param ( +[Parameter(Mandatory = $True)]$Text, +$token = "687...:AAF...", +$chat = "125468108" +) +$endpoint = "sendMessage" +$url = "https://api.telegram.org/bot$token/$endpoint" +$Body = @{ +chat_id = $Chat +text = $Text +} +Invoke-RestMethod -Uri $url -Body $Body +} \ No newline at end of file diff --git a/Scripts/Telegram-Bot-Service.ps1 b/Scripts/Telegram-Bot-Service.ps1 new file mode 100644 index 0000000..10a7e5c --- /dev/null +++ b/Scripts/Telegram-Bot-Service.ps1 @@ -0,0 +1,63 @@ +function Get-FromTelegram { +param ( + $token = "687...:AAF...", + [switch]$last, + [switch]$date +) +$endpoint = "getUpdates" +$url = "https://api.telegram.org/bot$token/$endpoint" +$result = Invoke-RestMethod -Uri $url +if ($date) { +$Collections = New-Object System.Collections.Generic.List[System.Object] +foreach ($r in $($result.result)) { + $EpochTime = [DateTime]"1/1/1970" + $TimeZone = Get-TimeZone + $UTCTime = $EpochTime.AddSeconds($r.message.date) + $d = $UTCTime.AddMinutes($TimeZone.BaseUtcOffset.TotalMinutes) + #$d + $Collections.Add([PSCustomObject]@{ + Message = $r.message.text; + Date = $d + }) +} +$Collections +} else { +if ($last) { + $result.result.message.text[-1] +} else { + $result.result.message.text +} +} +} + +function Send-ToTelegram { +param ( +[Parameter(Mandatory = $True)]$Text, +$token = "687...:AAF...", +$chat = "125468108" +) +$endpoint = "sendMessage" +$url = "https://api.telegram.org/bot$token/$endpoint" +$Body = @{ +chat_id = $Chat +text = $Text +} +Invoke-RestMethod -Uri $url -Body $Body +} + +$LastDate = (Get-FromTelegram -date)[-1].Date +while ($true) { + $LastMessage = (Get-FromTelegram -date)[-1] + Start-Sleep 1 + $LastDateTest = $LastMessage.Date + if (($LastMessage.Message -match "/Service") -and ($LastDate -ne $LastDateTest)) { + $ServiceName = $($LastMessage.Message -split " ")[-1] + $Result = $(Get-Service $ServiceName -ErrorAction Ignore).Status + if ($Result) { + Send-ToTelegram -Text $Result + } else { + Send-ToTelegram -Text "Service not found" + } + $LastDate = $LastDateTest + } +} \ No newline at end of file diff --git a/Scripts/Zabbix-API-Last-Uptime-All-Hosts.ps1 b/Scripts/Zabbix-API-Last-Uptime-All-Hosts.ps1 new file mode 100644 index 0000000..538879e --- /dev/null +++ b/Scripts/Zabbix-API-Last-Uptime-All-Hosts.ps1 @@ -0,0 +1,92 @@ +$ip = "192.168.3.102" +$url = "http://$ip/zabbix/api_jsonrpc.php" +$token = "914ee100f4e8c4b68a70eab2a0a1fb153cfcd4905421d0ffacb82c20a57aa50e" + +function ConvertFrom-UnixTime { + param ( + $intime + ) + $EpochTime = [DateTime]"1/1/1970" + $TimeZone = Get-TimeZone + $UTCTime = $EpochTime.AddSeconds($intime) + $UTCTime.AddMinutes($TimeZone.BaseUtcOffset.TotalMinutes) +} + +function ConvertTo-TimeSpan { + param ( + $insec + ) + $TimeSpan = [TimeSpan]::fromseconds($insec) + "{0:dd' day 'hh\:mm\:ss}" -f $TimeSpan +} + +### Получить список всех хостов (имя и id) +$data = @{ + "jsonrpc"="2.0"; + "method"="host.get"; + "params"=@{ + "output"=@( + "hostid"; + "host"; + ); + }; + "id"=2; + "auth"=$token; +} +$hosts = (Invoke-RestMethod -Method POST -Uri $url -Body ($data | ConvertTo-Json) -ContentType "application/json").Result + +### Получить id элемента данных по наименованию ключа для каждого хоста +$Collections = New-Object System.Collections.Generic.List[System.Object] +foreach ($h in $hosts) { + $data = @{ + "jsonrpc"="2.0"; + "method"="item.get"; + "params"=@{ + "hostids"=@($h.hostid); + }; + "auth"=$token; + "id"=1; + } + $items = (Invoke-RestMethod -Method POST -Uri $url -Body ($data | ConvertTo-Json) -ContentType "application/json").Result + $items_id = ($items | Where-Object key_ -match system.uptime).itemid + if ($items_id -ne $null) { + $Collections.Add([PSCustomObject]@{ + host = $h.host; + hostid = $h.hostid; + item_id_uptime = $items_id + }) + } +} + +### Получить всю историю элемента данных по его id для каждого хоста +$Collections_output = New-Object System.Collections.Generic.List[System.Object] +foreach ($c in $Collections) { + $data = @{ + "jsonrpc"="2.0"; + "method"="history.get"; + "params"=@{ + "hostids"=$c.hostid; + "itemids"=$c.item_id_uptime; + }; + "auth"=$token; + "id"=1; + } + $items_data_uptime = (Invoke-RestMethod -Method POST -Uri $url -Body ($data | ConvertTo-Json) -ContentType "application/json").Result + + ### Convert Secconds To TimeSpan and DateTime + $sec = $items_data_uptime.value + $UpTime = ConvertTo-TimeSpan $sec[-1] + + ### Convert From Unix Time + $time = $items_data_uptime.clock + $GetDataTime = ConvertFrom-UnixTime $time[-1] + + $Collections_output.Add([PSCustomObject]@{ + host = $c.host; + hostid = $c.hostid; + item_id_uptime = $c.item_id_uptime; + GetDataTime = $GetDataTime + UpTime = $UpTime + }) +} +$Collections_output | Format-Table \ No newline at end of file