Início

porplague70

How To Install Linux, Apache, MySQL, PHP (LAMP) stack On CentOS 7

Introduction

A “LAMP” stack is a group of open source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually an acronym which represents the Linux operating system, with the Apache web server. The site data is stored in a MySQL database (using MariaDB), and dynamic content is processed by PHP.

In this guide, we’ll get a LAMP stack installed on an CentOS 7 VPS. CentOS will fulfill our first requirement: a Linux operating system.

Note: The LAMP stack can be installed automatically on your Droplet by adding this script to its User Data when launching it. Check out this tutorial to learn more about Droplet User Data.

Prerequisites

Before you begin with this guide, you should have a separate, non-root user account set up on your server. You can learn how to do this by completing steps 1-4 in the initial server setup for CentOS 7.

Step One — Install Apache

The Apache web server is currently the most popular web server in the world, which makes it a great default choice for hosting a website.

We can install Apache easily using CentOS’s package manager, yum. A package manager allows us to install most software pain-free from a repository maintained by CentOS. You can learn more about how to use yum here.

For our purposes, we can get started by typing these commands:

sudo yum install httpd

Since we are using a sudo command, these operations get executed with root privileges. It will ask you for your regular user’s password to verify your intentions.

Afterwards, your web server is installed.

Once it installs, you can start Apache on your VPS:

sudo systemctl start httpd.service

You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser (see the note under the next heading to find out what your public IP address is if you do not have this information already):

http://your_server_IP_address/

You will see the default CentOS 7 Apache web page, which is there for informational and testing purposes. It should look something like this:

CentOS 7 Apache default

If you see this page, then your web server is now correctly installed.

The last thing you will want to do is enable Apache to start on boot. Use the following command to do so:

sudo systemctl enable httpd.service

How To Find your Server’s Public IP Address

If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.

From the command line, you can find this a few ways. First, you can use the iproute2 tools to get your address by typing this:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

This will give you one or two lines back. They are both correct addresses, but your computer may only be able to use one of them, so feel free to try each one.

An alternative method is to use an outside party to tell you how it sees your server. You can do this by asking a specific server what your IP address is:

curl http://icanhazip.com

Regardless of the method you use to get your IP address, you can type it into your web browser’s address bar to get to your server.

Step Two — Install MySQL (MariaDB)

Now that we have our web server up and running, it is time to install MariaDB, a MySQL drop-in replacement. MariaDB is a community-developed fork of the MySQL relational database management system. Basically, it will organize and provide access to databases where our site can store information.

Again, we can use yum to acquire and install our software. This time, we’ll also install some other “helper” packages that will assist us in getting our components to communicate with each other:

sudo yum install mariadb-server mariadb

When the installation is complete, we need to start MariaDB with the following command:

sudo systemctl start mariadb

Now that our MySQL database is running, we want to run a simple security script that will remove some dangerous defaults and lock down access to our database system a little bit. Start the interactive script by running:

sudo mysql_secure_installation

The prompt will ask you for your current root password. Since you just installed MySQL, you most likely won’t have one, so leave it blank by pressing enter. Then the prompt will ask you if you want to set a root password. Go ahead and enter Y, and follow the instructions:

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorization.

New password: password
Re-enter new password: password
Password updated successfully!
Reloading privilege tables..
 ... Success!

For the rest of the questions, you should simply hit the “ENTER” key through each prompt to accept the default values. This will remove some sample users and databases, disable remote root logins, and load these new rules so that MySQL immediately respects the changes we have made.

The last thing you will want to do is enable MariaDB to start on boot. Use the following command to do so:

sudo systemctl enable mariadb.service

At this point, your database system is now set up and we can move on.

Step Three — Install PHP

PHP is the component of our setup that will process code to display dynamic content. It can run scripts, connect to our MySQL databases to get information, and hand the processed content over to our web server to display.

We can once again leverage the yum system to install our components. We’re going to include the php-mysql package as well:

sudo yum install php php-mysql

This should install PHP without any problems. We need to restart the Apache web server in order for it to work with PHP. You can do this by typing this:

