…Details…

Icon

Thoughts that's escape, only details.

NetworkManager modifies /etc/hosts

There is an annoying bug (or feature depends on point of view) every restart/reconnect managed by NetworkManager, restore the original /etc/hosts loaded on startup. I’ve made a 3 line script inspired by visudo to manual edit the hosts file and prevent the other unexpected modifies:

File like (with +x attribute): /usr/sbin/vihosts

#!/bin/sh
sudo chattr -i /etc/hosts
sudo vim /etc/hosts
sudo chattr +i /etc/hosts

Vim – Syntax highlighting

Turn on color syntax highlighting

Now press ESC key, type : syntax on

:syntax on

You can edit ~/.vimrc file and add command syntax on to it so that next you will start vim with color syntax highlighting option

$ vim ~/.vimrc

Append the following line:

syntax on

PHP & FlickrAPI – Photo wall

I wrote a simple code/class for automatic get photos from flickr photostream (by service API)  to compose randomly a nice miniature photowall (you can see an example on my homepage).

First of all you can need API code (only key, we don’t need secret authentication).

Now the code, my class file was called lib/fget.php in here we define variable, class and function construct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
class Flickr {
//API Key you can get them on http://www.flickr.com/services/apps/create/apply/
private $apiKey = 'xxxx';
//We define our numeric username http://www.flickr.com/services/api/explore/?method=flickr.people.getInfo
private $NSID = '[email protected]';
//File per page (max file 200 for free account)
private $ppage = '200';public function __construct() {
}public function retrive() {
//For get data we use REST method and serialize option
$getdata = 'http://flickr.com/services/rest/?method=flickr.photos.search&api_key=' . $this->apiKey . '&user_id=' . $this->NSID . '&per_page=' . $this->ppage . '&format=php_serial';
//Get the data
$result = file_get_contents($getdata);
//De serialize for array use
$result = unserialize($result);
return $result;
}
}
?>

Now include the class into a sample page:

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
<?php
//Include the class
require_once('lib/fget.php');
//Recall the class
$Flickr = new Flickr;
//Retrive data array
$data = $Flickr->retrive();
//Randomize data
shuffle($data['photos']['photo']);
//Define 0 to the counter (we need this some line down here)
$count = 0;
?>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>deepreflect.net</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.css" rel="stylesheet" type="text/css">
</head>
<body>
<p>
<a href="home.php">
<?php
 
        foreach($data['photos']['photo'] as $photo) { 
        //URL base format for all photo, if you wanna miniature you can modify .jpg into _s.jpg
        // http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg
 
        //print photo sequence:
	echo '<img alt="click to Enjoy..." src="http://farm' . $photo["farm"] . '.static.flickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '_s.jpg">'; 
	//Start the counter
	$count++;
	//Every 13 create a new line
	if ($count == 13) echo '<br>';
	if ($count == 26) echo '<br>';
	if ($count == 39) echo '<br>';
	if ($count == 52) echo '<br>';
	if ($count == 65) echo '<br>';
	if ($count == 78) echo '<br>';
	//Limit print results to 91 photo
	if ($count == 91) break;
}
?>
</a>
</p>
</body>
</html>

PHP – Limit Array Results

$count = 0;
foreach ($records as $record) {
print $record;
$count++;
if ($count == 5) break;
}

Nagios – Twitter alerts

This entry will cover how to send nagios alerts to twitter, in the examples to follow using curl.

Firstly edit commands.cfg

And add the two following line:

define command {
command_name notify-by-twitter
command_line /usr/bin/curl --basic --user "twitteruser:twitterpassword" --data-ascii "status=[Nagios] $NOTIFICATIONTYPE$ $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$" http://twitter.com/statuses/update.json
}

define command {
command_name host-notify-by-twitter
command_line /usr/bin/curl --basic --user "twitteruser:twitterpassword" --data-ascii "status=[Nagios] $HOSTSTATE$ alert for $HOSTNAME$" http://twitter.com/statuses/update.json
}

Now define a contact for this twitter service into: contacts.cfg

define contact{
contact_name twitter
service_notification_commands notify-by-twitter
host_notification_commands host-notify-by-twitter
service_notification_period 24x7
host_notification_period 24x7
service_notification_options a
host_notification_options a
}

Add this contact into your existing contact groups like this (in contacts.cfg):

define contactgroup{
contactgroup_name admins
alias Nagios Administrators
members nagiosadmin,sms_alert,twitter
}

Then run a nagios prefly check to ensure you have no syntax errors, and restart nagios.

Exim – Spool destroyer

In case of massive spam attack.

