diff --git a/Scripts/Add-ADUserToMySQL.ps1 b/Scripts/Add-ADUserToMySQL.ps1 new file mode 100644 index 0000000..7605543 --- /dev/null +++ b/Scripts/Add-ADUserToMySQL.ps1 @@ -0,0 +1,19 @@ +$ip = "192.168.1.253" +$user = "posh" +$pass = "1qaz!QAZ" +$db = "db_aduser" +Add-Type –Path "$home\Documents\MySQL-Connector-NET\8.0.31-4.8\MySql.Data.dll" +$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ +ConnectionString="server=$ip;uid=$user;pwd=$pass;database=$db" +} +$Connection.Open() +$Command = New-Object MySql.Data.MySqlClient.MySqlCommand +$Command.Connection = $Connection +$UserList = Get-ADUser -filter * -properties name,EmailAddress +foreach ($user in $UserList) { +$uname=$user.Name +$uemail=$user.EmailAddress +$Command.CommandText = "INSERT INTO table_aduser (Name,Email) VALUES ('$uname','$uemail')" +$Command.ExecuteNonQuery() +} +$Connection.Close() \ No newline at end of file diff --git a/Scripts/Clear-env-Temp-14-days.ps1 b/Scripts/Clear-env-Temp-14-days.ps1 new file mode 100644 index 0000000..44e0b6e --- /dev/null +++ b/Scripts/Clear-env-Temp-14-days.ps1 @@ -0,0 +1,8 @@ +$ls = Get-Item $env:TEMP\*.tmp # or your path and file extension +$date = (Get-Date).AddDays(-14) +foreach ($l in $ls) { + if ($l.LastWriteTime -le $date) { + $l.FullName + Remove-Item $l.FullName -Recurse + } +} \ No newline at end of file diff --git a/Scripts/ConvertFrom-Bit.psm1 b/Scripts/ConvertFrom-Bit.psm1 new file mode 100644 index 0000000..991ab0f --- /dev/null +++ b/Scripts/ConvertFrom-Bit.psm1 @@ -0,0 +1,15 @@ +function ConvertFrom-Bit { + param ( + $bit + ) + [int]$int = 0 + $bits = $bit.ToString().ToCharArray() + $index = ($bits.Count)-1 + foreach ($b in $bits) { + if ($b -notlike 0) { + $int += [math]::Pow(2,$index) + } + $index -= 1 + } + $int +} \ No newline at end of file diff --git a/Scripts/ConvertFrom-UnixTime.psm1 b/Scripts/ConvertFrom-UnixTime.psm1 new file mode 100644 index 0000000..81a4638 --- /dev/null +++ b/Scripts/ConvertFrom-UnixTime.psm1 @@ -0,0 +1,9 @@ +function ConvertFrom-UnixTime { + param ( + $intime + ) + $EpochTime = [DateTime]"1/1/1970" + $TimeZone = Get-TimeZone + $UTCTime = $EpochTime.AddSeconds($intime) + $UTCTime.AddMinutes($TimeZone.BaseUtcOffset.TotalMinutes) +} \ No newline at end of file diff --git a/Scripts/ConvertSecondsTo-TimeSpan.psm1 b/Scripts/ConvertSecondsTo-TimeSpan.psm1 new file mode 100644 index 0000000..e71e2d6 --- /dev/null +++ b/Scripts/ConvertSecondsTo-TimeSpan.psm1 @@ -0,0 +1,7 @@ +function ConvertSecondsTo-TimeSpan { + param ( + $insec + ) + $TimeSpan = [TimeSpan]::fromseconds($insec) + "{0:dd' day 'hh\:mm\:ss}" -f $TimeSpan +} \ No newline at end of file diff --git a/Scripts/ConvertTo-Bit.psm1 b/Scripts/ConvertTo-Bit.psm1 new file mode 100644 index 0000000..a865738 --- /dev/null +++ b/Scripts/ConvertTo-Bit.psm1 @@ -0,0 +1,22 @@ +function ConvertTo-Bit { + param ( + [Int]$int + ) + [array]$bits = @() + $test = $true + while ($test -eq $true) { + if (($int/2).GetType() -match [double]) { + $int = ($int-1)/2 + [array]$bits += 1 + } + elseif (($int/2).GetType() -match [int]) { + $int = $int/2 + [array]$bits += 0 + } + if ($int -eq 0) { + $test = $false + } + } + $bits = $bits[-1..-999] + ([string]($bits)) -replace "\s" +} \ No newline at end of file diff --git a/Scripts/ConvertTo-UnixTime.psm1 b/Scripts/ConvertTo-UnixTime.psm1 new file mode 100644 index 0000000..89a15b1 --- /dev/null +++ b/Scripts/ConvertTo-UnixTime.psm1 @@ -0,0 +1,8 @@ +function ConvertTo-UnixTime { + param ( + $date = $(Get-Date) + ) + $tz = (Get-TimeZone).BaseUtcOffset.TotalMinutes + $sec = (New-TimeSpan -Start (Get-Date "01/01/1970") -End ((Get-Date).AddMinutes(-$tz))).TotalSeconds # -3h UTC + [int]$sec +} \ No newline at end of file diff --git a/Scripts/Firewall-Add-and-Delete-Port-Log.ps1 b/Scripts/Firewall-Add-and-Delete-Port-Log.ps1 new file mode 100644 index 0000000..f5cde12 --- /dev/null +++ b/Scripts/Firewall-Add-and-Delete-Port-Log.ps1 @@ -0,0 +1,19 @@ +$days = 5 +$obj = @() +$fw = Get-WinEvent "Microsoft-Windows-Windows Firewall With Advanced Security/Firewall" +foreach ($temp_fw in $fw) { +if ($temp_fw.id -eq 2097) { # 2004 + $type = "Added Rule" +} +elseif ($temp_fw.id -eq 2006) { + $type = "Deleted Rule" +} +$port = $temp_fw.Properties[7] | select -ExpandProperty value +$name = $temp_fw.Properties[1] | select -ExpandProperty value +$obj += [PSCustomObject]@{ + Time = $temp_fw.TimeCreated; + Type = $type; + Port = $port; + Name = $name} +} +$obj | Where-Object time -gt (Get-Date).AddDays(-$days) \ No newline at end of file diff --git a/Scripts/Firewall-Viewer.ps1 b/Scripts/Firewall-Viewer.ps1 new file mode 100644 index 0000000..91f41fe --- /dev/null +++ b/Scripts/Firewall-Viewer.ps1 @@ -0,0 +1,6 @@ +Get-NetFirewallRule -Enabled True -Direction Inbound | select -Property DisplayName, +@{Name='Protocol';Expression={($_ | Get-NetFirewallPortFilter).Protocol}}, +@{Name='LocalPort';Expression={($_ | Get-NetFirewallPortFilter).LocalPort}}, +@{Name='RemotePort';Expression={($_ | Get-NetFirewallPortFilter).RemotePort}}, +@{Name='RemoteAddress';Expression={($_ | Get-NetFirewallAddressFilter).RemoteAddress}}, +Enabled,Profile \ No newline at end of file diff --git a/Scripts/Get-ADUserFromMySQL.ps1 b/Scripts/Get-ADUserFromMySQL.ps1 new file mode 100644 index 0000000..ab401ee --- /dev/null +++ b/Scripts/Get-ADUserFromMySQL.ps1 @@ -0,0 +1,25 @@ +$ip = "192.168.1.253" +$user = "posh" +$pass = "1qaz!QAZ" +$db = "db_aduser" +Add-Type –Path "$home\Documents\MySQL-Connector-NET\8.0.31-4.8\MySql.Data.dll" +$Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ +ConnectionString = "server=$ip;uid=$user;pwd=$pass;database=$db" +} +$Connection.Open() +$Command = New-Object MySql.Data.MySqlClient.MySqlCommand +$Command.Connection = $Connection +$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter +$MYSQLDataSet = New-Object System.Data.DataSet +$Command.CommandText = "SELECT * FROM table_aduser" +$MYSQLDataAdapter.SelectCommand = $Command +$NumberOfDataSets = $MYSQLDataAdapter.Fill($MYSQLDataSet, "data") +$Collections = New-Object System.Collections.Generic.List[System.Object] +foreach($DataSet in $MYSQLDataSet.tables[0]) { +$Collections.Add([PSCustomObject]@{ +Name = $DataSet.name; +Mail = $DataSet.email +}) +} +$Connection.Close() +$Collections \ No newline at end of file diff --git a/Scripts/Get-CredToXML.ps1 b/Scripts/Get-CredToXML.ps1 new file mode 100644 index 0000000..79f2b3c --- /dev/null +++ b/Scripts/Get-CredToXML.ps1 @@ -0,0 +1,22 @@ +function Get-CredToXML { + param ( + $CredFile = "$home\Documents\cred.xml" + ) + if (Test-Path $CredFile) { + Import-Clixml -path $CredFile + } + elseif (!(Test-Path $CredFile)) { + $Cred = Get-Credential -Message "Enter credential" + if ($Cred -ne $null) { + $Cred | Export-CliXml -Path $CredFile + $Cred + } + else { + return + } + } +} + +# $Cred = Get-CredToXML +# $Login = $Cred.UserName +# $PasswordText = $Cred.GetNetworkCredential().password \ No newline at end of file diff --git a/Scripts/Get-ReadExcel.ps1 b/Scripts/Get-ReadExcel.ps1 new file mode 100644 index 0000000..a7fed57 --- /dev/null +++ b/Scripts/Get-ReadExcel.ps1 @@ -0,0 +1,8 @@ +$path = "$home\Desktop\Services-to-Excel.xlsx" +$Excel = New-Object -ComObject Excel.Application +$Excel.Visible = $false +$ExcelWorkBook = $excel.Workbooks.Open($path) # открыть xlsx-файл +$ExcelWorkBook.Sheets | select Name,Index # отобразить листы +$ExcelWorkSheet = $ExcelWorkBook.Sheets.Item(1) # открыть лист по номеру Index +1..100 | %{$ExcelWorkSheet.Range("A$_").Text} # прочитать значение из столбца А строки c 1 по 100 +$Excel.Quit() \ No newline at end of file diff --git a/Scripts/Get-SQLiteTable.ps1 b/Scripts/Get-SQLiteTable.ps1 new file mode 100644 index 0000000..454fdd7 --- /dev/null +++ b/Scripts/Get-SQLiteTable.ps1 @@ -0,0 +1,4 @@ +$path = "$home\Documents\Get-Service.db" +$TableName = "Service" +Import-Module MySQLite +Invoke-MySQLiteQuery -Path $path -Query "SELECT * FROM $TableName" \ No newline at end of file diff --git a/Scripts/Get-ServiceToExcel.ps1 b/Scripts/Get-ServiceToExcel.ps1 new file mode 100644 index 0000000..246a208 --- /dev/null +++ b/Scripts/Get-ServiceToExcel.ps1 @@ -0,0 +1,49 @@ +$path = "$home\Desktop\Services-to-Excel.xlsx" +$Excel = New-Object -ComObject Excel.Application +$Excel.Visible = $false # отключить открытие GUI +$ExcelWorkBook = $Excel.Workbooks.Add() # Создать книгу +$ExcelWorkSheet = $ExcelWorkBook.Worksheets.Item(1) # Создать лист +$ExcelWorkSheet.Name = "Services" # задать имя листа +$ExcelWorkSheet.Cells.Item(1,1) = "Name service" +# Задать имена столбцов: +$ExcelWorkSheet.Cells.Item(1,2) = "Description" +$ExcelWorkSheet.Cells.Item(1,3) = "Status" +$ExcelWorkSheet.Cells.Item(1,4) = "Startup type" +$ExcelWorkSheet.Rows.Item(1).Font.Bold = $true # выделить жирным шрифтом +$ExcelWorkSheet.Rows.Item(1).Font.size=14 +# Задать ширину колонок: +$ExcelWorkSheet.Columns.Item(1).ColumnWidth=30 +$ExcelWorkSheet.Columns.Item(2).ColumnWidth=80 +$ExcelWorkSheet.Columns.Item(3).ColumnWidth=15 +$ExcelWorkSheet.Columns.Item(4).ColumnWidth=25 +$services = Get-Service +$counter = 2 # задать начальный номер строки для записи +foreach ($service in $services) { +$status = $service.Status +if ($status -eq 1) { +$status_type = "Stopped" +} elseif ($status -eq 4) { +$status_type = "Running" +} +$Start = $service.StartType +if ($Start -eq 1) { +$start_type = "Delayed start" +} elseif ($Start -eq 2) { +$start_type = "Automatic" +} elseif ($Start -eq 3) { +$start_type = "Manually" +} elseif ($Start -eq 4) { +$start_type = "Disabled" +} +$ExcelWorkSheet.Columns.Item(1).Rows.Item($counter) = $service.Name +$ExcelWorkSheet.Columns.Item(2).Rows.Item($counter) = $service.DisplayName +$ExcelWorkSheet.Columns.Item(3).Rows.Item($counter) = $status_type +$ExcelWorkSheet.Columns.Item(4).Rows.Item($counter) = $start_type +if ($status_type -eq "Running") { +$ExcelWorkSheet.Columns.Item(3).Rows.Item($counter).Font.Bold = $true +} +$counter++ # +1 увеличить для счетчика строки Rows +} +$ExcelWorkBook.SaveAs($path) +$ExcelWorkBook.close($true) +$Excel.Quit() \ No newline at end of file diff --git a/Scripts/Get-ServiceToSQLite.ps1 b/Scripts/Get-ServiceToSQLite.ps1 new file mode 100644 index 0000000..ad41af2 --- /dev/null +++ b/Scripts/Get-ServiceToSQLite.ps1 @@ -0,0 +1,16 @@ +$path = "$home\Documents\Get-Service.db" +$Module = Get-Module MySQLite +if ($Module -eq $null) { +Install-Module MySQLite -Repository PSGallery -Scope CurrentUser +} +Import-Module MySQLite +New-MySQLiteDB -Path $path +Invoke-MySQLiteQuery -Path $path -Query "CREATE TABLE Service (Name TEXT NOT NULL, DisplayName TEXT NOT NULL, Status TEXT NOT NULL);" + +$Service = Get-Service | select Name,DisplayName,Status +foreach ($S in $Service) { +$Name = $S.Name +$DName = $S.DisplayName +$Status = $S.Status +Invoke-MySQLiteQuery -Path $path -Query "INSERT INTO Service (Name, DisplayName, Status) VALUES ('$Name', '$DName', '$Status');" +} \ No newline at end of file diff --git a/Scripts/Get-TimeStamp.psm1 b/Scripts/Get-TimeStamp.psm1 new file mode 100644 index 0000000..96210e5 --- /dev/null +++ b/Scripts/Get-TimeStamp.psm1 @@ -0,0 +1,5 @@ +function Get-TImeStamp { + $tz = (Get-TimeZone).BaseUtcOffset.TotalMinutes + $unixtime = (New-TimeSpan -Start (Get-Date "01/01/1970") -End ((Get-Date).AddMinutes(-$tz))).TotalSeconds # -3h UTC + ([string]$unixtime -replace "\..+") + "000000000" +} \ No newline at end of file diff --git a/Scripts/Get-WebCertificate.psm1 b/Scripts/Get-WebCertificate.psm1 new file mode 100644 index 0000000..e65e15d --- /dev/null +++ b/Scripts/Get-WebCertificate.psm1 @@ -0,0 +1,23 @@ +function Get-WebCertificate ($srv) { + $iwr = iwr $srv + $status_code = $iwr.StatusCode + $status = $iwr.BaseResponse.StatusCode + $info = $iwr.BaseResponse.Server + $spm = [System.Net.ServicePointManager]::FindServicePoint($srv) + $date_end = $spm.Certificate.GetExpirationDateString() + $cert_name = ($spm.Certificate.Subject) -replace "CN=" + $cert_owner = ((($spm.Certificate.Issuer) -split ", ") | where {$_ -match "O="}) -replace "O=" + $Collections = New-Object System.Collections.Generic.List[System.Object] + $Collections.Add([PSCustomObject]@{ + Host = $srv; + Server = $info; + Status = $status; + StatusCode = $status_code; + Certificate = $cert_name; + Issued = $cert_owner; + End = $date_end + }) + $Collections +} + +# Get-WebCertificate https://google.com \ No newline at end of file diff --git a/Scripts/Log-Logon.ps1 b/Scripts/Log-Logon.ps1 new file mode 100644 index 0000000..6c45530 --- /dev/null +++ b/Scripts/Log-Logon.ps1 @@ -0,0 +1,13 @@ +$srv = "localhost" +$FilterXPath = '' +$RDPAuths = Get-WinEvent -ComputerName $srv -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" -FilterXPath $FilterXPath +[xml[]]$xml = $RDPAuths | Foreach {$_.ToXml()} +$EventData = Foreach ($event in $xml.Event) { +New-Object PSObject -Property @{ +"Connection Time" = (Get-Date ($event.System.TimeCreated.SystemTime) -Format 'yyyy-MM-dd hh:mm K') +"User Name" = $event.UserData.EventXML.User +"User ID" = $event.UserData.EventXML.SessionID +"User Address" = $event.UserData.EventXML.Address +"Event ID" = $event.System.EventID +}} +$EventData | ft \ No newline at end of file diff --git a/Scripts/Log-Reboot.ps1 b/Scripts/Log-Reboot.ps1 new file mode 100644 index 0000000..ab1c714 --- /dev/null +++ b/Scripts/Log-Reboot.ps1 @@ -0,0 +1,21 @@ +$query = ' + + + + + +' +Get-WinEvent -LogName System -FilterXPath $query \ No newline at end of file diff --git a/Scripts/Network-Utilisation-Monitoring.ps1 b/Scripts/Network-Utilisation-Monitoring.ps1 new file mode 100644 index 0000000..3c8814c --- /dev/null +++ b/Scripts/Network-Utilisation-Monitoring.ps1 @@ -0,0 +1,15 @@ +$WARNING = 25 +$CRITICAL = 50 +$TransferRate = ((Get-Counter "\\huawei-mb-x-pro\сетевой интерфейс(intel[r] wi-fi 6e ax211 160mhz)\всего байт/с" +).countersamples | select -ExpandProperty CookedValue)*8 +$NetworkUtilisation = [math]::round($TransferRate/1000000000*100,2) +if ($NetworkUtilisation -gt $CRITICAL){ +Write-Output "CRITICAL: $($NetworkUtilisation) % Network utilisation, $($TransferRate.ToString('N0')) b/s" +# exit 2 +} +if ($NetworkUtilisation -gt $WARNING){ +Write-Output "WARNING: $($NetworkUtilisation) % Network utilisation, $($TransferRate.ToString('N0')) b/s" +# exit 1 +} +Write-Output "OK: $($NetworkUtilisation) % Network utilisation, $($TransferRate.ToString('N0')) b/s" +# exit 0 \ 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/Scheduled-Task-Creat-Startup.ps1 b/Scripts/Scheduled-Task-Creat-Startup.ps1 new file mode 100644 index 0000000..fb1d4e3 --- /dev/null +++ b/Scripts/Scheduled-Task-Creat-Startup.ps1 @@ -0,0 +1,3 @@ +$Trigger = New-ScheduledTaskTrigger –AtLogon +$Action = New-ScheduledTaskAction -Execute "$home\Documents\DNS-Change-Tray-1.3.exe" +Register-ScheduledTask -TaskName "DNS-Change-Tray-Startup" -Trigger $Trigger -Action $Action -RunLevel Highest –Force \ No newline at end of file diff --git a/Scripts/Scheduled-Task-Import-Startup.ps1 b/Scripts/Scheduled-Task-Import-Startup.ps1 new file mode 100644 index 0000000..2070324 --- /dev/null +++ b/Scripts/Scheduled-Task-Import-Startup.ps1 @@ -0,0 +1,31 @@ +$xml = ' + + + \DNS-Change-Tray-Startup + + + + InteractiveToken + HighestAvailable + + + + false + true + IgnoreNew + + true + false + + + + + + + + %USERPROFILE%\Documents\DNS-Change-Tray-1.3.exe + + + +' +Register-ScheduledTask -Xml ($xml | Out-String) -TaskName "DNS-Change-Tray-Startup" \ No newline at end of file diff --git a/Scripts/Send-WOL.psm1 b/Scripts/Send-WOL.psm1 new file mode 100644 index 0000000..7d15747 --- /dev/null +++ b/Scripts/Send-WOL.psm1 @@ -0,0 +1,19 @@ +function Send-WOL { +param ( +[Parameter(Mandatory = $True)]$Mac, +$IP, +[int]$Port = 9 +) +$Mac = $Mac.replace(":", "-") +if (!$IP) {$IP = [System.Net.IPAddress]::Broadcast} +$SynchronizationChain = [byte[]](,0xFF * 6) +$ByteMac = $Mac.Split("-") | %{[byte]("0x" + $_)} +$Package = $SynchronizationChain + ($ByteMac * 16) +$UdpClient = New-Object System.Net.Sockets.UdpClient +$UdpClient.Connect($IP, $port) +$UdpClient.Send($Package, $Package.Length) +$UdpClient.Close() +} + +# Send-WOL -Mac "D8-BB-C1-70-A3-4E" +# Send-WOL -Mac "D8-BB-C1-70-A3-4E" -IP 192.168.3.100 \ No newline at end of file diff --git a/Scripts/Start-TCPServer.psm1 b/Scripts/Start-TCPServer.psm1 new file mode 100644 index 0000000..8851fd6 --- /dev/null +++ b/Scripts/Start-TCPServer.psm1 @@ -0,0 +1,15 @@ +function Start-TCPServer { + param( + $Port = 5201 + ) + do { + $TcpObject = New-Object System.Net.Sockets.TcpListener($port) + $ReceiveBytes = $TcpObject.Start() + $ReceiveBytes = $TcpObject.AcceptTcpClient() + $TcpObject.Stop() + $ReceiveBytes.Client.RemoteEndPoint | select Address,Port + } while (1) +} + +# Start-TCPServer -Port 5201 +# Test-NetConnection -ComputerName 192.168.3.99 -Port 5201 \ No newline at end of file diff --git a/Scripts/Start-UDPServer.psm1 b/Scripts/Start-UDPServer.psm1 new file mode 100644 index 0000000..adee80c --- /dev/null +++ b/Scripts/Start-UDPServer.psm1 @@ -0,0 +1,21 @@ +function Start-UDPServer { +param( +$Port = 5201 +) +$RemoteComputer = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any, 0) +do { +$UdpObject = New-Object System.Net.Sockets.UdpClient($Port) +$ReceiveBytes = $UdpObject.Receive([ref]$RemoteComputer) +$UdpObject.Close() +$ASCIIEncoding = New-Object System.Text.ASCIIEncoding +[string]$ReturnString = $ASCIIEncoding.GetString($ReceiveBytes) +[PSCustomObject]@{ +LocalDateTime = $(Get-Date -UFormat "%Y-%m-%d %T") +ClientIP = $RemoteComputer.address.ToString() +ClientPort = $RemoteComputer.Port.ToString() +Message = $ReturnString +} +} while (1) +} + +# Start-UDPServer -Port 5201 \ No newline at end of file diff --git a/Scripts/Test-NetUDPConnection.psm1 b/Scripts/Test-NetUDPConnection.psm1 new file mode 100644 index 0000000..d133eb4 --- /dev/null +++ b/Scripts/Test-NetUDPConnection.psm1 @@ -0,0 +1,24 @@ +function Test-NetUDPConnection { +param( +[string]$ComputerName = "127.0.0.1", +[int32]$PortServer = 5201, +[int32]$PortClient = 5211, +$Message +) +begin { +$UdpObject = New-Object system.Net.Sockets.Udpclient($PortClient) +$UdpObject.Connect($ComputerName, $PortServer) +} +process { +$ASCIIEncoding = New-Object System.Text.ASCIIEncoding +if (!$Message) {$Message = Get-Date -UFormat "%Y-%m-%d %T"} +$Bytes = $ASCIIEncoding.GetBytes($Message) +[void]$UdpObject.Send($Bytes, $Bytes.length) +} +end { +$UdpObject.Close() +} +} + +# Test-NetUDPConnection -ComputerName 192.168.3.100 -PortServer 5201 +# Test-NetUDPConnection -ComputerName 192.168.3.100 -PortServer 514 -Message "<30>May 31 00:00:00 HostName multipathd[784]: Test message" \ 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 diff --git a/Scripts/Zabbix-Agent-Deploy.ps1 b/Scripts/Zabbix-Agent-Deploy.ps1 new file mode 100644 index 0000000..55e0c6d --- /dev/null +++ b/Scripts/Zabbix-Agent-Deploy.ps1 @@ -0,0 +1,18 @@ +$url = "https://cdn.zabbix.com/zabbix/binaries/stable/6.4/6.4.5/zabbix_agent2-6.4.5-windows-amd64-static.zip" +$path = "$home\Downloads\zabbix-agent2-6.4.5.zip" +$WebClient = New-Object System.Net.WebClient +$WebClient.DownloadFile($url, $path) +Expand-Archive $path -DestinationPath "C:\zabbix-agent2-6.4.5\" +Remove-Item $path +New-NetFirewallRule -DisplayName "Zabbix-Agent" -Profile Any -Direction Inbound -Action Allow -Protocol TCP -LocalPort 10050,10051 + +$Zabbix_Server = "192.168.3.102" +$conf = "C:\zabbix-agent2-6.4.5\conf\zabbix_agent2.conf" +$cat = cat $conf +$rep = $cat -replace "Server=.+","Server=$Zabbix_Server" +$rep | Select-String Server= +$rep > $conf + +$exe = "C:\zabbix-agent2-6.4.5\bin\zabbix_agent2.exe" +.$exe --config $conf --install +Get-Service *Zabbix*Agent* | Start-Service \ No newline at end of file