sudo systemctl restart httpd.service

Install PHP Modules

To enhance the functionality of PHP, we can optionally install some additional modules.

To see the available options for PHP modules and libraries, you can type this into your system:

yum search php-

The results are all optional components that you can install. It will give you a short description for each:

php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
php-cli.x86_64 : Command-line interface for PHP
php-common.x86_64 : Common files for PHP
php-dba.x86_64 : A database abstraction layer module for PHP applications
php-devel.x86_64 : Files needed for building PHP extensions
php-embedded.x86_64 : PHP library for embedding in applications
php-enchant.x86_64 : Enchant spelling extension for PHP applications
php-fpm.x86_64 : PHP FastCGI Process Manager
php-gd.x86_64 : A module for PHP applications for using the gd graphics library
. . .

To get more information about what each module does, you can either search the internet, or you can look at the long description in the package by typing:

yum info package_name

There will be a lot of output, with one field called Description which will have a longer explanation of the functionality that the module provides.

For example, to find out what the php-fpm module does, we could type this:

yum info php-fpm

Along with a large amount of other information, you’ll find something that looks like this:

. . .
Summary     : PHP FastCGI Process Manager
URL         : http://www.php.net/
License     : PHP and Zend and BSD
Description : PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI
            : implementation with some additional features useful for sites of
            : any size, especially busier sites.

If, after researching, you decide you would like to install a package, you can do so by using the yum install command like we have been doing for our other software.

If we decided that php-fpm is something that we need, we could type:

sudo yum install php-fpm

If you want to install more than one module, you can do that by listing each one, separated by a space, following the yum install command, like this:

sudo yum install package1 package2 ...

At this point, your LAMP stack is installed and configured. We should still test out our PHP though.

Step Four — Test PHP Processing on your Web Server

In order to test that our system is configured properly for PHP, we can create a very basic PHP script.

We will call this script info.php. In order for Apache to find the file and serve it correctly, it must be saved to a very specific directory, which is called the “web root”.

In CentOS 7, this directory is located at /var/www/html/. We can create the file at that location by typing:

sudo vi /var/www/html/info.php

This will open a blank file. We want to put the following text, which is valid PHP code, inside the file:

<?php phpinfo(); ?>

When you are finished, save and close the file.

If you are running a firewall, run the following commands to allow HTTP and HTTPS traffic:

sudo firewall-cmd --permanent --zone=public --add-service=http 
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

Now we can test whether our web server can correctly display content generated by a PHP script. To try this out, we just have to visit this page in our web browser. You’ll need your server’s public IP address again.

The address you want to visit will be:

http://your_server_IP_address/info.php

The page that you come to should look something like this:

CentOS 7 default PHP info

This page basically gives you information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.

If this was successful, then your PHP is working as expected.

You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, you can type this:

sudo rm /var/www/html/info.php

You can always recreate this page if you need to access the information again later.

Conclusion

Now that you have a LAMP stack installed, you have many choices for what to do next. Basically, you’ve installed a platform that will allow you to install most kinds of websites and web software on your server.

porplague70

How to Stop and Disable FireHow to Stop and Disable Firewalld on CentOS 7

Firewalld is a complete firewall solution that has been made available by default on all CentOS 7 servers, including Liquid Web Core Managed CentOS 7, and Liquid Web Self Managed CentOS 7. On occasion, perhaps for testing, disabling or stopping firewalld may be necessary. Follow the instructions below to disable firewalld and stop firewalld.

It is highly recommended that you have another firewall protecting your network or server before, or immediately after, disabling firewalld.

Pre-Flight Check

  • These instructions are intended specifically for stopping and disabling firewalld CentOS 7.
  • I’ll be working from a Liquid Web Self Managed CentOS 7 server, and I’ll be logged in as root.

Disable Firewalld

To disable firewalld, run the following command as root:

systemctl disable firewalld

Stop Firewalld

To stop firewalld, run the following command as root:

systemctl stop firewalld

Check the Status of Firewalld

And finally, to check the status of firewalld, run the following command as root:

systemctl status firewalld