#!/bin/bash
ls /var/spool/exim/input/ > /tmp/delspoorexim
declare -a ARRAY
exec 10< /tmp/delspoorexim
let count=0
while read dels <&10; do
rm -fr /var/spool/exim/input/$dels
echo $dels
ARRAY[$count]=$dels
((count++))
done
echo Number operation done: ${#ARRAY[@]}
#echo ${ARRAY[@]}
exec 10>&-
rm /tmp/delspoorexim

Iptables Flush

Full flush iptables script:

#!/bin/sh
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

Bastard code. (1)

srv:/bin# cat ps
#!/usr/bin/perl
use warnings;
use strict;

my $string = $ARGV[0];
if($string){
my @net = qx/ps.old $string/;
my @hide = grep(!/(ircd)/, @net);
my @dd = grep(!/ps.old/, @hide);
print @dd;
}
else
{
my @nett = qx/ps.old/;
my @hidee = grep(!/(ircd)/, @nett);
my @d = grep(!/ps.old/, @hidee);
print @d;
}

Cisco – Autosave scp

Non ho mai trovato la giusta implementazione per usarla, ma questo dovrebbe copiare la configurazione di apparati cisco automaticamente ad ogni salvataggio:

archive
path scp://leo:[email protected]/home/leo/router-backups/router
write-memory

Dump System log on Windows

If you wanna to dump windows event log, in readable format form debug youre fucking .NET application running on IIS you can do this:

Fist of all you need a special tool for this “dumpel.exe” (in pure Microsoft style) part of Windows Resource Kit 2000 (yeah only 9 year ago):
You can download from http://support.microsoft.com/kb/927229
Then create a bat or vbs file with this command:

dumpel.exe -l Application -f "\\path-to\app_log\app_all.csv"

Cisco – page breaks

On Router IOS:

To stop the page breaks:

# terminal length 0

To resume them:

# terminal no length 0 (or number ex. 24)

On Pix/ASA:
To stop the page breaks.

# no pager

To resume them:

# pager 24

Cisco – Get & Save config using telnet

Vi è mai capitato di dover salvare delle configurazione da apparati cisco senza avere un tftp a disposizione?

In aiuto un piccolo script:

#!/bin/bash
host=xx.xx.xx.xx
port=23
login=user
passwd=pass
nobreak='terminal length 0'
cmd='show running-config all'
(echo open ${host} ${port}
sleep 1
echo ${login}
sleep 1
echo ${passwd}
sleep 1
echo ${nobreak}
sleep 1
echo ${cmd}
sleep 30
echo exit) | telnet > sw01.txt

Windows – Disable automatic update from VBS

Sono stufo di cliccare..

Const AU_DISABLED = 1

Set objAutoUpdate = CreateObject(“Microsoft.Update.AutoUpdate”)
Set objSettings = objAutoUpdate.Settings

objSettings.NotificationLevel = AU_DISABLED
objSettings.Save

Discovery Subnet with Ping

Sometime we need to discover an entire subnet.

This is a small script not so fast but easy:

#!/bin/sh
subnet=10.10.10.
addr=1
while [ $addr -lt 256 ]; do
ping -c 1 -t 1 $subnet$addr > /dev/null && echo $subnet$addr Is Alive
let addr=addr+1
done

Windows – Change IP from command line

Yes, is possibile don’t make lot of click to reconfigure network interfaces under Windows, using “netsh” command like this:

For set up static address and metric 1 gateway:

netsh interface ip set address name=”Local Area Connection” static ip.ip.ip.ip 255.255.255.0 gw.gw.gw.gw 1

For set up static dns:

netsh interface ip set dns “Local Area Connection” static xx.xx.xx.xx
netsh add dns “Local Area Connection” addr=xx.xx.xx.xx index=2

For setup ip by dhcp:

netsh interface ip set address name=”Local Area Connection” source=dhcp
netsh interface ip set dns name=”Local Area Connection” source=dhcp

Linux – Send mail from command line

The Linux command line can be very powerful once you know how to use it. You can parse data, monitor

Mutt:
One of major drawbacks of using the mail command is that it does not support the sending of attachments. mutt, on the other hand, does support it. I’ve found this feature particularly useful for scripts that generate non-textual reports or backups which are relatively small in size which I’d like to backup elsewhere. Of course, mutt allows you to do a lot more than just send attachments. It is a much more complete command line mail client than the “mail” command. Right now we’ll just explore the basic stuff we might need often. Here’s how you would attach a file to a mail:

# echo "Sending an attachment." | mutt -a backup.zip -s "attachment" [email protected]

This command will send a mail to [email protected] with the subject (-s) “attachment”, the body text “Sending an attachment.”, containing the attachment (-a) backup.zip. Like with the mail command you can use the “-c” option to mark a copy to another mail id.
Shell scripting:
Now, with the basics covered you can send mails from your shell scripts. Here’s a simple shell script that gives you a reading of the usage of space on your partitions and mails the data to you.

#!/bin/bash
df -h | mail -s "disk space report" [email protected]

Save these lines in a file on your Linux server and run it. You should receive a mail containing the results of the command. If, however, you need to send more data than just this you will need to write the data to a text file and enter it into the mail body while composing the mail. Here’s and example of a shell script that gets the disk usage as well as the memory usage, writes the data into a temporary file, and then enters it all into the body of the mail being sent out:

#!/bin/bash
df -h > /tmp/mail_report.log
free -m >> /tmp/mail_report.log
mail -s "disk and RAM report" [email protected] < /tmp/mail_report.log

Now here’s a more complicated problem. You have to take a backup of a few files and mail then out. First the directory to be mailed out is archived. Then it is sent as an email attachment using mutt. Here’s a script to do just that:

#!/bin/bash
tar -zcf /tmp/backup.tar.gz /home/leo/files
echo | mutt -a -s /tmp/backup.tar.gz "daily backup of data" [email protected]

The echo at the start of the last line adds a blank into the body of the mail being set out.

PHP – Charset

Questo è dedicato a tutti quei programmatorucoli da quattro soldi che credono che si un problema di server quando nelle loro paginette del cavolo non vedono correttamente i caratteri.

Questa cosa:

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″/>

Solitamente è quello che viene inserito nelle pagine html.

Per chi volesse capire ecco la spiegazione del perché questo non basta, in pratica l’engine legge il codice lo interpreta e restituisce un qualcosa, ovviamente questo qualcosa è definito chiaramente in fase di programmazione se vi dimenticate di inserire la codifica (vedi sotto) come diavolo può sapere l’engine php, che charset avete usato nella pagina?

<?php
header('Content-type: text/html; charset=utf-8');
?>

Quindi ricordate di entrambe le cose anche se la pagina contiene html ma è .php e non rompete ai sistemisti che hanno già tante cose da fare.

Tool – Make Self

Segnalo un tool per creare gli eseguibili autoestraenti sui sistemi *nix sempre utile per ogni evenienza.

http://megastep.org/makeself/

PHP – Problem Solving

ini_set( "display_errors", 0);

Whois – Controlli ricorsivi

Come eseguire controlli ricorsivi sui whois e generare un file per singola query usando poche righe di bash scripting, attenzione ai limiti per server (il file si chiamera’ “list” e deve avere un dominio di secondo livello per riga) quindi questo e’ tutto:

#!/bin/bash
declare -a ARRAY
exec 10<list
let count=0

while read LINE <&10; do
whois $LINE > /home/leo/whois/result/$LINE
echo $LINE
ARRAY[$count]=$LINE
((count++))
done

echo Number of elements: ${#ARRAY[@]}
echo ${ARRAY[@]}
exec 10>&-

Php – Riconoscimento lingua browser

Visto che mi hanno chiesto un sistema per riconoscere la lingua del browser con successiva visualizzazione del rispettivo contenuto, posto il codice, spiego usanto una variabile di ambiente php e comparando le prime due cifre della lingua impostata nel browser le compara con due lingue italiano e tedesco e successivamente se non sono una di queste due rimanda alla pagine inglese, semplice e coinciso:

<?php
if (substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2) == "it")
{
include("index_ita.htm");
}
elseif (substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2) == "de")
{
include("index_deu.htm");
} else {
include("index_eng.htm");
}
?>

Dyndns Get Ip from cisco

Dal momento che l’SNMP non ha voglia da andare e avendo bisogno urgente di aggiornare un host su un dns, e essendo il router un Cisco 837 e non potendo usare ios 12.4 che supporta questo genere di protocollo, ho scritto qualche riga.

Un cron esegue ogni 15 minuti questo script:
/opt/dyn/noip2 -i `/opt/dyn/gci`

Ecco il contenuto di gci
#!/bin/sh
host=192.168.x.x
port=23
login=cisco
passwd=cisco
cmd='sh ip int brief'
(echo open ${host} ${port}
sleep 1
echo ${login}
sleep 1
echo ${passwd}
sleep 1
echo ${cmd}
sleep 1
echo exit) | telnet|grep Dialer0|awk '{print $2}'

Sarebbero cose da non usare.

Archives