Archivi autore: be-digit

Check Cryptocurrencies Price and Amount Coinbase Wallet with Powershell

Powershell script to check cryptocurrencies current prices and wallet amounts of Coinbase account wallet through Coinbase API.
Save the script and before run fill mandatory parameters (api key and secret key generated from Coinbase account) and change base currency to account default currency.

Example:

.\cryptobalance.ps1 -api_key 1234567890abcdef -secret_key 1234567890abcdefghijklmnopqrstuv -basecurrency EUR -cryptos "BTC", "ETH", "LTC", "BCH"
<#
.SYNOPSIS 
Retrieve current price and wallet amount of cryptocurrencies from Coinbase account and coinbase API.
See Coinbase API documentation here: https://developers.coinbase.com/api/v2.
REQUIREMENTS: Powershell and Windows 7 at least.
Simply change api_key, secret_key and basecurrency (to the default currency of your account) before running cryptobalance.ps1.
To create API and SECRET key go to your account preferences in Coinbase and follow the procedure.

.EXAMPLE
Run .\cryptobalance.ps1 -api_key 1234567890abcdef -secret_key 1234567890abcdefghijklmnopqrstuv -basecurrency EUR -cryptos "BTC", "ETH", "LTC", "BCH"

.NOTES 
Name: bitbalance.ps1
Author: Marco Braidotti 
Version History 
    3.0 - 21/02/2018
#>

    Param(
        [Parameter(Mandatory=$true)][String] $api_key = '',  #change with your api key generated on your Coinbase account settings API section
        [Parameter(Mandatory=$true)][String] $secret_key = '', #change with your secret key generated on your Coinbase account settings API section
        [String] $basecurrency = 'EUR', #change with your desired fiat currency
        [String[]] $cryptos = @("BTC", "ETH", "LTC", "BCH") #change with your desired criptos
        )

try {
    
$totalbalance = 0

foreach ($crypto in $cryptos) {

    $urlAPICryptoPrice = 'https://api.coinbase.com/v2/prices/' + $crypto + '-' + $basecurrency + '/spot'
    $CryptoPrice = ((Invoke-WebRequest $urlAPICryptoPrice | ConvertFrom-Json).data).amount

    $accounts = 'https://api.coinbase.com/v2/accounts'
    $time = 'https://api.coinbase.com/v2/time'
    $epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch

    $method = 'GET'
    $requestpath = '/v2/accounts'

    $sign = $epochtime + $method + $requestpath
    $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key)
    $computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign))

    $signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower()

    $header = @{
        "CB-ACCESS-SIGN"      = $signature
        "CB-ACCESS-TIMESTAMP" = $epochtime
        "CB-ACCESS-KEY"       = $api_key
    }

    $result = Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json"
    $wallets = $result.Content | ConvertFrom-Json


    foreach ($wallet in $wallets.data.balance) {
        if ($wallet.currency -eq $crypto) {
            $total = [math]::Round([Double]$wallet.amount * $CryptoPrice, 2)
        }
    }

    $totalbalance += $total
    Write-Host $crypto "Current Price:" $CryptoPrice $basecurrency "- Wallet Amount:" $total $basecurrency -ForegroundColor Yellow

}
$totalfiat = (((Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json").Content | ConvertFrom-Json).data | Where-Object {$_.type -match 'fiat'  } | Select-Object balance).balance.amount
write-host "Fiat Total Amount:" $totalfiat $basecurrency -ForegroundColor Yellow

$amount = $totalbalance + $totalfiat
write-host "Wallet Total Amount:" $amount $basecurrency -ForegroundColor Green

}
catch [Exception] {
    Write-Host $_.Exception.Message
  exit
}

 

Bitcoin, Ethereum, Litecoin Coinbase Prices and Wallet Amounts with Powershell

<#
.SYNOPSIS 
Retrieve current price and wallet amount of BTC, ETH, LTC cryptocurrencies
from Coinbase account and coinbase API.
See Coinbase API documentation here: https://developers.coinbase.com/api/v2.
REQUIREMENTS: Powershell and Windows 7 at least.
Simply change api_key, secret_key and basecurrency before running bitbalance.ps1.
To create API and SECRET key go to your account preferences in Coinbase
and follow the prucedure.

.EXAMPLE
Run bitbalance.ps1

.NOTES 
Name: bitbalance.ps1
Author: Marco Braidotti 
Version History 
    1.0 - 10/12/2017 
#>

$api_key = 'abcdefghi123456' #change with your api key generated on your Coinbase account settings API section
$secret_key = 'abcdefghijklmno123456789101234' #change with your secret key generated from on your Coinbase account settings API section
$basecurrency = 'EUR' #change with your desired fiat currency

#do not change anything below!!!!
$urlBTCprice = 'https://api.coinbase.com/v2/prices/BTC-' + $basecurrency + '/spot'
$urlETHprice = 'https://api.coinbase.com/v2/prices/ETH-' + $basecurrency + '/spot'
$urlLTCprice = 'https://api.coinbase.com/v2/prices/LTC-' + $basecurrency + '/spot'
$BTCprice = ((Invoke-WebRequest $urlBTCprice | ConvertFrom-Json).data).amount
$ETHprice = ((Invoke-WebRequest $urlETHprice | ConvertFrom-Json).data).amount
$LTCprice = ((Invoke-WebRequest $urlLTCprice | ConvertFrom-Json).data).amount

$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch

$method = 'GET'
$requestpath = '/v2/accounts'

$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key)
$computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign))

$signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower()

$header = @{
    "CB-ACCESS-SIGN"      = $signature
    "CB-ACCESS-TIMESTAMP" = $epochtime
    "CB-ACCESS-KEY"       = $api_key
}

$result = Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json"
$accounts = $result.Content | ConvertFrom-Json

foreach ($wallet in $accounts.data.balance) {   
    switch ($wallet.currency) {   
        $basecurrency {$totalfiat = [Double]$wallet.amount} 
        BTC {$totalBTC = [math]::Round([Double]$wallet.amount * $BTCprice, 2)} 
        ETH {$totalETH = [math]::Round([Double]$wallet.amount * $ETHprice, 2)} 
        LTC {$totalLTC = [math]::Round([Double]$wallet.amount * $LTCprice, 2)} 
        default {"N.D."}
    }
}

$totalamount = $totalfiat + $totalBTC + $totalETH + $totalLTC

Write-Host "Price BTC/$basecurrency : $BTCprice" -background red -ForegroundColor black
Write-Host "Price ETH/$basecurrency : $ETHprice" -background red -ForegroundColor black
Write-Host "Price LTC/$basecurrency : $LTCprice" -background red -ForegroundColor black
Write-Host "Balance $basecurrency : $totalfiat $basecurrency" -background yellow -ForegroundColor black
Write-Host "Balance BTC : $totalBTC $basecurrency" -background yellow -ForegroundColor black
Write-Host "Balance ETH : $totalETH $basecurrency" -background yellow -ForegroundColor black
Write-Host "Balance LTC : $totalLTC $basecurrency" -background yellow -ForegroundColor black
Write-Host "Total Balance : $totalamount $basecurrency" -ForegroundColor green

 

Veeam Backup Jobs Failed – VBScript Nagios Check

' Nagios Plugn for reading Veeam Backup and Replication's log
' It is intended to use with NSClient++


Dim rad,txt,dag,alert,status

Set cnn = CreateObject("ADODB.Connection")
Set Rs = CreateObject("ADODB.Recordset")

cnn.ConnectionString = "driver={SQL Server};server=localhost\VEEAMSQL2012;Trusted_Connection=Yes;database=VeeamBackup"
cnn.Open
rs.ActiveConnection = cnn
exitcode = 0
txt=""
allert()
rs.close
If txt > "" Then
  txt = "BACKUP VIRTUAL MACHINE IN ERRORE: \n" & txt & " | "
else
  txt = "OK"
  exitcode=0
End If

wscript.echo(txt)
wscript.quit exitcode

Function allert()
  Const ForReading = 1, ForWriting = 2, ForAppending = 8
  Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
  'strsql = "SELECT name, repo_name,progress,result,target_host_name   FROM [VeeamBackup].[dbo].[ReportJobsView]   where latest_result=2"
  strsql = "SELECT b.object_name as object_name, a.job_name as job_name, a.creation_time as creation_time, a.end_time as end_time, a.total_size as total_size, a.stored_size as stored_size FROM dbo.ReportSessionView a inner join dbo.ReportSessionInfoView b on a.id = session_id where a.result = '2' and a.id is not null and cast(a.creation_time as date) > dateadd(day,-1, cast(getdate() as date)) order by 2 desc"
  rs.Open strsql , cnn,3,3
  Do While Not rs.EOF 
  
                rad = rs("object_name") & " Job: " & rs("job_name") & " Data Inizio: " & rs("creation_time") & " Data Fine: " & rs("end_time") & " Dimensioni Totali: " & rs("total_size") & " Dimensioni Compresse: " & rs("stored_size") & "\n "
        
            Set fso = CreateObject("Scripting.FileSystemObject")
            txt = txt + rad 
        
        rs.MoveNext
    Loop
    exitcode = 2
    Exit Function
