Archivi categoria: Generale

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

Retrieve current price and wallet amount of BTC, ETH, LTC cryptocurrencies
from Coinbase account and coinbase API.
See Coinbase API documentation here:
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.

Run bitbalance.ps1

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 = '' + $basecurrency + '/spot'
$urlETHprice = '' + $basecurrency + '/spot'
$urlLTCprice = '' + $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 = ''
$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 $ {   
    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"
rs.ActiveConnection = cnn
exitcode = 0
If txt > "" Then
  txt = "BACKUP VIRTUAL MACHINE IN ERRORE: \n" & txt & " | "
  txt = "OK"
End If

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 = session_id where a.result = '2' and 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 
    exitcode = 2
    Exit Function
End Function

modified from:

Last Succesful Backup Bareos – Nagios Check


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


#!/usr/bin/perl -w

# Author: Marco Braidotti
# Quite a lot copied from 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
##    GNU General Public License for more details.
##    You should have received a copy of the GNU General Public License
##    along with  If not, see <>.

use strict;
use POSIX;
use File::Basename;
use DBI;
use DBD::Pg;
use Switch;
use Getopt::Long;
use vars qw(
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');
        "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) {

if ($opt_usage) {

if ($opt_version) {
 print "$progname $progVers\n";

##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, as client, JobStatus from job t right join ( select name, max(endtime) as maxdate from job where jobstatus = 'T' group by name ) tm on = and t.endtime = tm.maxdate where <> 'RestoreFiles' and 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;

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

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(,', ') as clientresult from job t right join ( select name, max(endtime) as maxdate from job where jobstatus = 'T' group by name ) tm on = and t.endtime = tm.maxdate where DATE_PART('day', now() - EndTime) > 30 and <> 'RestoreFiles' and 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;

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

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



ntopng – Network Traffic Analysis

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


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




or single interface:

ntopng -e --local-networks ",192,168.59.0/24," -i tcp:// -G=/run/ --community


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


Performance Analysis SQL Server


CPU Real-Time SQL Utilization:

EXEC dbo.sp_WhoIsActive
@output_column_list ='[session_id][start_time]

EXEC dbo.sp_WhoIsActive
@delta_interval=5, @get_task_info = 2,
@output_column_list ='[session_id][start_time][context switches]

Query History Log:

SELECT --TOP 1000 
[dd hh:mm:ss.mss]
  FROM [dbwhoisactive].[dbo].[tablelogwhoisactive]
    ORDER BY [collection_time] DESC

Simplified CPU Real-Time SQL Utilization:

    ((r.total_elapsed_time/1000.0)/60.0) as MinutesRunning,
    , 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:

[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) 
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;


SQL User Databases Relocation

To move a data or log file as part of a planned relocation, follow these steps:

  1. Run the following statement.
  2. Move the file or files to the new location.
  3. For each file moved, run the following statement.
    ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name, FILENAME = 'new_path\os_file_name' );
  4. Run the following statement.
    ALTER DATABASE database_name SET ONLINE;sq
  5. Verify the file change by running the following query.
    SELECT name, physical_name AS CurrentLocation, state_desc
    FROM sys.master_files
    WHERE database_id = DB_ID(N'<database_name>');