Lambda expressions are cool
Lambdache?
Quindi, cosa sono le lambda expression? Definiamo la lambda expression come funzioni anonime, sì funzioni come quelle del linguaggio C, per capirsi e anonime: senza, cioè, una dichiarazione che le dia un nome. Abbiamo, quindi, un nuovo approccio al codice, possiamo cioè scrivere codice funzionale: passare funzioni a funzioni così come adesso passiamo oggetti ad oggetti, restituire funzioni da funzioni, come adesso restituiamo oggetti a partire da oggetti ma soprattutto possiamo usare oggetti e funzioni assieme semplificando il codice. Detta così non è ancora chiara la portata della novità, per cui codice, codice, codice! Partiamo da come scriviamo il codice oggi e arriviamo a come si può scrivere con Java 8.
Lambda expressions are cool
In questo post faremo un unico esempio che andremo via via a modificare introducendo le lambda expression: abbiamo una lista di stringhe e vogliamo stamparla su console. Scriviamo il primo codice che ci viene in mente:
package it.cosenonjaviste.lambda;
import java.util.*;
public class SevenMinutesLambda {
public static void main(String[] args) {
List strings = Arrays.asList(“Lambda “, “expressions “, “are “, “cool”);
for (int i = 0; i < strings.size(); i++) {
System.out.print(strings.get(i));
}
}
}
Quanto abbiamo scritto fa quello che ci aspettiamo, ma con l’uso dei generics possiamo fare di meglio:
package it.cosenonjaviste.lambda;
import java.util.*;
public class SevenMinutesLambda {
public static void main(String[] args) {
List
for (String element : strings) {
System.out.print(element);
}
}
}
Questo codice è sicuramente familiare, perché lo usiamo da anni e a colpo d’occhio sappiamo cosa fa. Siamo sicuri però che sia il codice più semplice da scrivere e quello più performante? Prima di procedere riflettiamo per un attimo su quello che abbiamo di fronte, siamo davanti ad un caso di iterazione esterna, cioè stiamo dicendo alla collezione di stringhe: dammi una stringa, poi dammene un’altra e un’altra ancora, è il codice client che chiede alla lista un elemento alla volta e poi decide cosa farne, in pieno stile imperativo.
Iterazione interna
L’interazione interna invece, è tutta un’altra storia e mi permetto di prendere in prestito l’esempio di Mario Fusco al JavaOne per far capire la differenza tra i due. L’iterazione esterna è un po’ come far riordinare i giochi alla propria figlia piccolina:
“prendi quella palla laggiù”
“e adesso?”
“mettila nella cesta dei giochi”
“e adesso?”
“prendi quella bambola qui”
“e adesso?”
“mettila nella cesta dei giochi”
e adesso?
…
L’iterazione interna invece assomiglia di più a “prendi i tuoi giochi e mettili nella cesta” (sottointeso: scegli tu l’ordine con cui farlo e se hai l’altra mano libera e passi vicino ad un giocattolo, e ti va di prenderlo, prendi anche quello). Sicuramente anche chi non è genitore apprezza la compattezza e semplicità della seconda soluzione 😉 .
Cosa ci offre Java 8 per usare questo tipo di iterazione nel caso visto sopra? Il nuovo metodo forEach:
1
2
void forEach(Consumer super T> action)
//Performs an action for each element of this stream.
che prende in ingresso un Consumer, una nuova interfaccia di Java 8 (per la precisione è una interfaccia funzionale ma lasciamo questo argomento per un prossimo post). La cosa che ci interessa sapere ora è che questa interfaccia è come quelle che conosciamo e che ha un metodo da implementare:
1
void accept(T t) //Performs this operation on the given argument.
Scriviamo quindi una inner class anonima che implementa Consumer e la passiamo direttamente al forEach.
package it.cosenonjaviste.lambda;
import java.util.*;
import java.util.function.Consumer;
public class SevenMinutesLambda {
public static void main(String[] args) {
List
strings.forEach(new Consumer
public void accept(String s) {
System.out.print(s);
}
});
}
}
Il risultato non cambia, ma quello che abbiamo fatto è un cambio di paradigma, non diciamo più alla lista come produrre il risultato, ma cosa voglia che venga fatto su ogni elemento della collezione, ci concentriamo meno sul modo per farlo ma su cosa vogliamo ottenere. Un altro vantaggio è che l’iterazione è nascosta nell’implementazione. Non solo non rischiamo più di commettere errori nella costruzione del ciclo, ma l’implementazione è polimorfica in base alla classe a cui si applica il metodo. Di conseguenza, l’iterazione interna può essere ottimizzata a seconda del tipo di struttura dati e, quando richiesto e dove applicabile, può essere svolta in parallelo.
Basta un poco di zucchero e..
Tuttavia, il codice che abbiamo adesso non sembra così invitante: abbiamo scritto molte più righe per ottenere lo stesso risultato di prima. Fortunatamente, possiamo sostituire la inner class con una lambda expression, liberandoci di tutto il codice in più e, di fatto, scrivendo tutto in un’unica riga.
import java.util.*;
import java.util.function.Consumer;
public class SevenMinutesLambda {
public static void main(String[] args) {
List
strings.forEach((String s) -> System.out.print(s));
}
}
Adesso sì che abbiamo qualcosa di un po’ più “alieno” sotto gli occhi. Esaminiamo la nostra lambda (=funzione anonima) con attenzione. Una funzione ha un nome, una lista di parametri, un corpo e un valore ritornato. Abbiamo la lista di parametri (String s) separata dal corpo (System.out.print(s)) con la freccia ->. Il tipo di ritorno viene dedotto dal contesto, in questo caso è void. Il nome invece non c’è: era anonima la inner class prima, è anonima la funzione adesso. Ora la definizione di lambda che abbiamo dato all’inizio ha più senso.
Quindi, dove possiamo utilizzare le lambda? Dovunque ci sia una interfaccia che preveda tra i suoi metodi uno e un solo metodo astratto. Beh, ma le interfacce non hanno implementazioni, tutti i metodi di una interfaccia sono astratti per definizione, direte. No, da Java 8 è possibile avere interfacce che hanno dei metodi implementati (detti di default), anche questo argomento lo lasciamo per un prossimo post.
Meno verboso, meno noioso
Si può fare ancora di meglio, dal contesto il compilatore sa che stiamo applicando la nostra lambda ad una collezione di stringhe attraverso la type inference, quindi possiamo semplificare la funzione omettendo il tipo per s.
package it.cosenonjaviste.lambda;
import java.util.*;
public class SevenMinutesLambda {
public static void main(String[] args) {
List
strings.forEach(s -> System.out.print(s));
}
}
Ora la nostra lambda è talmente semplice che.. si può semplificare ancora! Dato che l’unica cosa che facciamo al suo interno è chiamare un metodo, possiamo usare un method reference al posto della nostra espressione. Anche questa è una novità introdotta dalla versione 8. Possiamo pensare i method reference come delle lambda expression che non sono anonime, ma che si riferiscono ad un specifico metodo di una determinata classe (o di una istanza). Ad esempio, String::valueOf o Integer::compare sono esempi di method reference per metodi statici. Detto questo, non ci resta che usare questo nuovo costrutto nel nostro codice e modificare il nostro esempio per l’ultima volta.
package it.cosenonjaviste.lambda;
import java.util.*;
public class SevenMinutesLambda {
public static void main(String[] args) {
List
strings.forEach(System.out::print);
}
}
Il passaggio alle lambda è completo ora, siamo passati da un ciclo for, classico esempio di iterazione esterna, a una iterazione interna gestita attraverso una funzione anonima o un method reference, sicuramente un bel po’ della verbosità di Java è stata eliminata a vantaggio della chiarezza e semplicità.
Installing and configuring an SSL certificate on Postfix/Dovecot mail server
From here ….thanks…
This guide describes the ways to enable the SSL/TLS encryption using a trusted SSL certificate for receiving secured incoming and outgoing connections on a Postfix-Dovecot server.
For testing purposes, a Comodo PositiveSSL certificate has been used; however, to secure your mail server, you can purchase any certificate with us as they meet your needs.
The testing was done on the following server stack:
- Ubuntu 16.04
- Postfix 3.1.0
- Dovecot 2.2.22
If you do not have any issued (trusted) certificate yet for the hostname of your mail server, it is necessary to purchase it, generate a CSR needed for activation and once done, activate it.
If you have your certificate issued, you are able to download it from the SSLs.com user account or from the email (fulfillment email) received from the Certificate Authority to the administrative contact email address you have chosen during the activation process.
The first thing you need to do is to upload and concatenate the certificate files on the server. You can follow the actions below:
1. Upload the certificate file yourdomainname.crt to the server along with the CA bundle. Keep in mind that the CA bundle can be either in a single file (example.ca-bundle) or in separate files (COMODORSADomainValidationSecureServerCA.crt, COMODORSAAddTrustCA.crt, AddTrustExternalCARoot.crt as in our case). The following files should be saved in the following way: the certificate and CA bundle files in the /etc/ssl/certs/ directory; the corresponding private key (example_com.key) in the /etc/ssl/private/ folder.
2.Combine the uploaded files into one using one of the commands below:
2.1. Create a file with the server certificate and CA chain:
- cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/yourdomainname.ca-bundle >> /etc/ssl/certs/certificate.crt
- cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/COMODORSADomainValidationSecureServerCA.crt /etc/ssl/certs/COMODORSAAddTrustCA.crt /etc/ssl/certs/AddTrustExternalCARoot.crt >> /etc/ssl/certs/certificate.crt
2.2. One file with the combined certificate, CA chain and Private Key can be acceptable for Postfix and Dovecot. One of the commands below can be used to create it:
- cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/yourdomainname.ca-bundle /etc/ssl/private/yourdomainname.key >> /etc/ssl/certs/certificate_and_key.crt
- cat /etc/ssl/certs/yourdomainname.crt /etc/ssl/certs/COMODORSADomainValidationSecureServerCA.crt /etc/ssl/certs/COMODORSAAddTrustCA.crt /etc/ssl/certs/AddTrustExternalCARoot.crt /etc/ssl/private/yourdomainname.key >> /etc/ssl/certs/certificate_and_key.crt
In order to check the content of the new file in question, run the following command: cat /etc/ssl/certs/certificate.crt or cat /etc/ssl/certs/certificate_and_key.crt.
It is necessary to check whether there are no excessive white spaces between or inside the PEM-encoded certificate and key blocks in the output.
If you notice such spaces, they can be edited manually – open the file in a text editor like “vi” or “nano” and remove the odd elements.
The editing of Postfix and Dovecot configuration files to enable SSL/TLS on specific ports
The process of sending and receiving mail over the Internet is a complex system of endpoint and intermediary instances (mail server and client software) labeled as mail user agents (MUA), mail submission agents (MSA), mail transfer agents (MTA) and mail delivery agents (MDA) depending on the functions they perform. Normally, an email is passed over each type of the above-mentioned parties, and different transport protocols are used on every step, namely submission protocol, Simple Mail Transfer Protocol (SMTP), Post Office Protocol (POP3) and Internet Message Access Protocol (IMAP).
The below chart shows the use of ports for specific transport protocol execution.
Protocol | Usage | Plain text / encrypted session | Encrypted session only |
POP3 | Incoming mail | 110 | 995 |
IMAP | Incoming mail | 143 | 993 |
SMTP | Outgoing mail | 25 | 465 |
Submission | Outgoing mail | 587 |
The Opportunistic TLS approach gives the possibility to use ports 25, 110, 143 and 587 either in the plain text (unencrypted) or secure (encrypted) mode. According to this approach, the STARTTLS command is requested when an existing active plain text session happens.
Technically, using ports 465, 993 and 995 and the way HTTP protocol is used over SSL/TLS are similar: 1) secure ports are detached from their “unsecured” counterparts; 2) any data exchange can be performed after establishing an encrypted session.
NOTE: Although port 465 is not listed as the SMTPS port in the official standards of IANA’s documentation, it is used to serve encrypted outgoing mail traffic by mail server administrators.
Both techniques described above are considered to be used in the Internet mail system nowadays. In order to secure your mail, it is better to install an SSL certificate on every mail port you are planning to use.
The steps below will help you to install your SSL certificate for both mail ports: incoming and outgoing ones:
Port 25 (SMTP with STARTTLS)
- Open to edit the file named main.cf (Postfix configuration file). You can usually find it in the /etc/postfix/ directory.
- Locate the TLS parameters section in the main.cf file and make the changes in the following values of certain directives. See the example below:
- if you save the certificate and private key in separate files:
smtpd_tls_cert_file=/etc/ssl/certs/certificate.crt
smtpd_tls_key_file=/etc/ssl/private/yourdomainname.key
- if you save the certificate and private key in a single file:
smtpd_tls_cert_file=/etc/ssl/certs/certificate_and_key.crt
smtpd_tls_key_file=$smtpd_tls_cert_file
NB: It is necessary to make sure that smtpd_use_tls directive is set to yes:
smtpd_use_tls=yes
Once done, close the main.cf file and save the changes you made.
Ports 587 (Submission with STARTTLS) and 465 (SMTPS)
- Locate the Postfix’s master.cf file in the /etc/postfix/ directory and open it;
- When it is opened, uncomment (or edit if needed) the next lines:
- to open and protect port 587:
submission inet n – y – – smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=may
-o smtpd_sasl_auth_enable=yes
- to open and protect port 465:
smtps inet n – y – – smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
Now you can close this file.
Ports 110 (POP3 with STARTTLS), 143 (IMAP with STARTTLS), 993 (IMAPS) and 995 (POP3S)
If you need to install an SSL certificate for Dovecot, it is essential to follow the next steps:
- Open the file named 10-ssl.conf. This file can be usually located in the /etc/dovecot/conf.d/ directory.
- Edit the following lines:
- if you save the certificate and private key in separate files:
ssl_cert = </etc/ssl/certs/certificate.crt
ssl_key = </etc/ssl/private/yourdomainname.key
- if you save the certificate and private key in a single file:
ssl_cert = </etc/ssl/certs/cert_and_key.crt
ssl_key = </etc/ssl/certs/cert_and_key.crt
Make sure that thessl directive is set to yes:
ssl = yes
When the changes are made, close the 10-ssl.conf file.
If the steps mentioned above are made, the SSL certificate is installed for all incoming ports now.
Please note that if you have the Dovecot version 1.x, the directives for SSL certificates in configuration files may slightly differ:
- it is necessary to check whether /etc/dovecot/dovecot.conf has the following line:
protocols = imap pop3 imaps pop3s
- edit the /etc/dovecot/conf.d/10-ssl.conf file in the following way:
ssl_disable = no
– if you save the certificate and private key in separate files:
ssl_cert_file = </etc/ssl/certs/certificate.crt
ssl_key_file = </etc/ssl/private/yourdomainname.key
– if you save the certificate and private key in a single file:
ssl_cert_file = </etc/ssl/certs/cert_and_key.crt
ssl_key_file = </etc/ssl/certs/cert_and_key.crt
Useful tips:
Below you can find the information regarding some additional settings which can be useful in setting up your mail server’s SSL/TLS handling. For further information, you can refer to Postfix andDovecot official documentation regarding this matter as well.
It is possible to use the STARTTLS port on Postfix in the “wrapper” mode with the smtpd_tls_wrappermode directive. Instead of showing the STARTTLS support and waiting for the request from a remote client, this option helps to run a secure connection from the very beginning. The following directive should be added to /etc/postfix/master.cf , for instance:
smtps inet n – n – – smtpd
-o smtpd_tls_wrappermode=yes
On Dovecot, when you try to log in, there is an opportunity to set the ssl directive to required value (ssl=required), which implies forcing the SSL handshake.
In such cases, the password will be sent in a secure way, meanwhile with ssl = yes, email clients are not requested to use SSL/TLS in precedence. Both plaintext and non-plaintext authentication mechanisms can be applied with this setting.
In order to switch off the plaintext authentication mechanism, it is possible to use disable_plaintext_auth directive (/etc/dovecot/conf.d/10-auth.conf):
disable_plaintext_auth=yes
The following directives on Dovecot (/etc/dovecot/dovecot.conf) can be used for eliminating the ciphers which are better not to be used due to low encryption strength:
ssl_dh_parameters_length = 2048
ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL
To exclude certain ciphers or protocols for opportunistic (STARTTLS) or mandatory (regular SSL) encryption, it is possible to use the following directives in /etc/postfix/main.cf and assign the corresponding values to them:
– for mandatory TLS
smtpd_tls_mandatory_exclude_ciphers = [cipher] smtpd_tls_mandatory_protocols = ![protocol]
– for opportunistic TLS
smtpd_tls_exclude_ciphers = [cipher]
smtpd_tls_protocols = ![protocol]
To set the server side cipher list more preferable over the client-side one, these directives can be used:
– on Dovecot (/etc/dovecot/conf.d/10-ssl.conf)
ssl_prefer_server_ciphers = yes
– on Postfix (/etc/postfix/main.cf)
tls_preempt_cipherlist = yes
How to check SSL installation
OpenSSL
The OpenSSL toolkit helps to check the SSL certificate installation on a server both remotely and locally.
In order to check STARTTLS ports, the following command should be run. Replace [port] with the port number and [protocol] with smtp, pop3 or imap value:
openssl s_client -connect example.com:[port] -servername example.com -starttls [protocol]
In order to check non-STARTTLS ports, use the following command:
openssl s_client -connect example.com:[port] -servername example.com
How to check your secure connection
In order to check your mail server connectivity over SSL/TLS, the online checkers listed below can be used.
You need to specify the server hostname and port number or an existing email account and run the test.
Fail2ban Error in file postfix-sasl.conf
my old file conf was :
failregex = ^%(__prefix_line)swarning: [-._\w]+\[\]: SASL ((?i)LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(:[ A-Za-z0-9+/:]*={0,2})?\s*$
If you go to https://regex101.com/ you can test the regular expression on the log string :
May 10 15:57:59 mail postfix/smtpd[28617]: warning: ip43.ip-192-99-125.net[192.99.125.43]: SASL LOGIN authentication failed: Connection lost to authentication server
I corrected the error and the the configuration is :
failregex = ^%(__prefix_line)swarning: [-._\w]+\[<HOST>\]: SASL ((?i)LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed(:[ A-Za-z0-9+:]*={0,2})?\s*$
You can leave also the first setting but it is not necessary.
Some others command to do test:
fail2ban-client ping
fail2ban-client status
fail2ban-client status dovecot
fail2ban-client status postfix-sasl
fail2ban-regex /root/software/test_fail2ban_dovecot.log /etc/fail2ban/filter.d/dovecot.conf
You can test a piece of log file with a configuration jail file using the command fail2ban-regex
1a -> no need to change rotation, read about the settings: bantime, findtime, maxretry
1b -> fail2ban reads the log which is defined in jails logpath, for the recidive jail /var/log/fail2ban.log will be used
2 -> yes it means recidve will ban ip based on the log entrys matching bantime, findtime, maxretry
3. -> such long block time should not be needed, if it is an repeating offender he will by chached up by the recidive jail
4. it depends on your system and resources, if you are worry about the amount of blocked ip´s then you can set up the jails with ipset,
read also:
Using Fail2ban to Secure Your Server – A Tutorial
Optimising your Fail2Ban filters | The Art of Web
Protection Against Brute Force Attacks (Fail2Ban)
Fail2Ban Jails Management
fail2ban-client set <jail> unbanip <ip>
Bach color Linux
# Reset
Color_Off='\033[0m' # Text Reset
# Regular Colors
Black='\033[0;30m' # Black
Red='\033[0;31m' # Red
Green='\033[0;32m' # Green
Yellow='\033[0;33m' # Yellow
Blue='\033[0;34m' # Blue
Purple='\033[0;35m' # Purple
Cyan='\033[0;36m' # Cyan
White='\033[0;37m' # White
# Bold
BBlack='\033[1;30m' # Black
BRed='\033[1;31m' # Red
BGreen='\033[1;32m' # Green
BYellow='\033[1;33m' # Yellow
BBlue='\033[1;34m' # Blue
BPurple='\033[1;35m' # Purple
BCyan='\033[1;36m' # Cyan
BWhite='\033[1;37m' # White
# Underline
UBlack='\033[4;30m' # Black
URed='\033[4;31m' # Red
UGreen='\033[4;32m' # Green
UYellow='\033[4;33m' # Yellow
UBlue='\033[4;34m' # Blue
UPurple='\033[4;35m' # Purple
UCyan='\033[4;36m' # Cyan
UWhite='\033[4;37m' # White
# Background
On_Black='\033[40m' # Black
On_Red='\033[41m' # Red
On_Green='\033[42m' # Green
On_Yellow='\033[43m' # Yellow
On_Blue='\033[44m' # Blue
On_Purple='\033[45m' # Purple
On_Cyan='\033[46m' # Cyan
On_White='\033[47m' # White
# High Intensity
IBlack='\033[0;90m' # Black
IRed='\033[0;91m' # Red
IGreen='\033[0;92m' # Green
IYellow='\033[0;93m' # Yellow
IBlue='\033[0;94m' # Blue
IPurple='\033[0;95m' # Purple
ICyan='\033[0;96m' # Cyan
IWhite='\033[0;97m' # White
# Bold High Intensity
BIBlack='\033[1;90m' # Black
BIRed='\033[1;91m' # Red
BIGreen='\033[1;92m' # Green
BIYellow='\033[1;93m' # Yellow
BIBlue='\033[1;94m' # Blue
BIPurple='\033[1;95m' # Purple
BICyan='\033[1;96m' # Cyan
BIWhite='\033[1;97m' # White
# High Intensity backgrounds
On_IBlack='\033[0;100m' # Black
On_IRed='\033[0;101m' # Red
On_IGreen='\033[0;102m' # Green
On_IYellow='\033[0;103m' # Yellow
On_IBlue='\033[0;104m' # Blue
On_IPurple='\033[0;105m' # Purple
On_ICyan='\033[0;106m' # Cyan
On_IWhite='\033[0;107m' # White
the escape character in bash, hex and octal respectively:
| | bash | hex | octal | NOTE |
|-------+-------+--------+---------+------------------------------|
| start | \e | \x1b | \033 | |
| start | \E | \x1B | - | x cannot be capital |
| end | \e[0m | \x1m0m | \033[0m | |
| end | \e[m | \x1b[m | \033[m | 0 is appended if you omit it |
| | | | | |
short example:
| color | bash | hex | octal | NOTE |
|-------------+--------------+----------------+----------------+---------------------------------------|
| start green | \e[32m<text> | \x1b[32m<text> | \033[32m<text> | m is NOT optional |
| reset | <text>\e[0m | <text>\1xb[0m | <text>\033[om | o is optional (do it as best practice |
| | | | | |
bash exception:
If you are going to use these codes in your special bash variables
- PS0
- PS1
- PS2 (= this is for prompting)
- PS4
you should add extra escape characters so that bash can interpret them correctly. Without this adding extra escape characters it works but you will face problems when you use Ctrl + r
for search in your history.
exception rule for bash
You should add \[
before any starting ANSI code and add \]
after any ending ones.
Example:
in regular usage: \033[32mThis is in green\033[0m
for PS0/1/2/4: \[\033[32m\]This is in green\[\033[m\]
\[
is for start of a sequence of non-printable characters
\]
is for end of a sequence of non-printable characters
Tip: for memorize it you can first add \[\]
and then put your ANSI code between them:
– \[start-ANSI-code\]
– \[end-ANSI-code\]
type of color sequence:
- 3/4 bit
- 8 bit
- 24 bit
Before diving into these colors, you should know about 4 modes with these codes:
1. color-mode
It modifies the style of color NOT text. For example make the color bright or darker.
0
reset1;
lighter than normal2;
darker than normal
This mode is not supported widely. It is fully support on Gnome-Terminal.
2. text-mode
This mode is for modifying the style of text NOT color.
3;
italic4;
underline5;
blinking (slow)6;
blinking (fast)7;
reverse8;
hide9;
cross-out
and are almost supported.
For example KDE-Konsole supports 5;
but Gnome-Terminal does not and Gnome supports 8;
but KDE does not.
3. foreground mode
This mode is for colorizing the foreground.
4. background mode
This mode is for colorizing the background.
The below table shows a summary of 3/4 bit version of ANSI-color
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| color-mode | octal | hex | bash | description | example (= in octal) | NOTE |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 0 | \033[0m | \x1b[0m | \e[0m | reset any affect | echo -e "\033[0m" | 0m equals to m |
| 1 | \033[1m | | | light (= bright) | echo -e "\033[1m####\033[m" | - |
| 2 | \033[2m | | | dark (= fade) | echo -e "\033[2m####\033[m" | - |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| text-mode | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 3 | \033[3m | | | italic | echo -e "\033[3m####\033[m" | |
| 4 | \033[4m | | | underline | echo -e "\033[4m####\033[m" | |
| 5 | \033[5m | | | blink (slow) | echo -e "\033[3m####\033[m" | |
| 6 | \033[6m | | | blink (fast) | ? | not wildly support |
| 7 | \003[7m | | | reverse | echo -e "\033[7m####\033[m" | it affects the background/foreground |
| 8 | \033[8m | | | hide | echo -e "\033[8m####\033[m" | it affects the background/foreground |
| 9 | \033[9m | | | cross | echo -e "\033[9m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| foreground | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 30 | \033[30m | | | black | echo -e "\033[30m####\033[m" | |
| 31 | \033[31m | | | red | echo -e "\033[31m####\033[m" | |
| 32 | \033[32m | | | green | echo -e "\033[32m####\033[m" | |
| 33 | \033[32m | | | yellow | echo -e "\033[33m####\033[m" | |
| 34 | \033[32m | | | blue | echo -e "\033[34m####\033[m" | |
| 35 | \033[32m | | | purple | echo -e "\033[35m####\033[m" | real name: magenta = reddish-purple |
| 36 | \033[32m | | | cyan | echo -e "\033[36m####\033[m" | |
| 37 | \033[32m | | | white | echo -e "\033[37m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 38 | 8/24 | This is for special use of 8-bit or 24-bit |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| background | ~ | | | ~ | ~ | ~ |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 40 | \033[40m | | | black | echo -e "\033[40m####\033[m" | |
| 41 | \033[41m | | | red | echo -e "\033[41m####\033[m" | |
| 42 | \033[42m | | | green | echo -e "\033[42m####\033[m" | |
| 43 | \033[43m | | | yellow | echo -e "\033[43m####\033[m" | |
| 44 | \033[44m | | | blue | echo -e "\033[44m####\033[m" | |
| 45 | \033[45m | | | purple | echo -e "\033[45m####\033[m" | real name: magenta = reddish-purple |
| 46 | \033[46m | | | cyan | echo -e "\033[46m####\033[m" | |
| 47 | \033[47m | | | white | echo -e "\033[47m####\033[m" | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| 48 | 8/24 | This is for special use of 8-bit or 24-bit | |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
The below table shows a summary of 8 bit version of ANSI-color
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| 0-7 | \033[38;5 | \x1b[38;5 | \e[38;5 | standard. normal | echo -e '\033[38;5;1m####\033[m' | |
| 8-15 | | | | standard. light | echo -e '\033[38;5;9m####\033[m' | |
| 16-231 | | | | more resolution | echo -e '\033[38;5;45m####\033[m' | has no specific pattern |
| 232-255 | | | | | echo -e '\033[38;5;242m####\033[m' | from black to white |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| 0-7 | | | | standard. normal | echo -e '\033[48;5;1m####\033[m' | |
| 8-15 | | | | standard. light | echo -e '\033[48;5;9m####\033[m' | |
| 16-231 | | | | more resolution | echo -e '\033[48;5;45m####\033[m' | |
| 232-255 | | | | | echo -e '\033[48;5;242m####\033[m' | from black to white |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
The 8-bit fast test:
for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done
The below table shows a summary of 24 bit version of ANSI-color
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| foreground | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | R = red | echo -e '\033[38;2;255;0;02m####\033[m' | R=255, G=0, B=0 |
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | G = green | echo -e '\033[38;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
| 0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | B = blue | echo -e '\033[38;2;0;0;2552m####\033[m' | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| background | octal | hex | bash | description | example | NOTE |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | R = red | echo -e '\033[48;2;255;0;02m####\033[m' | R=255, G=0, B=0 |
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | G = green | echo -e '\033[48;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
| 0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | B = blue | echo -e '\033[48;2;0;0;2552m####\033[m' | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
some screen-shots
foreground 8-bit summary in a .gif
background 8-bit summary in a .gif
color summary with their values
blinking
on KDE-Terminal
a simple C
code that shows you more
a more advanced tool that I developed to deal with these colors:
color-mode shot
text mode shot
combining is OK
more shots
Tips and Tricks for Advanced Users and Programmers:
Can we use these codes in a programming language?
Yes, you can. I experienced in bash, c, c++, d perl, python
Are they slow down the speed of a program?
I think, NO.
Can we use these on Windows?
3/4-bit Yes, if you compile the code with gcc
some screen-shots on Win-7
How to calculate the length of code?
\033[
= 2, other parts 1
Where can we use these codes?
Anywhere that has a tty
interpreter
xterm
, gnome-terminal
, kde-terminal
, mysql-client-CLI
and so on.
For example if you want to colorize your output with mysql you can use Perl
#!/usr/bin/perl -n
print "\033[1m\033[31m$1\033[36m$2\033[32m$3\033[33m$4\033[m" while /([|+-]+)|([0-9]+)|([a-zA-Z_]+)|([^\w])/g;
store this code in a file name: pcc
(= Perl Colorize Character) and then put the file a in valid PATH
then use it anywhere you like.
ls | pcc
df | pcc
inside mysql
first register it for pager
and then try:
[user2:db2] pager pcc
PAGER set to 'pcc'
[user2:db2] select * from table-name;
It does NOT handle Unicode.
Do these codes only do colorizing?
No, they can do a lot of interesting things. Try:
echo -e '\033[2K' # clear the screen and do not move the position
or:
echo -e '\033[2J\033[u' # clear the screen and reset the position
There are a lot of beginners that want to clear the screen with system( "clear" )
so you can use this instead of system(3)
call
Are they available in Unicode?
Yes. \u001b
Which version of these colors is preferable?
It is easy to use 3/4-bit
, but it is much accurate and beautiful to use 24-bit
.
If you do not have experience with html so here is a quick tutorial:
24 bits means: 00000000
and 00000000
and 00000000
. Each 8-bit is for a specific color.
24..17
is for and 16..9
for and 8..1
for
So in html #FF0000
means and here it is: 255;0;0
in html #00FF00
means which here is: 0;255;0
Does that make sense? what color you want combine it with these three 8-bit values.
reference:
Wikipedia
ANSI escape sequences
tldp.org
tldp.org
misc.flogisoft.com
some blogs/web-pages that I do not remember