End Function

modified from: https://exchange.nagios.org/directory/Plugins/Backup-and-Recovery/Check-Veeam-Backup-Jobs/details

Last Succesful Backup Bareos – Nagios Check

example:

./check_bareos_last_backup.pl -c 3 -w 6 -j CopyToTape -O 192.168.59.211 -d bareos -u bareos_webui -p citestpass

source:

#!/usr/bin/perl -w

# Author: Marco Braidotti
# Quite a lot copied from check_bacula.pl which is GPL.

## examples: 

##    This program is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    This program is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with check_bareos_last_backup.pl.  If not, see <http://www.gnu.org/licenses/>.


use strict;
use POSIX;
use File::Basename;
use DBI;
use DBD::Pg;
use Switch;
use Getopt::Long;
use vars qw(
       $opt_help
           $opt_job
           $opt_critical
           $opt_warning
           $opt_level
           $opt_usage
           $opt_version
           $out
           $sql
           $date_start
           $date_stop
           $state
           $count
           );
           
sub print_help();
sub print_usage();
sub get_now();
sub get_date;

my $sql;
my $sq11;
my $sq12;
my $sql3;
my $sql4;
my $sqlresult;
my $days;
my $end;
my $client;
my $test;
my $clientresult;
my $level;
my $progname = basename($0);
my $progVers = "0.9";
my $sqlHost;
my $sqlDB;
my $sqlUsername;
my $sqlPassword;


my %ERRORS = (  'UNKNOWN'       =>      '3',
                'OK'            =>      '0',
                'WARNING'       =>      '1',
                'CRITICAL'      =>      '2');
                
Getopt::Long::Configure('bundling');
GetOptions
        (
        "c=s"   =>      \$opt_critical, "critical=s"    =>      \$opt_critical,
        "w=s"   =>      \$opt_warning,  "warning=s"     =>      \$opt_warning,
        ##"L=s"   =>      \$opt_level,    "level=s"       =>      \$opt_level,
        "j=s"   =>      \$opt_job,      "job=s"         =>      \$opt_job,
        "h"     =>      \$opt_help,     "help"          =>      \$opt_help,
                                        "usage"         =>      \$opt_usage,
    "O=s"     =>      \$sqlHost,  "hostname"       =>      \$sqlHost,
    "d=s"     =>      \$sqlDB,  "database"       =>      \$sqlDB,
    "u=s"     =>      \$sqlUsername,  "username"       =>      \$sqlUsername,
    "p=s"     =>      \$sqlPassword,  "password"       =>      \$sqlPassword,
        "V"     =>      \$opt_version,  "version"       =>      \$opt_version
        ) || die "Try '$progname --help' for more information.\n";

    
sub print_help() {
 print "\n";
 print "If Bacula holds its MySQL-data behind password, you have to manually enter the password into the script as variable \$sqlPassword.\n";
 print "And be sure to prevent everybody from reading it!\n";
 print "\n";
 print "Options:\n";
 ##print "L       check backup level F for full, D for differential, I for incremential\n";
 print "c       max days since successful job for not returning critical\n";
 print "w       max days since successful job for not returning warning\n";
 print "j       name of the job to NOT check (case-sensitive)\n";
 print "h       show this help\n";
 print "V       print script version\n";
 print "O       host postgresql\n";
 print "d       database postgresql\n";
 print "u       database user postgresql\n";
 print "p       database password postgresql\n";
}

sub print_usage() {
 print "Usage: $progname -c <critical> -w <warning> -j <job-name> [ -h ] [ -V ]\n";
}

if ($opt_help) {
 print_usage();
 print_help();
 exit $ERRORS{'UNKNOWN'};
}

if ($opt_usage) {
 print_usage();
 exit $ERRORS{'UNKNOWN'};
}

if ($opt_version) {
 print "$progname $progVers\n";
 exit $ERRORS{'UNKNOWN'};
}

##switch ($opt_level) {

##		case "F"	{ $level = "full";}
##		case "D"	{ $level = "differential";}
##		case "I"	{ $level = "incremental";}
##		else		{ print_usage(); exit $ERRORS{'UNKNOWN'}; }
##}