Wait, you actually wanted to Start and Enable Firewalld on CentOS 7? Then hit our tutorial on: How to Start and Enable Firewalld on CentOS 7!

porplague70

Setting up WPAD Autoconfigure for the Squid Package.

Setting up WPAD Autoconfigure for the Squid Package

pfSense can be configured to serve up automatic proxy configuration data to clients to point users to squid running either on pfSense or another local system, assuming their systems settings are configured for this behavior. Though the data can be served from the firewall, the task is better suited for another local web server if one is available.

Note

To use the web server on the firewall to serve this data, the GUI must run in HTTP mode, or the vhosts package may be used to setup an alternate HTTP server on port 80. Neither of these are recommended as much as running a separate local web server for this task.

This process is known as WPAD, short for Web Proxy AutoDiscovery Protocol. If a web browser is configured for autodiscovery, it will try a few methods to figure out a proxy’s location.

A WPAD host may be supplied via DHCP numbered option 252 (string value containing the entire URL to the WPAD file) or DNS, which is easy to do with the built-in DNS forwarder.

Why would this be done?

To use squid authentication, squid cannot be used in transparent mode. HTTPS traffic also cannot be filtered using transparent mode. When squid is run in normal mode, a proxy IP and port must be configured on each client machine, which can be tedious. This can also cause problems on road warrior laptops that come in and out of the network. Rather than resetting their proxy configuration each time they enter and leave, autoconfigure will let them come and go without much trouble.

Most, if not all, modern browsers ship with the autoconfigure setting turned off, so it may still be necessary to push/enter this setting to client PCs. Even so, another advantage of using autoconfigure is that should squid move to another IP address, only one file must be changed to inform the clients of the updated IP address. (This may be easy to pull off in a windows domain with AD, but not for many others!)

Prerequisites

This How-To assumes squid is already operating in a non-transparent configuration. For help with that, look elsewhere in this documentation and on the Forums.

Create wpad.dat

Before starting, a wpad.dat file must be crafted. This is a single file with a JavaScript function which tells the browser how to find a proxy hostname and port. This function can be as simple or as complex as desired, there are many examples on the web. In this example, all clients will be directed to the squid instance on the firewall.

The contents of the example wpad.dat file are:

function FindProxyForURL(url,host)
{
return "PROXY 192.168.1.1:3128";
}

The function in that file tells the browser to look for a proxy on 192.168.1.1 at port 3128.

Now upload that file to pfSense or another locally accessible web server with scp, or create it using the built-in file editor. The file must go in /usr/local/www/.

Due to the different ways that various browser versions try to access the file, this same code should exist in at least three different places:

/usr/local/www/wpad.dat
/usr/local/www/wpad.da
/usr/local/www/proxy.pac

(More advanced users might do this from the shell and use ln to link the files.)

We recommend pointing wpad. to an internal web server which can answer requests for the wpad.dat and associated files. It can be any web server, but typically must be served from both the default VirtualHost as well as one named wpad, due to differences in how browsers request the file.

To make this work using pfSense to serve the file, local IP addresses will need to be able to access the local interface IP address of the pfSense router. They do not need to access the WebGUI with a password, this file will be served without authentication. The GUI must also be run in HTTP mode, which is less secure. If the GUI is set to use HTTP, never open up access to the GUI over the WAN.

Configure DNS

Now to setup the DNS portion. WPAD will take the domain name given to the machine, likely assigned by DHCP, and prepend wpad.. If the domain is example.com, it will look for wpad.example.com. This task may be accomplished with the DNS Forwarder/DNS Resolver in pfSense or with another internal DNS server used by client PCs.

A client browser will ultimately try to access http://wpad.example.com/wpad.dat – among others. More details on the hostnames tried by WPAD are available in the WPAD article on Wikipedia.

To add the entry using the DNS forwarder on pfSense, navigate to Services > DNS Forwarder. Click fa-plus to add a new Host Override.

Enter the following (Replace the domain and IP address with their actual values):

  • Hostwpad
  • Domainexample.com
  • IP Address192.168.1.1
  • DescriptionWPAD Autoconfigure Host

