How Unix programmers at restaurants search menus for their favorite plate

A Unix programmer heads over to the local diner to get something to eat for lunch. He, or Bob as he prefers, knows better than to manually scan the entire menu with his eyeballs because it’s inefficient. Bob knows that there’s a better way to automate the process in searching for what he wants to eat.

Last time he was here he had a pretty good pasta-and-shrimp plate for under 10 bucks.

Bob wonder’s if this same dish is still available. He pops open his laptop running Linux and scrapes the restaurant website menu table into a plain text file.

menu.txt

the menu

steak burrito $11.95
pasta and shrimp $9.75
caesar salad $6.50

Now that Bob has the menu, he does a grep search for the pasta-and-shrimp plate:

$ cat menu.txt | grep shrimp

pasta and shrimp $9.75

So far so good. He filters for the price column by using awk and the NF variable (which is the number of columns fields available) in order to get the last column containing the prices:

$ cat menu.txt | grep shrimp | awk '{print $NF}'

$9.75

The starvation is kicking in and he’s typing furiously by now. Bob proceeds with sed to turn the dollar amount into an integer by replacing everything except for what’s inbetween the dollar symbol and decimal period. He’ll use a capturing group and replace the contents with the first capture group \1:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g'

9

Finally, using the handy test command and the less-than flag -lt, Bob can check whether the price is less than 10 with the help of xargs to pipe the value as the first argument to test:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g' | xargs -I {} test {} -lt 10 

But wait there’s no output! Actually, test returns an exit status code of 0 if the condition passes or 1 if no match.

Bob simply echo’s Available if the previous command was successful by using &&, otherwise he’ll echo 🙁 by using the double pipe || if it was not successful:

$ cat menu.txt | grep shrimp | awk '{print $NF}' | sed -E 's/\$([0-9]+)\..*/\1/g' | xargs -I {} test {} -lt 10 && echo 'Available!' || echo ':('

Available!

Voila! there it is, the desired pasta-and-shrimp plate is still the under ten bucks. Bob is happy and proceeds to order his favorite dish.

(hope you liked this intro post to unix pipes and bash commands!)

Fonte:


github miguelmota


link miguelmota.com

Best Practice and Recommendations for Linux Server

Securing Linux server is very important to protect your data, intellectual property from the hands of crackers (hackers). The system administrator is responsible for security of the Linux box. In this blog we will go through important tips for hardening a Linux server.

Note: In this blog we are targeting specifically CentOS & RHEL Linux Operating system but same concept can be applied to other Linux/Unix flavors as well.

Link here to best practices

Link here to Linux Server Maintenance Checklist

Unity – Aggiungi link all’eseguibile in /opt

Place the installation to a common area (/opt).

$ sudo mkdir /opt/eclipse
$ sudo mv  /home/USERNAME_HIDDEN/eclipse/java-neon/ /opt/eclipse/

make a common link to the eclipse program to /usr/local/bin/eclipse.

$ sudo ln -s /opt/eclipse/eclipse /usr/local/bin/eclipse

Test running eclipse from the commandline.. Type this without a path:

$ eclipse

If it doesn’t work the exec program might be at:

/opt/eclipse/eclipse/eclipse

Fix this by removing the previous link and linking the exec with:

$ sudo rm /usr/local/bin/eclipse
$ sudo ln -s /opt/eclipse/eclipse/eclipse /usr/local/bin/eclipse

When you can bring up Eclipse from the commandline, you can make a desktop entry by creating a desktop program with.

Create the GUI Launcher

$ gedit  /home/USERNAME_HIDDEN/.local/share/applications/eclipse.desktop

copy and paste this into the editor then save it:

[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Name=Eclipse
Exec=/usr/local/bin/eclipse
Comment=Eclipse Integrated Development Environment
Icon=/opt/eclipse/eclipse/icon.xpm
Categories=programing;IDE;utility

Now eclipse should appear in your Ubuntu Launcher search button.

Continue reading

Security Tools to Check for Viruses and Malware on Linux

Antivirus tool

Whether you need an antivirus or anti-malware scanner or a tool to hunt for rootkits, Linux has you covered.

Wait, Linux needs antivirus and anti-malware solutions? I thought it was immune to such things. Perhaps a bit of clarification is necessary here.

First and foremost, no operating system is 100 percent immune to attack. Whether a machine is online or offline, it can fall victim to malicious code. Although Linux is less prone to such attacks than, say, Windows, there is no absolute when it comes to security. I have witnessed, first hand, Linux servers hit by rootkits that were so nasty, the only solution was to reinstall and hope the data backup was current. I’ve been a victim of a (very brief) hacker getting onto my desktop, because I accidentally left desktop sharing running (that was certainly an eye opener). The lesson? Even Linux can be vulnerable.

So why does Linux need tools to prevent viruses, malware, and rootkits? It should be obvious why every server needs protection from rootkits — because once you are hit with a rootkit, all bets are off as to whether you can recover without reinstalling the platform. It’s antivirus and anti-malware where admins start getting a bit confused.

Let me put it simply — if your server (or desktop for that matter) makes use of Samba or sshfs (or any other sharing means), those files will be opened by users running operating systems that are vulnerable. Do you really want to take the chance that your Samba share directory could be dishing out files that contain malicious code? If that should happen, your job becomes exponentially more difficult. Similarly, if that Linux machine performs as a mail server, you would be remiss to not include AV scanning (lest your users be forwarding malicious mail).

With all of that said, what are your options? Let’s take a look at a few tools, offered for the Linux platform, that do a good job of protecting you (and your users) from viruses, malware, and rootkits.

ClamAV

Without a doubt, ClamAV is the most popular option for keeping viruses off of your Linux machines and out of your shared directories. There are a few reasons why ClamAV is so popular among the Linux crowd. First, it’s open source, which in and of itself is a big win. Second, it’s very effective in finding trojans, viruses, malware, and other threats. ClamAV features a multi-threaded scanner daemon that is perfectly suited for mail servers and on-demand scanning.

ClamAV can be run from command line or it with the ClamTK GUI. Both tools are easy to use and very dependable. Installing ClamAV is simple.

For Debian-based systems:

sudo apt install clamav

For RHEL/CentOS systems:

sudo yum install epel-release

sudo yum install clamav

For Fedora-based systems:

sudo dnf install clamav

For SUSE-based systems:

sudo zypper in clamav

If you’re running a Debian-based desktop, you can install ClamTK (the GUI) with the command:

sudo apt install clamtk

There are also third-party tools that can be added (to include support for the likes of MTA, POP3, Web & FTP, Filesys, MUA, Bindings, and more).

Upon installation, the first thing you’ll want to do is update the signatures with the command sudo freshclam. Once that completes, you can scan a directory with the command:

clamscan -r -i DIRECTORY

where DIRECTORY is the location to scan. The -r option means to recursively scan and the -i options means to only print out infected files. If you work with the GUI, it’s even easier. From the GUI you can run a scan and, should ClamAV find anything, act on it (Figure 1).

ClamAV

Figure 1: ClamAV found a file with possible malicious code.

Usare rsync per una sincronizzazione in locale

Come detto, grazie a rsync è possibile sincronizzare file e cartelle in modo facile e sicuro. Supponendo di voler sincronizzare due cartelle in locale (ad esempio per creare un backup o una copia “esportabile” su una chiavetta USB) potremmo usare una sintassi del genere:

rsync -avz /path/to/source /path/to/destination

Vediamo nel dettaglio le opzioni utilizzate:

  • a => modalitĂ  “archivio” (copia ricorsivamente tutti i file, preservando permessi, timestamp, link simbolici, owner e gruppi);
  • v => modalitĂ  “verbose”, offre un output a video circa il risultato dell’elaborazione;
  • z => comprime i dati usando l’algoritmo gzip;

Non sovrascrivere i file modificati di recente

Si faccia attenzione: utilizzando la sintassi vista sopra, rsync andrĂ  ad allineare il contenuto del path di destinazione con quello del path sorgente! Se nella cartella di destinazione si hanno dei file piĂš recenti rispetto alla cartella sorgente e li si vuole preservare si dovrĂ  aggiungere il comando -u, in caso contrario, infatti, la cartella di destinazione viene allineata con la sorgente a prescindere che i files in essa contenuti siano piĂš recenti o meno.

rsync -auvz /path/to/source /path/to/destination

Sincronizzare un solo file

Volendo è possibile utilizzare rsync per effettuare il backup di un singolo file specificandone il nome in qualità di sorgente:

rsync -avz /path/to/source/filename /path/to/destination

Sincronizzare solo la struttura della directory

E’ possibile decidere di sincronizzare solo la struttura della directory sorgente nella destinazione remota. Per farlo useremo l’opzione -d in questo modo:

rsync -avd /path/to/source/filename /path/to/destination

Eliminare i file non presenti nella posizione sorgente

Supponiamo di avere dei files nella cartella di destinazione che non sono presenti nella cartella sorgente. Come si comporta rsync in questa situazione? Normalmente ignora questi file e li lascia dove sono. Se, tuttavia, preferiamo eliminarli possiamo utilizzarel’opzione –delete in questo modo:

rsync -avd --delete /path/to/source/filename /path/to/destination

Sincronizzare solo i file giĂ  presenti nella cartella di destinazione

E’ anche possibile dire ad rsync di sincronizzare esclusivamente i files giĂ  presenti nella folder di destinazione evitando cioè di crearne di nuovi qualora nella sorgente siano presenti files non rinvenibili nella directory target. Per una simile eventualitĂ  si utilizzerĂ  l’opzione –existing in questo modo:

rsync -avd --existing /path/to/source/filename /path/to/destination

Conoscere la data di creazione di un file in GNU/Linux

In Ext4 è possibile farlo con:

sudo debugfs -R stat /pippo/Scrivania/test.txt /dev/sda3

Ed infatti, creando un file di test e dando quel comando, l’output è:

Inode: 6029808 Type: regular Mode: 0644 Flags: 0x80000
Generation: 3337172570 Version: 0x00000000:00000001
User: 1000 Group: 1000 Size: 0
File ACL: 0 Directory ACL: 0
Links: 1 Blockcount: 0
Fragment: Address: 0 Number: 0 Size: 0
 ctime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
 atime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
 mtime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
crtime: 0x4e47fa9b:c3e1fd20 -- Sun Aug 14 18:40:59 2011
Size of extra inode fields: 28
EXTENTS:
(END)

dove la quartultima riga contiene il dato che ci interessa, cioè crtime (creation time).

Gli altri sono:

  • ctime (change time): ora del cambiamento, che può includere anche solo una modifica ai permessi senza apertura del file;
  • atime (access time): ora di accesso al file;
  • mtime (modification time): ora di modifica del file.

Schematicamente, ecco cosa avviene (la x indica un cambio del timestamp):

ctime atime mtime crtime
Creazione file x x x x
Apertura file x
Modifica file x x x
Cambio permessi x

 

PerchĂŠ oggi non andrai lontano se non conosci SQL, Python e JavaScript

linguaggio-programmiQuanto è grave, al giorno d’oggi, non conoscere le basi della programmazione? La risposta la lasciamo a una colossale ricerca effettuata negli Stati Uniti su qualcosa come 26 milioni di offerte di lavoro postate online. L’analisi, diffusa questo mese da Burning Glass e Oracle Academy, ha rivelato che metà dei posti di lavoro al top per retribuzione (dai 57mila dollari in su l’anno) richiede almeno le nozioni di base dei linguaggi di programmazione. In particolare SQL, Java, JavaScript, C# e Python.

Attenzione, perché non stiamo parlando di lavori legati strettamente alla tecnologia digitale. L’informatica è oggi presente in ogni tipo di industria, spiega Alison Derbenwick Miller, vicepresidente di Oracle Academy, e questo significa che saper programmare è un tipo di competenza richiesto in molteplici campi. Chimica, fisica, biologia, marketing, ingegneria, comunicazione, banking, assicurazioni: oggi sono innumerevoli i settori in cui si ha a che fare con i big data, e quindi con nozioni base di “coding”. E saper programmare con i controfiocchi, come sottolinea la ricerca di Burning Glass e Oracle Academy, è fondamentale almeno per sei professioni specifiche: operatori IT, analisti di dati, scienziati, ingegneri, artisti e designer.

Saper fare di “coding” significa anche guadagnare di piĂš. L’analisi condotta da Burning Glass e Oracle Academy sui “big data” delle ricerche di lavoro evidenzia come le professioni che richiedono nozioni di programmazione offrano stipendi superiori di circa 22mila dollari l’anno (84mila dollari in media contro i 62mila dei mestieri “coding free”). Non solo. Le professioni legate in qualche modo alla programmazione – oltre sette milioni di posti nel 2015 solo negli Stati Uniti – crescono secondo la ricerca a una velocitĂ  del 12% superiore a quella media di mercato.

Programmare significa automatizzare lavori ripetitivi e trovare soluzioni a problemi ritenuti impossibili da risolvere, spiega Mike Grassotti, capo del settore IT a LiftForward, azienda di New York che offre prestiti a Pmi. ÂŤE’ la nuova alfabetizzazione – riassume l’italoamericano – : il “coding” diventerĂ  presto un requisito di base della formazione, proprio come oggi lo è il saper leggere e scrivereÂť.

La morale? E’ che anche stavolta Steve Jobs è stato profetico. In un’intervista televisiva di oltre vent’anni fa il padre della Mela aveva proclamato che ÂŤOgni persona in questo Paese dovrebbe imparare come si programma, perchĂŠ è qualcosa che ti insegna a pensareÂť. Era il lontano 1995. Un anno e mezzo dopo Jobs sarebbe tornato in Apple, rivoluzionando le nostre vite con l’iMac, l’iPod, l’iPhone e l’iPad.

Fonte: Il Sole 24 ore

Ssh e autenticazione tramite chiavi

Fonte: http://guide.debianizzati.org/index.php/Ssh_e_autenticazione_tramite_chiavi

== Introduzione ==
Quando ci si deve connettere molto spesso ad un server (o a molti server) tramite ”'[[SSH]]”’, può essere tedioso dover inserire ogni volta la password.

Un modo sicuro per ”aggirare” questo problema è basato sull’autenticazione tramite una coppia di chiavi (privata e pubblica).

Il concetto alla base di questo sistema di autenticazione è semplice: si demanda il compito di verificare i dati di autenticazione direttamente alle chiavi ssh, rimuovendo la richiesta della password (meno volte viene digitata, piÚ è difficile che qualche utente male intenzionato la riesca a capire) che viene, eventualmente, sostituita dalla richiesta di una passphrase di sblocco della chiave.

== Configurazione ==
=== Generazione delle chiavi ===
Per poter gestire questo processo di autenticazione è necessario generare una coppia di chiavi (pubblica e privata). Il comando è semplice:

$ ssh-keygen 

Si può voler scegliere una lunghezza maggiore (default 2048) con

$ ssh-keygen -b 4096

L’uso dell’opzione '''-t''' per indicare il tipo di chiave è [[OpenSSH#Configurazione_Client|fortemente sconsigliato]].

Durante la generazione delle chiavi ci viene chiesto dove salvarle (normalmente è ~/.ssh/id_rsa): il valore di default va bene.

Per quanto riguarda la passphrase richiesta, sempre durante la generazione delle chiavi, ci sono due opzioni, entrambe con pregi e difetti:
* inserire una passphrase: dal punto di vista della sicurezza, è ottimo; dal punto di vista pratico, però, si è di fronte al problema che è necessario inserirla ad ogni connessione (nel caso di piĂš host, comunque, rappresenterebbe un sistema molto comodo di accesso tramite la stessa ”passphrase”, invece di una password diversa per ogni host)
* inserire una passphrase vuota: dal punto di vista della sicurezza lascia un po’ a desiderare, in quanto il furto della chiave permetterebbe l’accesso incondizionato agli host; dal punto di vista pratico, invece, è comodissimo, in quanto slega l’accesso alla macchina remota dalla richiesta di password.

In realtà questo discorso può valere in caso di utilizzo non interattivo come ad esempio in uno script, negli altri casi si può ricorrere a ssh-agent per mantenere in cache la passphrase per la sessione corrente:

$ ssh-add ~/.ssh/id_rsa

=== Copia manuale della chiave pubblica ===
La chiave privata, come illustrato nel funzionamento, viene utilizzato dal computer che richiede la connessione (client), mentre quella pubblica deve essere salvata sul computer al quale connettersi (server).

Prendiamo, ad esempio, la seguente chiave pubblica (contenuta nel file ~/.ssh/id_rsa.pub presente sul client):

ssh-rsa AAAAB3NzaC1kc3MAAACBAPe/PbwWkXR7qI8hcbxLRUS0/fIul0eUiSvu/hnXZXZDIZjVi1VlIbipff6n7Z6vF0hJRg6l
[cut]
gjLLTka0/QF8SP4JYFKs0Iasdju6y1slmx9IdzQt+hvMqF2+PPchCWcyBP3S5Zje4T6Az1MgrvuwCXIW6oUZXCA== user@host

Copiamo il contenuto nel file ~/.ssh/authorized_keys presente sul server, nella home relativa all’utente usato su quella macchina e salviamo il file.

=== Copia automatica della chiave pubblica ===
Alternativamente, è possibile usare lo script ”ssh-copy-id” in questo modo dal client:

$ ssh-copy-id -i ~/.ssh/id_rsa.pub utente@server

oppure ancora utilizzando scp:

$ scp -P  ~/.ssh/id_rsa.pub @:~/.ssh/authorized_keys

I permessi sulla directory remota ~/.ssh devono essere settati a:

drwxr-xr-x 2 utente utente  4096 30 dic 00:31 .ssh

mentre sul file ~/.ssh/authorized_keys:

-rw-r--r-- 1 utente utente  610 30 dic 00:17 authorized_keys

== Configurazione del server ==
Sul server, in cui deve essere giĂ  presente un’installazione di base funzionante di SSH, aggiornate il file /etc/ssh/sshd_config e settate i campi:

HostbasedAuthentication yes
RSAAuthentication yes
PubkeyAuthentication yes

Riavviate il servizio:

# /etc/init.d/ssh restart

e verificate di essere in grado di autenticarvi tramite chiave:

$ ssh utente@server

{{Box|Consiglio:|se ”’non”’ volete permettere il login tramite password, ma solo attraverso public key, settate anche le opzioni:

ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

Da non usare se avete utilizzato una passphrase nella generazione della chiave.}}

”’Attenzione”’: in caso di autenticazione tramite chiavi, nel file di configurazione del server non va utilizzata la direttiva AllowUsers.

Per un’installazione di base di SSH si veda ad esempio la guida [[OpenSSH: file di configurazione]].

== Test di funzionamento ==
Se tutto è stato eseguito correttamente, sarà possibile connettersi al server tramite un semplice:

$ ssh utente@server

Se è stata inserita, durante la generazione delle chiavi, una passphrase, sarà necessario usarla per completare il processo di autenticazione, altrimenti apparirà direttamente il prompt della macchina remota.

== Approfondimenti ==
* [http://www.debian.org/doc/manuals/reference/ch06.it.html#_the_remote_access_server_and_utility_ssh La guida Debian: SSH]

[[Categoria:SSH server e amministrazione remota]]

write a shell script

To successfully write a shell script, you have to do three things:

  1. Write a script
  2. Give the shell permission to execute it
  3. Put it somewhere the shell can find it

Now, fire up your text editor and type in your first script as follows:

#!/bin/bash
...the script

And after saving you must make it executeable.

sudo chmod +x <path>
sudo chmod 755 <filename>

Note that it is a good idea to put your scripts in one place, so you can run them without requiring a path. If you create a bin directory in your home ( mkdir ~/bin ) the next time you login, that will automatically be included in your PATH.

mkdir ~/bin
chmod 755 ~/bin

Edit : If you want the script to be available to all users, place it in /usr/local/bin and have it owned by root with rx access by others sudo chown root:root /usr/local/bin/your_script ; sudo chmod 655 /usr/local/bin/your_script

gksudo gedit ~/.bashrc

Add the following to the end of .bashrc and save:

if [ -d $HOME/bin ]; then
PATH=$PATH:$HOME/bin
fi

 

Creating a bootable USB drive from an ISO image

Using isohybrid + dd

The isohybrid tool in the syslinux package will convert ISO images into a USB flash drive compatible format:

# apt-get install syslinux
# isohybrid path/to/image.iso

Use lsblk to identify the device path (e.g., /dev/sdX) of your USB drive:

# lsblk
sde                                     8:64   1   7.4G  0 disk  
└─sde1                                  8:65   1   7.4G  0 part  /media/usbdrive

Use too:

# fdisk-l

If it’s been automounted, as is the case above, unmount it first:

# umount /media/usbdrive

Use dd to write the ISO image to the disk path. That’s /dev/sde NOT /dev/sde1:

dd if=path/to/image.iso of=/dev/sde status=progress bs=4M
Things to keep in mind:
  • bs=dimensioni(bytes)
    Legge e scrive dati in blocchi delle dimensioni specificate
  • Root access is required: You will need to perform the above commands as root. On Ubuntu prepend the commands with sudo (e.g., sudo apt-get install syslinux)
  • dd will completely overwrite your USB drive: Any data on it will be lost so if you use this method you’ll want to use it with a dedicated USB device.
  • dd needs to write to the disk path, not the partition path: in the above example /dev/sde is the disk path device, /dev/sde1 is the partition path (e.g., sde1 is the first partition on sde). You need to write to the disk path because isohybrid prepends a partition structure to the ISO.
  • status=progress (like the sentence itself say) show the progress of copy

How isohybrid works

Starting in version 3.72, ISOLINUX supports a “hybrid mode” which can be booted from either CD-ROM or from a device which BIOS considers a hard disk or ZIP disk, e.g. a USB key or similar.  These isohybrid images contain in addition to the normal CD-based ISO9660 filesystem, a valid-looking DOS-style partition table. So if you simply “raw” copy an isohybrid processed image to a USB flash drive, the BIOS will boot the image directly.

iso2usb.py helper script

The ‘dd’ command has always scared me. One wrong keystroke and you can overwrite the wrong hard disk. To make things a little less scary and safer, I wrote iso2usb:
Syntax: iso2usb.py iso_path usb_device
iso2usb: Create a bootable USB flash drive containing ISO image

Arguments:
    iso_path        Path to ISO (e.g., product.iso)
    usb_device      USB device path (e.g., /dev/sdc)

Options:
    --force         Not implemented, interactive confirmation required
iso2usb will do its best to verify that the usb_device is actually a USB device, and prompt for confirmation with device information before doing anything dangerous:
# iso2usb.py turnkey-core-13.0-wheezy-amd64.iso /dev/sdc
****************************************************************************
iso: turnkey-core-13.0-wheezy-amd64.iso (hybrid: False)
usb: disk/by-id/usb-SanDisk_Cruzer_Blade_200601650311ADD19323-0:0 (/dev/sdc)
****************************************************************************
Is the above correct? (y/N):

Additionally, iso2usb will check whether the ISO image has been pre-processed with isohybrid, and if not it will process the image before writing it.

Once completed, the USB flash drive should now boot directly, showing exactly the same bootup screen as if you’d written the image directly to a CD.

The old pre-isohybrid version of iso2usb

If for some reason your ISO isn’t using ISOLINUX as the bootloader you might want to try the old pre-isohybrid version of the iso2usb.py script which I wrote a few years ago. It extracts the ISO to the USB drive together and then installs syslinux. Recently I tried using it but hit issues related to changes in isolinux, which has since introduced the new isohybrid method.

The future

All future TurnKey ISO’s will be pre-processed with isohybrid, making it that little bit more TurnKey for installing ISO’s to USB flash disks.

BASH Frequently Asked Questions

Here Bash Faq & Bash Guide

These are answers to frequently asked questions on channel #bash on the freenode IRC network. These answers are contributed by the regular members of the channel (originally heiner, and then others including greycat and r00t), and by users like you. If you find something inaccurate or simply misspelled, please feel free to correct it!

All the information here is presented without any warranty or guarantee of accuracy. Use it at your own risk. When in doubt, please consult the man pages or the GNU info pages as the authoritative references.

BASH is a BourneShell compatible shell, which adds many new features to its ancestor. Most of them are available in the KornShell, too. The answers given in this FAQ may be slanted toward Bash, or they may be slanted toward the lowest common denominator Bourne shell, depending on who wrote the answer. In most cases, an effort is made to provide both a portable (Bourne) and an efficient (Bash, where appropriate) answer. If a question is not strictly shell specific, but rather related to Unix, it may be in the UnixFaq.

This FAQ assumes a certain level of familiarity with basic shell script syntax. If you’re completely new to Bash or to the Bourne family of shells, you may wish to start with the (incomplete) BashGuide.

If you can’t find the answer you’re looking for here, try BashPitfalls. If you want to help, you can add new questions with answers here, or try to answer one of the BashOpenQuestions.

Chet Ramey’s official Bash FAQ contains many technical questions not covered here.

Il Backup perfetto con Linux

Il backup in ambiente Linux è una di quelle procedure che va impostata bene una sola volta, per poi dimenticarsene completamente. Trovo molto utile la guida scritta da Saverio Bolognani che spiega dettagliatamente come implementare il “Backup Perfetto” in ambienti Linux. Ovviamente la procedura quì descritta può essere applicata anche sui sistemi Ubuntu Linux.

Penso che il backup perfetto (in qualsiasi sistema operativo) debba soddisfare i seguenti requisiti. Continue reading

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 14.04

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 14.04

https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04

 

How To Create a New User and Grant Permissions in MySQL

https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql

 

How To Create a New User and Grant Permissions in MySQL

https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql

 

How To Set Up Apache Virtual Hosts on Ubuntu 12.04 LTS

https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

 

How can I exclude all “permission denied” messages from “find”?

Use:

find ./quellochecerco 2>/dev/null

This hides not just the permission denied errors, of course, but all error messages.

If you really want to keep other possible errors, such as too many hops on a symlink, but not the permission denied ones, then you’d probably have to take a flying guess that you don’t have many files called ‘permission denied’ and try:

find . 2>&1 | grep -v 'permission denied' > files_and_folders

 

Rimuovere tutte le tabelle di un db MySql

Remove all tables from database MySql

SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
  FROM information_schema.tables
  WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@tables,'dummy') INTO @tables;

SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;

This script will not raise error with NULL result in case when you already deleted all tables in the database by adding at least one nonexistent – “dummy” table.

And it fixed in case when you have many tables.

And This small change to drop all view exist in the Database

SET FOREIGN_KEY_CHECKS = 0;
SET GROUP_CONCAT_MAX_LEN=32768;
SET @views = NULL;
SELECT GROUP_CONCAT('`', TABLE_NAME, '`') INTO @views
  FROM information_schema.views
  WHERE table_schema = (SELECT DATABASE());
SELECT IFNULL(@views,'dummy') INTO @views;

SET @views = CONCAT('DROP VIEW IF EXISTS ', @views);
PREPARE stmt FROM @views;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;

Come scaricare in maniera ricorsiva da un sito FTP

In questi giorni ho dovuto scaricare un sacco di file da un server FTP remoto, la soluzione migliore in casi come questo è collegarsi sul ​​server remoto e fare un archivio compresso di tutti i file (per questo uso tar -zcvf ArchiveName.tgz /ercorso/da/archiviare/), in questo modo dovrete scaricare solo 1 file che è anche stato compresso e FTP può fare perfettamente questo lavoro.

Ma questa volta non avevo alcuna shell sul server remoto, solo un account FTP, quindi qual è il modo migliore per scaricare un gran numero di file in modo ricorsivo?

Come prima cosa ho dato uno sguardo alla pagina di manuale di ftp, ah ho dimenticato di dire che la macchina in cui devo scaricare tutti i file è un server senza interfaccia grafica quindi nessun client FTP grafico a portata di mano, guardando la pagina del man FTP , la cosa piÚ simile di quello che mi serviva era il comando mget:

mget file-remoti
Espandere i file-remoti sulla macchina remota ed esegui un get
per ogni nome di file che viene prodotto. Vedere glob per i dettagli su
come si espande il nome del file. I nomi dei file risultanti saranno quindi
elaborati a seconda dei casi e delle impostazioni di ntrans e di nmap.
I file vengono trasferiti nella directory di lavoro locale, che
può essere cambiata con ‘lcd directory’; nuove directory locali
possono essere create con ‘! mkdir directory ‘.

Quindi utile, ma non per me in questo caso in cui ho piÚ sottodirectory, quindi con una rapida ricerca su Google ho scoperto che semplicemente il protocollo FTP non supportano il download ricorsivo e quindi è necessario utilizzare le opzioni dei client per farlo, vediamo quindi come farlo con wget.

Wget

GNU Wget è un pacchetto software gratuito per il recupero dei file tramite HTTP, HTTPS e FTP, i protocolli di Internet piÚ utilizzati. Si tratta di un tool non-interattivo a riga di comando, quindi può essere facilmente chiamato da script, cron jobs, terminali senza il supporto di X-Windows, ecc
Quindi questo sembra lo strumento perfetto per essere utilizzato su un server, come plus wget è presente di sicuro in qualsiasi repository delle distribuzione Linux e ciò rende l’installazione è banale.

La sintassi di base per wget è

 wget ftp://myusername:mypassword@ftp.yoursite.com/tuofile

Con un comando come questo si utilizza il protocollo FTP con l’account myusername e la password mypassword per prelevare da ftp.yoursite.com il file tuofile.
Ma abbiamo bisogno di alcune opzioni extra per avere un download ricorsivo dal sito FTP.

Opzioni Extra

-r –recursive Attiva il download ricorsivo.

-l profondità –level=profondità Specifica la profondità massima di ricorsione. La profondità massima di default è 5.

CosĂŹ il nostro comando diventa:

wget -r --level=99 ftp://myusername:mypassword@ftp.yoursite.com/

In questo modo, a partire dalla directory root wget scarica in modo ricorsivo fino a 99 livelli (oppure è possibile utilizzare inf per infinito)
Oppure è possibile utilizzare l’opzione -m (che sta per mirror)
L’opzione -m attiva il mirroring cioè attiva la ricorsione ed il time-stamping, imposta una profondità infinita di ricorsione e mantiene gli elenchi di directory FTP:

wget -m ftp://myusername:mypassword@ftp.yoursite.com/

Se come me avete un sito molto grande vi suggerisco di eseguirlo con un nohup davanti al comando ed eseguirlo in background.

Un consiglio finale per wget, se si deve ri-scaricare lo stesso sito, è possibile utilizzare anche l’opzione -nc, in questo modo i file non verranno scaricati 2 volte.

-nc –no-clobber
Se un file è stato scaricato piÚ di una volta nella stessa directory, Il comportamento di Wget dipende da alcune opzioni, tra cui -nc. In alcuni casi, il file locale verrà sovrascritto, al momento del download. In altri casi sarà conservata.

Durante l’esecuzione di Wget con -r o -p, ma senza -N, -nd, o -nc, ri-scaricare un file risulta semplicemente nel fare una nuova copia , basta sovrascrivere il vecchio. Aggiungendo -nc questo comportamento sarà impedito , provocando invece la conservazione della versione originale e di tutti i file recenti presenti sul server.

Terminator – Useful tool for arranging terminals

 

 

 

 
Originally created and developed for a long time by Chris Jones, the goal of this project is to produce a useful tool for arranging terminals. It is inspired by programs such as gnome-multi-term, quadkonsole, etc. in that the main focus is arranging terminals in grids (tabs is the most common default method, which Terminator also supports).

Web-site

Installation

Linux Distributions

Ubuntu

Click here: Install Terminator

This may give you an older version, so to install the very latest Terminator:

sudo add-apt-repository ppa:gnome-terminator
sudo apt-get update
sudo apt-get install terminator