if ($opt_job && $opt_warning && $opt_critical) {
 my $dsn = "DBI:Pg:dbname=$sqlDB;host=$sqlHost";
 my $dbh = DBI->connect( $dsn,$sqlUsername,$sqlPassword ) or die "Error connecting to: '$dsn': $DBI::errstr\n";

##$sql = "SELECT  Datediff(NOW(), EndTime) as \'days\', EndTime AS \'end\' FROM `Job` WHERE Name = \"$opt_job\" and JobStatus='T' AND Level = \"$opt_level\" ORDER BY Datediff(NOW(), EndTime) ASC LIMIT 1;";

my $sql1 = "select DATE_PART('day', now() - EndTime) as days, t.endtime as end, t.name as client, JobStatus from job t right join ( select name, max(endtime) as maxdate from job where jobstatus = 'T' group by name ) tm on t.name = tm.name and t.endtime = tm.maxdate where t.name <> 'RestoreFiles' and t.name not in ('";
my $sql2 = "') order by days";

$sql = join "", $sql1, $opt_job, $sql2;

my $sth = $dbh->prepare($sql) or die "Error preparing statement",$dbh->errstr;
$sth->execute;

my @row;
while ( @row = $sth->fetchrow_array()) {
($days,$end,$client) = @row;
}
$sth->finish;
$dbh->disconnect();

if (! $end) { print "Bareos Backup UNKNOWN: Successful job for $opt_job - $days - $end not found.\n"; exit $ERRORS{'UNKNOWN'}; }

$state = 'OK';
if ($days > $opt_warning) { $state='WARNING' }
if ($days > $opt_critical) { $state='CRITICAL' }
if ($days < 0) { $state='UNKNOWN';} ;


 my $dsnresult = "DBI:Pg:dbname=$sqlDB;host=$sqlHost";
 my $dbhresult = DBI->connect( $dsnresult,$sqlUsername,$sqlPassword ) or die "Error connecting to: '$dsn': $DBI::errstr\n";


my $sql3 = "select '1' as test, array_to_string(array_agg(t.name),', ') as clientresult from job t right join ( select name, max(endtime) as maxdate from job where jobstatus = 'T' group by name ) tm on t.name = tm.name and t.endtime = tm.maxdate where DATE_PART('day', now() - EndTime) > 30 and t.name <> 'RestoreFiles' and t.name not in ('";
my $sql4 = "') group by test";

$sqlresult = join "", $sql3, $opt_job, $sql4;

my $sthresult = $dbhresult->prepare($sqlresult) or die "Error preparing statement",$dbhresult->errstr;
$sthresult->execute;

my @rowresult;
while ( @rowresult = $sthresult->fetchrow_array()) {
($test,$clientresult) = @rowresult;
}
$sthresult->finish;
$dbhresult->disconnect();


print "Backup Clients $state. Trascorsi almeno 30 giorni dall'ultimo backup effettuato con successo dei clients: $clientresult\n";
exit $ERRORS{$state};

}
else
{
print_help();
exit $ERRORS{'UNKNOWN'};
}

 

ntopng – Network Traffic Analysis

/bin/echo -e "deb http://www.nmon.net/apt-stable/14.04/ x64/\ndeb
http://www.nmon.net/apt-stable/14.04/ all/" > /etc/apt/sources.list.d/ntop.list
wget -qO - http://www.nmon.net/apt-stable/ntop.key | sudo apt-key add -
apt-get update
apt-get install nprobe ntopng ntopng-data n2disk nbox libsnmp-base snmp-mibs-downloader

 

nprobe --zmq tcp://127.0.0.1:5557 -i none -n none --collector-port 2101 &
nprobe --zmq tcp://127.0.0.1:5558 -i none -n none --collector-port 2103 &

 

ntopng.conf:

-n=1
-w=3001
-W=0
-g=-1
-m="192.168.59.0/24,192.168.190.0/24,192.168.1.0/24"
-S=1
-d=/storage/ntopng/var/tmp/ntopng
-G=/var/tmp/ntopng.pid
-i=tcp://127.0.0.1:5558
-i=tcp://127.0.0.1:5557

or single interface:

ntopng -e --local-networks "192.168.1.0/24,192,168.59.0/24,192.168.190.0/24" -i tcp://127.0.0.1:5557 -G=/run/ntopng.pid --community

 

Sorgente: How to monitor what’s happening in your network – VapourApps

 

Performance Analysis SQL Server

sp_whoisactive: https://www.brentozar.com/responder/log-sp_whoisactive-to-a-table/

CPU Real-Time SQL Utilization:

EXEC dbo.sp_WhoIsActive
@get_transaction_info=0,
@output_column_list ='[session_id][start_time]
                  [cpu][status][context_switches][wait_info][program_name]
                 [database_name][sql_text][host_name][open_tran_count]', 