Click Save.

Block Port 80 Out from LAN

Create a firewall rule at the TOP of the LAN tab (or appropriate interface) that blocks anything from <internal subnet> to * on port 80.

Note

If the firewall is used to serve WPAD and the WebGUI anti-lockout rule has been disabled, web traffic must also be allowed to the pfSense firewall GUI port. If this is not acceptable, point wpad. to another internal web server which can answer requests for the wpad.dat and associated files.

Test Clients

Fire up a browser on a client behind the pfSense firewall, and see what happens. If squid is configured for authentication, the client will be greeted with a login prompt. Otherwise, check squid’s logs to ensure traffic is going through the proxy. A proxy test site such ashttp://www.lagado.com/proxy-test can also be useful.

If nothing happened, check the browser settings. Many modern browsers ship with the autoconfigure settings off.

Internet Explorer

  • Open Internet Options
  • Click the Connections tab
  • Click the LAN Settings button
  • Check Automatically Detect Settings
  • Click OK, and OK again.

Firefox

  • Click Tools (Or the three bar icon)
  • Click Options
  • Click Advanced
  • Click the Network tab
  • Click the Settings button
  • Select Auto-detect proxy settings for this network
  • Click OK
porplague70

Endereços IP de acesso aos webservices da Nota Fiscal Eletrônica. SEFAZ

Atenção para os endereços IP de acesso aos ambientes de produção e homologação da NFE. As empresas que possuem firewall devem estar liberando conexão pela porta 443 para *TODAS* as seguintes redes:
 
 Produção  189.2.188.128/26  187.5.111.0/25  201.48.19.0/26
 Homologação  189.2.188.178  187.5.111.50  201.48.19.50
porplague70

Gerando Sua Chave Pública SSH.

Gerando Sua Chave Pública SSH

Vários servidores Git autenticam usando chaves públicas SSH. Para fornecer uma chave pública, cada usuário no seu sistema deve gerar uma se eles ainda não a possuem. Este processo é similar entre os vários sistemas operacionais. Primeiro, você deve checar para ter certeza que você ainda não possui uma chave. Por padrão, as chaves SSH de um usuário são armazenadas no diretório ~/.ssh. Você pode facilmente verificar se você tem uma chave indo para esse diretório e listando o seu conteúdo:

$ cd ~/.ssh
$ ls
authorized_keys2  id_dsa       known_hosts
config            id_dsa.pub

Você está procurando por um par de arquivos chamados algo e algo.pub, onde algo é normalmente id_dsa ou id_rsa. O arquivo .pub é a sua chave pública, e o outro arquivo é a sua chave privada. Se você não tem estes arquivos (ou não tem nem mesmo o diretório .ssh), você pode criá-los executando um programa chamado ssh-keygen, que é fornecido com o pacote SSH em sistemas Linux/Mac e vem com o pacote MSysGit no Windows:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/schacon/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/schacon/.ssh/id_rsa.
Your public key has been saved in /Users/schacon/.ssh/id_rsa.pub.
The key fingerprint is:
43:c5:5b:5f:b1:f1:50:43:ad:20:a6:92:6a:1f:9a:3a sc*****@ag**********.local

Primeiro ele confirma onde você quer salvar a chave (.ssh/id_rsa), e então pergunta duas vezes por uma senha, que você pode deixar em branco se você não quiser digitar uma senha quando usar a chave.

Agora, cada usuário que executar o comando acima precisa enviar a chave pública para você ou para o administrador do seu servidor Git (assumindo que você está usando um servidor SSH cuja configuração necessita de chaves públicas). Tudo o que eles precisam fazer é copiar o conteúdo do arquivo .pub e enviar para você via e-mail. As chaves públicas são parecidas com isso.

$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== sc*****@ag**********.local

Para um tutorial mais detalhado sobre criação de chaves SSH em vários sistemas operacionais, veja o guia do GitHub sobre chaves SSH no endereço http://github.com/guides/providing-your-ssh-key.

porplague70

Enhanced e-mail SPAM protection in ISPConfig 3

