Report inadequate content

Scripts in Harecoded

Convert a CSV to JSON with PHP

Imagine a data list dumped in a plain text file (e.g: CSV) and you need to convert it to JSON format. You could use this simple php script to do such task.

It's the simplest version but from here you can customize it to fit your requeriments.

Usage:

php script_name.php file_to_convert.csv > result.json

The script:

$csv = file_get_contents( $argv[1] );
$csv = explode("\n", trim($csv) );

foreach ( $csv as &$line )
{
$line = trim( $line );
}

print json_encode($csv);

This example covers a "single column" CSV file. If you want to add several columns you only need to add an explode with the separator character, be comma, somicolon or tab.

Comando `tree` para Mac

Existe una utilidad llamada "tree" en Windows y Linux que sirve para ver un listado de directorio en un formato ASCII un poco más agradable a la vista. Si no quieres bajarte los MacPorts para esta pequeña utilidad lo más fácil es crear un script de una línea y enlazarlo en /bin para poder llamarlo directamente.

El comando en cuestión es este:

find . -print | sed -e 's;[^/]*/;|--;g;s;--|; |;g'

Ahora, para utilizarlo a troche y moche basta con pegar su contenido en un fichero en cualquier ubicación. Por ejemplo, en mi carpeta de usuario de scripts (/Users/alombarte/scripts/tree.sh):

#!/bin/bash
find . -print | sed -e 's;[^/]*/;|--;g;s;--|; |;g'

Y entonces, para poder escribir allí donde queramos el comando tree hacemos un enlace simbólico:

sudo ln -s /Users/alombarte/scripts/tree.sh /bin/tree

Un ejemplo de la salida es este:

 

|--a1
| |--a11
| | |--fichero_en_a11.txt
| |--fichero_en_a1.txt
|--a2
| |--a21

Así de simple :)

Overburning script for Mac OS X, Record large films in Mac

If you use the Finder burning tool to create your CDs, or an application that doesn't support overburning (surpass a little bit the CD or DVD maximum size) I am sure that some time you got anrgy.

Sometimes are films, sometimes it's just one more song in the CD library you are creating... The thing is that you have 703MB and you cannot burn a 700MB CD. It won't happen again!

Because I did a script to overburn CDs and DVDs, and it's quite simple if you want to try it:

  • Save the following script inside a overburn.sh file with your prefered text editor or from the shell
  • Give it execution permissions
  • Create a folder named contents_to_overburn that will contain your overburned CD/DVD stuff
  • Copy anything you want to burn inside the folder
  • Execute the script from the terminal, so you can see what's happening, with: ./overburn.sh