@sort_order='[CPU]DESC'

/*delta*/
EXEC dbo.sp_WhoIsActive
@delta_interval=5, @get_task_info = 2,
@output_column_list ='[session_id][start_time][context switches]
                  [CPU_delta][reads_delta][writes_delta][tempdb_writes_delta]
                  [tempdb_reads_delta][tempdb_current_delta]
                  [database_name][host_name][login_name]', 
@sort_order='[CPU_delta]DESC'

Query History Log:

SELECT --TOP 1000 
[dd hh:mm:ss.mss]
      ,[session_id]
      ,[sql_text]
      ,[sql_command]
      ,[login_name]
      ,[wait_info]
      ,[CPU]
      ,[tempdb_allocations]
      ,[tempdb_current]
      ,[blocking_session_id]
      ,[blocked_session_count]
      ,[reads]
      ,[writes]
      ,[physical_reads]
      ,[used_memory]
      ,[status]
      ,[open_tran_count]
      ,[percent_complete]
      ,[host_name]
      ,[database_name]
      ,[program_name]
      ,[start_time]
      ,[login_time]
      ,[request_id]
      ,[collection_time]
  FROM [dbwhoisactive].[dbo].[tablelogwhoisactive]
    ORDER BY [collection_time] DESC

Simplified CPU Real-Time SQL Utilization:

select
    r.session_id,
    r.cpu_time,
    ((r.total_elapsed_time/1000.0)/60.0) as MinutesRunning,
    s.login_name,
    c.client_net_address,
    s.program_name
    ,sjj.name as Job
    ,sj.step_name as 'Step Job'
    ,st.text as query
from sys.dm_exec_requests r
inner join sys.dm_exec_sessions s
on r.session_id = s.session_id
left join sys.dm_exec_connections c
on r.session_id = c.session_id
outer apply sys.dm_exec_sql_text(r.sql_handle) st
left JOIN msdb.dbo.sysjobsteps sj
  ON SUBSTRING(s.[program_name],30,34) =
  CONVERT(VARCHAR(34), CONVERT(VARBINARY(32), sj.job_id), 1)
left JOIN msdb.dbo.sysjobs sjj
ON sj.job_id = sjj.job_id
where s.login_name <> 'sa' 
and r.session_id <> @@spid
order by r.cpu_time desc, ((r.total_elapsed_time/1000.0)/60.0) desc

Blocking Sessions SQL:

SELECT  DISTINCT    
[Blocked By]    = ISNULL(CONVERT (varchar, w.blocking_session_id), ''),
[Host Name Block]     = ISNULL(ws.host_name, N''),        
[Login Block]         = ws.login_name,       
[Database Block]      = ISNULL(db_name(wp.dbid), N''),     
[Application Block]   = ISNULL(ws.program_name, N''),
[Session ID]    = s.session_id,
[Host Name]     = ISNULL(s.host_name, N''),        
[Login]         = s.login_name,       
[Database]      = ISNULL(db_name(p.dbid), N''),     
[Application]   = ISNULL(s.program_name, N''),
[SQL block] = ISNULL(wst.text,''),
[SQL] = ISNULL(st.text,'')
FROM sys.dm_exec_sessions s
LEFT OUTER JOIN sys.dm_exec_connections c ON (s.session_id = c.session_id) 
LEFT OUTER JOIN sys.dm_exec_requests r ON (s.session_id = r.session_id) 
LEFT OUTER JOIN sys.dm_os_tasks t ON (r.session_id = t.session_id
AND r.request_id = t.request_id) 
LEFT OUTER JOIN   (     
SELECT *, ROW_NUMBER() OVER (PARTITION BY waiting_task_address ORDER BY wait_duration_ms DESC) AS row_num     
FROM sys.dm_os_waiting_tasks   ) w ON (t.task_address = w.waiting_task_address) AND w.row_num = 1   
LEFT OUTER JOIN sys.sysprocesses p ON (s.session_id = p.spid)
LEFT OUTER JOIN sys.dm_exec_sessions ws ON w.session_id=ws.session_id
LEFT OUTER JOIN sys.sysprocesses wp ON (ws.session_id = wp.spid)
LEFT OUTER JOIN sys.dm_exec_requests wr ON (ws.session_id = wr.session_id)
outer apply sys.dm_exec_sql_text(r.sql_handle) st
outer apply sys.dm_exec_sql_text(wr.sql_handle) wst
WHERE NOT w.blocking_session_id IS NULL
ORDER BY 1  desc;