The command below enables a stricter SPAM handling for postfix on ISPConfig 3 servers.

In Detail:

  • Reject sender hostnames with invalid syntax
  • Reject sender hostnames that are no fully qualified domains (e.g. reject “server1” but allow server1.domain.tld)
  • Reject sender domains that have no DNS records
  • Check sender IP addresses against realtime blacklists.

First make a backup of the postfix main.cf file in case that you want to reverse the changes later:

cp -pf /etc/postfix/main.cf /etc/postfix/main.cf.bak

Then execute this command to enable the additional spam protection functions (the command is one line!).

postconf -e ‘smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_hostname, reject_non_fqdn_hostname, reject_unknown_recipient_domain, reject_non_fqdn_recipient, reject_unauth_destination, reject_non_fqdn_sender, reject_unknown_sender_domain, reject_unknown_recipient_domain, reject_rbl_client cbl.abuseat.org,reject_rbl_client dul.dnsbl.sorbs.net,reject_rbl_client ix.dnsbl.manitu.net, check_recipient_access mysql:/etc/postfix/mysql-virtual_recipient.cf, reject_unauth_destination’

Then restart postfix:

/etc/init.d/postfix restart

porplague70

SUBSTITUIR STRING COM SED

Vc não fechou o comando … note que vc abre a instrução do SED com aspas simples, logo vc tem que fechar

sed 's/antigo/novo/g' arquivo

jogando pra um arquivo.

sed 's/antigo/novo/g' arquivo > arquivo.new
porplague70

Como adicionar uma linha ao crontab tab diretamente pela linha de comando

Sem utilizar a edição via crontab -e (comando abre o conteúdo do cron no seu editor para edição), é possível diretamente da linha de comando adicionar uma nova linha ao crontab. Abaixo um exemplo:

?
$ (crontab -l; echo "30 04 * * 4 /home/data/drall/backups/report.sh 2>&1") | crontab -

A manha é justamente executar 2 comandos em um subshell agrupados por “(” e “)”. O primeiro comando, crontab -l, obtem os comandos atualmente existente no crontab. O comando echo em seguida emite o novo comando. A junção dos dois é feita e estas saídas se tornam via pipe a entrada padrão para o comando crontab, que efetuará o salvamento de todo o novo conteúdo em seu registro.

Também é possível adicionar via comandos salvo em um arquivo:

$ cat /tmp/cron | crontab -
porplague70

Mandar e-mail via linha de comando no Linux.

Mandar e-mail via linha de comando no Linux

Todo mundo fica dizendo que e-mail é coisa do passado e que o futuro mesmo é utilizar as redes sociais e a Web 2.0 (lol) para se comunicar. Mas a verdade é que o e-mail ainda é muito útil e acredito que vai demorar bastante tempo para que isso mude. No pior dos casos, e-mail ainda continua sendo uma boa forma de registro e notificação.

E no caso da notificação, enviar e-mail via linha de comando do Linux é bastante útil. Terminou uma tarefa no crontab? Envia um e-mail com o resultado. Caiu um servidor? Envia um e-mail para alguém notificando. Ou então querer apenas testar um servidor de e-mail local? É só usar a imaginação.

Como todos sabemos, o Linux conta com o recurso de shell, que por sua vez permite criar poderosos programas que são chamados de shell scripts. Vejamos aqui esta pequena dica de como enviar e-mail via linha de comando.

O comando mail

O comando mail será usado aqui primeiramente. Ele está contido no pacote mailx, geralmente em todas as distribuições (Debian por exemplo, é o bsd-mailx, Red Hat/Fedora seria apenas mailx). Além disso, é necessário um servidor de e-mail local, o que é comum em todas as distribuições Linux por aí.

Mandando um e-mail com o comando mail, manualmente, via linha de comando:

mail -s "Assunto Teste" se******@do*****.br

O parâmetro -s especifica o assunto da mensagem. Coloque entre aspas como no exemplo para que ele reconheça todo o assunto com espaços. O último argumento é o endereço para quem se vai enviar a mensagem.