hdiutil makehybrid -o tempfile contents_to_overburn/
hdiutil burn tempfile.iso
rm tempfile.iso
rm contents_to_overburn/*

At this point you have the CD burned and the folder emptied for a next use. Hope that works for you, enjoy. This script can be improved or even integrated with the OS X environment easily. If you feel like doing it, please share :)

See the Apple developer page for hdiutil for more information.

Basic and simple iptables configurations for home users

OpenBSD has been always my prefered distribution when I have to install a firewall based on a *NIX machine. The PF rules are what I am used to see. But last year I had to write several configurations for a debian machine using iptables which I am not really used to. Since I tend to forget these things, I paste here a basic configuration, if you want to use it, paste this in your desired starting script.

Please notice that these iptables scripts are intended to setup a FIREWALL that is in the middle of the traffic. If you want to use this rules for the machines that give the services change the FORWARD rules by INPUT

Configuration #1: Basic firewall accepting web, ssh and ftp

This configuration should be put in a machine between the machines that provide those services (WEB, SSH, FTP) and the Internet

# DELETE tables
iptables -F
iptables -X

# default policies (Deny by default)
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

# Accept loopback
iptables -A INPUT -i lo -j ACCEPT

# Keep State for already stablished traffic
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allowed services (web,ssh,ftp,icmp). # Note that we FORWARD paquets, this means that the services are not in the current machine. iptables -A FORWARD -p tcp --dport 80 -j ACCEPT iptables -A FORWARD -p tcp --dport 22 -j ACCEPT iptables -A FORWARD -p tcp --dport 21 -j ACCEPT iptables -A FORWARD -p icmp -j ACCEPT
#Pings to firewall: iptables -A INPUT -p icmp -j ACCEPT

Configuration 2: Only pings to firewall

#delete tables
iptables -F
iptables -X

#default policies
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

#Keep State for already stablished traffic
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#Pings to firewall:
iptables -A INPUT -p icmp -j ACCEPT

Configuration 3: Scripts for the machine that runs the services

This script is for the machines that run the services, not for a firewall in between. Note that the services have an INPUT instead of a FORWARD

# delete tables
iptables -F
iptables -X

# default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Accept loopback
iptables -A INPUT -i lo -j ACCEPT

# Keep State for already stablished traffic
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allowed services (ssh,web):
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

#Pings to machine:
iptables -A INPUT -p icmp -j ACCEPT

Como conectarse a internet con un móvil symbian y Ubuntu

En un artículo anterior hablábamos sobre cómo conectarse a internet con un móbil nokia 3G y macintosh. Esta vez, nos conectaremos desde un linux (Ubuntu 6.10).

Primero de todo el móbil tiene que estar bien configurado para hacer de módem. Estos pasos son los mismos que ya hemos explicado anteriormente, en cuanto a Linux, para no andar instalando más software del que viene por defecto usaremos el programa wvdial.

Manos a la obra. Lo primero que necesitamos es conectar mediante el cable USB el teléfono al ordenador y a continuación detectar como se llama el dispositivo que hace de módem en nuestro sistema. Para eso una consulta rápida al comando dmesg:

dmesg | tail

Eso nos devolverá en las últimas líneas algo similar a:

[17185105.844000] PPP BSD Compression module registered [17185105.880000] PPP Deflate Compression module registered [17185457.612000] usb 4-1: USB disconnect, address 2 [17185578.008000] usb 4-1: new full speed USB device using uhci_hcd and address 3 [17185578.184000] usb 4-1: configuration #1 chosen from 1 choice [17185578.196000] cdc_acm 4-1:1.8: ttyACM0: USB ACM device

Aqui podemos identificar la palabra ttyACM0 que es nuestro módem. A continuación ejecutaremos desde una terminal o desde la ventana ejecutar (ALT+F2) la línea:

gedit ~/.wvdialrc &

Y dentro del fichero pegaremos: [Dialer Defaults] Modem = /dev/ttyACM0 Phone = *99***1# Username = vodafone Password = vodafone Ojo al poner /dev/ttyACM0, debéis poner VUESTRO dispositivo (también podéis hacer un ls /dev/tty* para ver si aparece en la lista). Casi estamos! Ahora por último abrir una terminal y escribid:

wvdial

Empieza la secuencia y ya está conectado (no?). A navegar!

Posibles errores: Si tenéis mensajes de Permission denied probad a invocar el comando añadiendo delante sudo. Si en algún momento el módem se cuelga: pppd 2.4.4 started by root, uid 0 Using interface ppp0 Connect: ppp0 < --> /dev/ttyACM0 PAP authentication succeeded LCP terminated by peer Connection terminated. Modem hangup Exit. es que el teléfono no esta bien configurado para hacer de módem 3G

Muy útiles son los manuales: man wvdial y man wvdial.conf (sintaxis fichero configuración) .

Este post ha sido escrito a través de la conexión con el móbil :)

Script for compressing files with gzip within the terminal with date

This is a simple bash script to compress in tar.gz (gzip) format a file or folder appending date to file name.

Save this file as gzip.sh and give it execution permissions. From terminal i could be: chmod 755 gzip.sh
This script does the following:

  • Checks if you passed exactly 2 arguments
  • Compresses your source
  • Adds the date on the resulting filename
  • Optionally changes permissions of your filename (uncomment line chown and put the desired user:group)

Script:

#!/bin/bash
# Albert Lombarte
#
if [ $# != 2 ]
# There must be two arguments
then
    echo "--USAGE: $0 source target"
    exit 1
fi

FILENAME=`date "+%Y-%b-%d_$2"`
WHAT=$1

#======================================
echo "-- STARTED compression of $WHAT into $FILENAME"

#Use 'sudo' command before commands if needed

tar -c --gzip -f $FILENAME $WHAT
#chown alombarte:bckgroup $FILENAME

echo "-- FINISHED $WHAT"
echo ""
exit 1

or the same with less stuff...

#!/bin/bash
# Albert Lombarte

if [ $# != 2 ]
then
    echo "--USAGE: $0 source target"
    exit 1
fi

tar -c --gzip -f $1 $2

This example ...will result in 03-Aug-2005_alombarte.tar.gz

./gzip.sh /home/alombarte alombarte.tar.gz