Quando você der ENTER, não vai aparecer nada e nem vai voltar pro prompt. Digite então toda a sua mensagem e quando terminar, aperte CTRL+D. Vai aparecer um “Cc:“, que significa que se você quiser enviar cópia para alguém, basta colocar agora. Aperte ENTER e vói-lá! A mensagem foi para o destinatário (bem, pelo menos era pra ir!).

Agora vamos utilizar um modo mais rápido e não-interativo de se mandar o mesmo e-mail:

echo "Isto é um e-mail de teste" | mail -s "Assunto Teste 2" se******@do*****.br

Agora ao invés de você ter que digitar, ele já joga a mensagem “Isto é um e-mail de teste” no corpo e manda o e-mail. Isso serve para você acoplar justamente em um shell script sem ter que precisar que alguém digite alguma coisa na hora.

Mas o echo ainda é limitado para mensagens grandes, então vamos ler de um arquivo:

mail -s "Assunto Teste 3" se******@do*****.br < /var/log/syslog

Ele usou um redirecionador (mais sobre eles no artigo Shell: Entrada e Saída) para que o conteúdo do arquivo /var/log/syslog se tornasse o corpo da mensagem. Mais uma vez, você pode usar um shell-script para gerar o arquivo com o conteúdo que você quiser e depois mandar por e-mail.

Há outros parâmetros no comando mail também. Para ver todos, basta ler a boa e velha página de manual (man mail).

Outro exemplo:

echo 'Maravilha!' | mail -s "Assunto Teste 4" se******@do*****.br \
-c ou********@do*****.br,ma****@do*****.br \
-b es************@do*****.br

Neste caso, mandei um e-mail para se******@do*****.br, com cópia para ou********@do*****.br e ma****@do*****.br (vários e-mails separados por vírgula) e uma cópia oculta para es************@do*****.br.

O comando mail faz parte do sistema padrão de e-mails locais que é utilizado há vários anos pelos sistemas Unix em geral. Por isso, o campo From, ou seja, o Remetente da mensagem vai ser o usuário que está executando o comando, mais o nome completo da máquina. Exemplo, se eu sou o usuário eitch, na máquina batima.devin.com.br, quer dizer que o Remetente será: ei***@ba****.br.

Anexos com o mutt

Como nem tudo são flores, na hora de mandar arquivos anexos junto a mensagem, o comando mail não suporta essa funcionalidade. Neste caso, geralmente o pessoal utiliza o cliente de e-mail de linha de comando mutt.

icon nota Mandar e mail via linha de comando no Linux
NOTAO mutt é na verdade um cliente de e-mail para linha de comando completo. Pode ser que sua distribuição Linux não tenha esse programa instalado. Então se o comando mutt não for encontrado, instale o programa junto à sua distribuição (com o apt-get, yum, ou outros).

O comando é bem parecido com o do mail:

echo "Assunto Anexo" | mutt -s "Assunto Teste 5" -a arquivo.zip se******@do*****.br

O parâmetro -a é quem cuida dos anexos. No caso de enviar vários anexos, é necessário também que o -a fique antes do destinatário, seguido por “–”, assim:

echo "Assunto Anexo" | mutt -s "Assunto Teste 6" \
-a /home/eitch/imagem.jpg /var/log/syslog /home/eitch/arquivo.zip -- hu************@gm***.com

Via um servidor SMTP

Não são todos os sistemas que tem um servidor de e-mail local. Por exemplo, algumas máquinas de hostings não possuem um sendmail, postfix ou qmail instalados e prontos para usar. Em outros casos, organizações preferem ficar sem o servidor de e-mail de cada máquina e concentrar tudo em uma única file de e-mail, um único servidor de e-mail na rede. Este caso do servidor de e-mail único é bem comum.

SMTP – Simple Mail Transfer Protocol é o protocolo para envio de e-mails e um servidor SMTP é justamente o que recebe os e-mails e repassa para outros servidores necessários. Não vou me aprofundar muito no assunto SMTP, mas vamos aprender um pouco como usá-lo diretamente.

icon nota Mandar e mail via linha de comando no Linux
NOTAPara fazer essa parte, você precisa ter um servidor STMP já funcionando. Neste tutorial, usaremos como exemplo o smtp.devin.com.br, que é fictício. Substitua este servidor pelo seu.

Pra enviar o e-mail, vamos primeiro conversar diretamente com o servidor SMTP através do comando nc. O nc é o comando netcat e serve para abrir conexões TCP puras e transferir dados para ela (como se fosse um telnet não-interativo). Se o comando nc não existir na sua máquina, instale-o dos repositórios, já que vem em praticamente todas as distribuições Linux.

Exemplo de script shell para mandar e-mail via nc:

#!/bin/bash
#
cat <<EOF | /usr/bin/nc smtp.devin.com.br 25
HELO $(hostname)
MAIL FROM: <hu**@de***.br>
RCPT TO: <de*****@do*****.br>
DATA
From: Hugo Cisneiros (Eitch) <hu**@de***.br>
To: Nome do Destino <de*****@do*****.br>
Date: $(date '+%a, %d %b %Y %H:%M:%S %z')
Subject: Assunto da mensagem
Content-Type: text/plain; charset=UTF-8
                                                                                                                                                                                              
Fala Destinatário!
Estou mandando este e-mail via shell script, usando o nc diretamente pelo SMTP.
Legal né?
Abraços!
.
QUIT
EOF

O que fizemos no exemplo é conversar usando o protocolo SMTP.

  • Na linha 3 usamos o comando cat para capturar tudo o que digitarmos, até haver uma linha EOF (End Of File). Pense nisso como se fosse um comando echoextendido. Depois repassamos todo esse texto via pipe para o comando nc smtp.devin.com.br 25, que conecta ao servidor SMTP na porta 25. Para aprender mais sobre o pipe veja o Shell: Entrada e Saída;
  • A linha 4 identifica quem é você. O comando hostname identifica-o com o nome da sua máquina;
  • As linhas 5-6 contém de quem é o e-mail (MAIL FROM) e qual o destino (RCPT TO);
  • A linha 7, com o comando DATA, especifica que tudo que tiver a partir da próxima linha serão os dados do e-mail. Estes dados terminam quando houver uma linha apenas com o caracter ponto (.), que vai significar que o e-email acabou e pode ser mandado;
  • As linhas 8-12 contém o cabeçalho do e-mail. Cada cabeçalho é uma linha. No exemplo temos o nome da pessoa que enviou, do destinatário, a data atual (gerada automaticamente pelo comando date), o assunto (Subject) da mensagem e a codificação da mensagem (para a acentuação do português) não sair estranha. Os cabeçalhos acabam quando uma linha em branco é recebida;
  • As linhas 14-20 são o corpo da mensagem. Engloba tudo depois da linha em branco que finaliza o cabeçalho, até o caracter ponto que termina o e-mail.
  • A linha 21, já falada, termina o e-mail. Ao receber o ponto, o servidor SMTP já coloca a mensagem na fila para o envio. A partir daí você pode enviar outro e-mail (começando com o MAIL FROM), ou sair, como na próxima linha com o comando QUIT.
  • Na última linha, o EOF avisa ao cat que acabou o texto e o manda para o comando nc, como diz a linha 3.

Até que é fácil né? Basta agora ir substituindo os campos de e-mail e testando. Esse método com o comando nc é o ideal para utilizar junto com shell-scripts em servidores. Ele só não serve muito bem para mandar anexos, pois transformar os anexos para mandar via nc não é algo trivial de se fazer.

porplague70

Instalação do Zabbix 3.0.x/3.2.x/3.4 no Debian 8 Jessie

O Zabbix é uma solução de nível enterprise, de código aberto. O Zabbix é um software que monitora vários parâmetros da rede, dos servidores e da saúde dos serviços. Utiliza-se de um mecanismo flexível de notificação que permite configurar alertas por e-mail entre outros como Telegram, para praticamente qualquer evento. As notificações permitem que se reaja rapidamente à problemas no ambiente. O Zabbix oferece excelentes recursos de relatórios e visualização de dados armazenados. Isso faz com que o Zabbix seja a ferramenta ideal para planejamento de capacidade.

Distribuição utilizada: Debian 8 (Jessie) / Instalação Limpa (Tutorial de instalação aqui)

Vamos a instalação do pacote que irá atualizar nosso repositório com as fontes do Zabbix assim vai ficar fácil atualizar posteriormente.
Versão 3.4.X

# wget http://repo.zabbix.com/zabbix/3.4/debian/pool/main/z/zabbix-release/zabbix-release_3.4-1+jessie_all.deb
# dpkg -i zabbix-release_3.4-1+jessie_all.deb

Versão 3.2.X

# wget http://repo.zabbix.com/zabbix/3.2/debian/pool/main/z/zabbix-release/zabbix-release_3.2-1+jessie_all.deb
# dpkg -i zabbix-release_3.2-1+jessie_all.deb

Versão 3.0.X

# wget http://repo.zabbix.com/zabbix/3.0/debian/pool/main/z/zabbix-release/zabbix-release_3.0-1+jessie_all.deb
# dpkg -i zabbix-release_3.0-1+jessie_all.deb

Atualize o repositório:

# apt update

Instalando os pacotes do Zabbix Server com banco de dados MySQL e interface web Apache.

# apt install zabbix-server-mysql zabbix-frontend-php

screenshot_20160910_191607

Serão instalados diversos pacotes entre eles o apache e mysql-server.

screenshot_20160910_191808

Será solicitado a senha do usuário root do MySQL, após repita.

screenshot_20160910_191819

Vamos intalar nosso agente também.

# apt install zabbix-agent

Vamos criar uma base de dados chamada zabbix e um usuário também chamado de zabbix no MySQL.

# mysql -uroot -p
1
2
3
create database zabbix character set utf8 collate utf8_bin;
grant all privileges on zabbix.* to zabbix@localhost identified by 'SENHA';
quit;

Importe o esquema de tabelas e dados padrões.

# cd /usr/share/doc/zabbix-server-mysql
# zcat create.sql.gz | mysql -u root zabbix -p

Digite a senha de seu usuário zabbix criada no passo anterior para importar as tabelas.

Agora vamos editar o arquivo zabbix_server.conf para informar os dados para conexão com o MySQL.

# vim /etc/zabbix/zabbix_server.conf
1
2
3
4
DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=SENHA

Iniciando o Zabbix Server e o Agente.

# /etc/init.d/zabbix-server start
# /etc/init.d/zabbix-agent start

Editando a configuração do PHP para a interface web do Zabbix

A configuração do Apache para a interface web do Zabbix está localizada em /etc/apache2/conf-enabled/zabbix.conf. Algumas das configurações do PHP já estão definidas, para alterar edite:

# vim /etc/apache2/conf-enabled/zabbix.conf
1
2
3
4
5
6
7
php_value max_execution_time 300
php_value memory_limit 128M
php_value post_max_size 16M
php_value upload_max_filesize 2M
php_value max_input_time 300
php_value always_populate_raw_post_data -1
php_value date.timezone America/Sao_Paulo

É necessário que se remova o comentário na linha do parâmetro “date.timezone” e que se defina o timezone apropriado (America/Sao_Paulo para a maioria dos estados brasileiros). Após a alteração do arquivo de configuração será necessário o reinicio do processo do servidor web (Apache).

# /etc/init.d/apache2 restart

A interface web do Zabbix estará disponível em http://SEU-IP/zabbix através do seu navegador.
O usuário e senha padrões são: Admin/zabbix

screenshot_20160910_193954

[Next step]

screenshot_20160910_194002

Tudo deve estar ok [Next step]

screenshot_20160910_194011

Informe sua senha de conexão ao MySQL. [Next step]

screenshot_20160910_194018

[Next step]

screenshot_20160910_194024

[Next step]

screenshot_20160910_194028

[Finish]

screenshot_20160910_194043

Usuário: Admin Senha: zabbix

screenshot_20160910_194105

Zabbix instalado! ?