domingo, 17 de maio de 2009

Como construir uma antena Wirelless de mais ou menos 11 dBi


Construção de Antena

Esta página detalha a construção de uma antena de biquad. A antena de biquad é fácil de construir e fornece um ganho de 11dBi, com um beamwidth bastante amplo.

Background

Eu fiz um pouco de experimentação e testes com vários dipoles feitas para pratos de conífera 24dBi e tenham conseguido aumentar o desempenho do prato.
Trevor Marshall tem uma página da Web com informações sobre como usar um biquad como um feed sobre uma antena de satélite de Primestar, com muito bons resultados.

Decidi tentar usar um biquad como um feed sobre um prato de conífera 24dBi, para ver se eu poderia melhorar o desempenho do prato.

Observe que as fotos da Trevor Marshall na página da Web não mostram claramente a construção de biquad - particularmente da forma em que acompanha o cabo coaxial. Numerosas pessoas (inclusive eu) terem construído biquads incorrectamente, com base em suas fotos e encontrado dificuldades.
Use as fotos do meu biquad abaixo e remeter para os sites listados na seção referências na parte inferior desta página para obter mais informações sobre a construção correcta do biquad.

Partes necessárias
Usei as seguintes peças:
  • 123x123mm seção quadrado do PCB em branco
  • Comprimento de 50 mm de 1/2 "cobre pipe
  • Comprimento curto de CNT-400 ou LMR-400 coaxial de pouca perda (~ 300 mm longo)
  • 250 mm de fios de cobre de 2.5mm2 (aproximadamente 1,5 mm de diâmetro)
  • Conector N
Note que você não tem de usar PCB em branco para o reflector. Você pode usar qualquer material que electricamente condutoras, podem ser conectadas electricamente a braid coaxial e reflectirá microondas (ie, qualquer placa de metal fará coima).
Eu também já ouvi de pessoas usando o CD-ROM como o reflector, como foil sobre ele certamente refletirá microondas.

Reflector
Cut a square piece of blank printed circuit board, 123x123mm.

Note that Trevor Marshall recommends a size of 123x123mm if using the biquad as a stand-alone antenna, while 110x110 is optimal if using it as a feed for a large dish.
He also recommends attaching some lips to two sides of the reflector, to reduce radiation from the rear lobes.

Use some steel wool to remove any tarnish and polish it up. Cleaning the copper in this way will make it easier to solder.


blank printed circuit board

Cut a 50mm section of copper pipe, and file both ends smooth. Using some sandpaper and/or some files, polish up the copper pipe (including the inside of the copper pipe, to ensure a good connection with the coax braid).


the dimensions of the copper pipe

Cut a notch into one end of the copper pipe, removing approx 2mm from half the circumference.


a short secion of copper pipe, notched at one end

Drill a hole in the centre of the blank PCB so that the copper pipe is a tight fit in the hole. I found a reamer to be very useful for enlarging the hole to the correct size.


making a hole in the centre

Insert the copper pipe into the hole, with the notched end on the copper side of the blank PCB. The copper pipe should be protruding approx 16mm through the hole, measured on the copper side of the PCB.


insert the copper pipe into the reflector

Solder the copper pipe to the PCB, to ensure a good physical and electrical connection.


solder the copper pipe to the PCB

Quite a bit of heat is needed, due to the thickness of the copper pipe, and an electrical soldering iron probably won't be able to deliver sufficent heat. I found a small gas torch works quite well.


Making the Element
The element is made from a length of copper wire, bent into the appropriate shape.

Note that the length of each "side" should be as close to 30.5mm as possible (measured from the centre of the copper wire to the centre of the copper wire), which is a quarter of a wavelength at 2.4GHz


the shape and dimensions of the element

I had some offcuts of electrical power cable lying around, and found that 2.5mm2 power cable had a diameter of approx 1.6mm - a little bigger than the 1.2mm that Trevor Marshall specifies, but didn't think it would make a significant difference to the performance of the biquad.


recycling power cable offcuts

Remove the insulation, measure and cut a 244mm length the copper wire, and straighten it as best as you can.


straighten the wire

Measure the mid-point of the wire, and make a 90 degree bend. The bend should be quite sharp and pronounced.


90 degree bend

Measure the midpoints of each half, and make two more 90 degree bends in the wire, so that it looks like that shown in the photo below.


another two bends

Once again, measure the midpoints of each section, and make some more 90 degree bends, resulting in what is shown below.


bend it some more...

Do the same to the other side, resulting in the biquad shape.


make it symetrical...

Clean up all your bends, and ensure each side of the element is as straight as possible, and as close to 30.5mm as possible.
Note that you may need to trim a small amount off each end of the wire to achieve this.

Assembly
The element must now be attached to the reflector. Note that only the two "ends" of the copper wire are to be attached to the copper pipe - the centre of the copper wire must not touch the copper pipe (hence the notch which was cut into the end of the copper pipe.

The copper wire element should be approximately 15mm away from the reflector. Testing antenna performance while varying the spacing between the copper wire element and the rear reflector indicates that a spacing of approx 15mm provides the lowest SWR (test results available here).


the element soldered onto the copper pipe

Strip approx 30mm of the outer sheath from the end of the coax.


strip the outer sheath

Fold the braid back over the outer sheath, and trim the centre conductor, so that about 4mm is protruding.


fold the braid back, trim the centre conductor

Insert the braid into the copper pipe, so that the end of the centre conductor lines up with the extreme end of the copper pipe, and solder the centre of the element to it, ensuring the centre of the element is not in contact with the copper pipe. Refer to some of the additional photos below for details.


solder the centre conductor to the element


another view

Note that the feed between the rear reflector and the biquad element needs to be shielded. Using coax to feed the biquad element directly, and positioning the coax inside the copper tube achieves this.
Use of bare conductors as a feed between the reflector and biquad element results in a radiating feed (such as this one), which will have a detrimental effect on the biquad's performance.

I used a coax crimper to crimp the end of the copper pipe onto the coax. This ensures that the coax would not move inside the copper pipe.


the copper pipe crimped onto the coax


the completed biquad

Now terminate the other end of the coax with an N connector.

If desired, you can add spacers at each end of the element, to ensure the element doesn't move in relation to the reflector. Refer to my double biquad page for more details on making spacers to support the element.

If you intend to mount the biquad outside, I'd recommend you place it into a weather-proof enclosure, to prevent corrosion, and to prevent water ingress into the coax.
Numerous people have used small tuppaware containers successfully.

This can be achieved by drilling a hole in one side of the container, and pass the coax tail through the hole, leaving the biquad itself inside the container. Seal up the hole for the coax with some silicone, and your biquad should be protected against the elements.


another view of the completed biquad


Testing
Some very rough initial testing using the biquad as a feed on a 24dBi Conifer dish looks very promising, with the signal strength being at least as as good as my home made Conifer dipole (I was holding the biquad at approximately the focal point of the dish, and hadn't even removed the Conifer dipole).

I also managed to get a marginal link to a 180 degree waveguide on an access point 10km away, using only the biquad by itself, connected to a 30mW RoamAbout wireless card.

Some more detailed testing with multiple antennas, including the biquad shown above, indicates the biquad has a gain of approx 11-12dBi.

A friend has access to some antenna test equipment, and performed some tests on the biquad featured on this page.
The azimuth plot (ie, radiation pattern) of the biquad is shown below, and shows a 3dB beamwidth of about 50 degrees.


azimuth plot of the biquad

Variations
A number of people have suggested the spacing between the element and the rear reflector should be a 1/4 wavelength (ie, 30.5mm) instead of 15mm. However, test results (such as these) indicate the SWR of the biquad is minimised when the spacing is about 15-17mm. Increasing the spacing to 30.5mm increases the SWR significantly, thus reducing the efficiency of the biquad.

For a higher-gain variation of the biquad that's virtually just as easy to build, have a look at the double biquad.

Usage
When using a biquad to establish a link to another wireless device, you should ensure the polarisation of the biquad is the same as the antenna you are connecting to. Similarily, if establishing a link with two biquads, ensure they are both oriented for the same polarisation.
Failing to match the polarisation will result in significant signal loss.


vertically polarised


horizontally polarised

Changing the polarisation is just a matter of rotating the entire biquad antenna by 90 degrees.

The biquad antenna is not particularly directional, but has a fairly wide beamwidth.
The 3dB beamwidth for a biquad (without side lips) is typically about 40-50 degrees, thus making it ideal for any applications where you want fairly wide coverage.

The relatively wide beamwidth also makes a biquad very suitable for war-driving and stumbling, allowing you to pick up signals without having to align the antenna directly with the signal source.

While a directional antenna, such as a Conifer dish (3dB beamwidth of a 24dBi Conifer dish is approx 7 degrees), is better suited for point-to-point links, the narrow beamwidth of a Conifer dish requires more precision when aligning the antennas (the narrower the beamwidth, the less susceptible it will be to interferance from other sources). An antenna with a wider beamwidth, such as a biquad, doesn't require the same precision for alignment, thus making it easier to get a link working.

Kits
If you're one of those people who may not have all the tools required for building a biquad antenna from scratch, or you don't want to shop around for all the parts required, you can buy a DIY kit containing all components from WarDrivingWorld.

In November 2006, WarDrivingWorld sent me one of their DIY biquad kits to review. The kit contains all the pre-cut and pre-drilled parts required to build a biquad antenna.

terça-feira, 5 de maio de 2009

Sarg 2.2.5 - Gerador de relatórios para o Squid - Debian Lenny









Configure o Sarg


Abra o arquivo /etc/squid/sarg.conf e atualize para:

# /etc/squid/sarg.conf
#
# *** Idioma
language Portuguese
#
# *** Arquivo de log a ser lido para gerar relatório
access_log /var/log/squid/access.log
#
#*** Usar Gráfico - yes | no
graphs yes
#
# *** Título da pagina HTML
title "Relatorio de uso da Internet"
#
# *** Fonte da pagina HTML
font_face Tahoma,Verdana,Arial
#
# *** Nome do diretorio temporário dos arquivos em trabalho
# sarg -w dir
temporary_dir /tmp
#
# *** Diretório onde serão salvos os relatórios
# sarg -o dir
output_dir /var/www/squid-reports
#
# *** Converte IP em DNS (nome) - yes | no
# sarg -n
resolve_ip
#
# *** Usa IP ao inves de userid nos relatórios - yes | no
# sarg -p
user_ip no
#
# *** Ordena - normal | reverse
# Campos permitidos: USER | CONNECT | BYTES | TIME
topuser_sort_field BYTES reverse
#
# *** Usuarios contidos no sarg.users São excluídos do relatório
exclude_users /etc/squid/sarg.users
#
# *** Exclui host, domínios ou subredes do relatório
# Ex: 192.168.10.10 - exclui ip apenas
# 192.168.10.0 - exclui toda classe C
# s1.acme.foo - exclui hostname apenas
# acme.foo - exclui tod domínio
exclude_hosts /etc/squid/sarg.hosts
#
# *** Formata a data do relatório
# e (European=dd/mm/yy)
# u (American=mm/dd/yy)
# w (Weekly=yy.ww)
date_format e
#
# *** Remove relatórios antigos automaticamente
# 0 - sem limites.
lastlog 0
#
# *** Remove os arquivos temerários
remove_temp_files yes
#
# *** Gera o index.html - yes | no | only
# only - gera apenas um unico index.html principal
index yes
#
# *** Sobrescrever relatório - yes | no
overwrite_report yes
#
# *** O que fazer com registros sem identificação no access.log
# ignore - Ignora os registros
# ip - Usa o IP
# everybody - Usa o texto "everybody"
records_without_userid ip
#
# *** Usa vírgula ao invés de ponto no | yes
use_comma yes
#
# *** Comando para enviar relatório via SMTP - mail|mailx
mail_utility mailx
#
# *** Quantidade de sites do relatório topsites
topsites_num 100
#
# *** Ordena os topsites - CONNECT|BYTES A|D
# Onde A=Crescente, D=Descendente
topsites_sort_order CONNECT D
#
# *** Ordena o index.html - A | D
# Onde A=Crescente, D=Descendente
index_sort_order D
#
# *** Ignora registros com alguns códigos
# Ex: NONE/400
exclude_codes /etc/squid/sarg.exclude_codes
#
# *** Máximo de tempo decorrido (milliseconds)
# Use 0 para nao checar
max_elapsed 28800000
#
# *** O que os relatorios geram:
# topsites - exibe o site, conexao e bytes
# sites_users - exibe que usuario esteve num site
# users_sites - exite site acessados pelo usuario
# date_time - exibe a quatidade de bytese num dia/h
# denied - exibe todos os sites negados
# auth_failures - exibe as falhas nas autenticacoes
# site_user_time_date - exibe sites, datas, tempo e bytes
# Ex.: report_type topsites denied
#
report_type topsites sites_users users_sites date_time denied auth_failures site_user_time_date
#
# *** Troca o IP ou userid pelo nome do usuario no relatorio
# Ex:
# SirIsaac Isaac Newton
# vinci Leonardo da Vinci
# 192.168.10.1 Karol Wojtyla
# Cada linha precisa terminar com ' ' (enter)
usertab /etc/squid/sarg.usertab
#
# *** Exibe a URL longa ou so o site - yes | no
long_url no
#
# *** Data/Hora ou Tempo decorrido - bytes | elapsed
date_time_by bytes
#
# *** Padroes de multilinguagem
# Voce pode usar os seguintes caracteres:
# Latin1 - West European
# Latin2 - East European
# Latin3 - South European
# Latin4 - North European
# Cyrillic
# Arabic
# Greek
# Hebrew
# Latin5 - Turkish
# Latin6
# Windows-1251
# Koi8-r
charset Latin1
#
# *** Gera relatorios apenas dos usuarios listados
# Ex: include_users "user1:user2:...:usern"
#include_users none
#
# *** Gera relatorio ignorando uma lista de string
# Ex: exclude_string "string1:string2:...:stringn"
#exclude_string none
#
# *** Exibe mensagem de sussesso do relatorio gerado-yes|no
show_successful_message no
#
# *** Exibe a leitura de algumas estatisticas
show_read_statistics no
#
# *** Quais campos devem ser do relatorio Topuser
topuser_fields NUM DATE_TIME USERID CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
#
# *** Quais campos devem ser do relatorio User
user_report_fields CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
#
# *** Quantidade de usuarios do relatorio Topsites
# 0 = sem limites
topuser_num 0
#
# *** Gera relatorio em formato de lista ou tabela-list|table
site_user_time_date_type table
#
# *** Salva o resultado do relatorio em um arquivo
#datafile /tmp/p8
#
# *** Usa um caracter separador dos campos no arquivo
#datafile_delimiter ";"
#
# *** Quais campos de dados devem ter o arquivo
# Ex: datafile_fields all ou user
# Campos permitidos:
# user;date;time;url;connect;bytes;
# in_cache;out_cache;elapsed
#datafile_fields
#user;date;time;url;connect;bytes;in_cache;out_cache;elapsed
#
# *** Dias da semana levados em conta (Domingo->0,Sabado->6)
# Ex: weekdays 1-3,5
#weekdays 0-6
#
# *** Horas levadas conta
# Ex: hours 7-12,14,16,18-20
#hours 0-23
#
# *** Gera um relatorio para o log do SquidGuard
# Ex: squidguard_conf /usr/local/squidGuard/squidGuard.conf
#squidguard_conf none
#
# *** Exibe informacoes do sarg e site no relatorio - yes|no
#show_sarg_info yes
#
# *** Exibe logotipo do sarge - yes|no
show_sarg_logo yes
#
# *** Onde esta seus documentos Web
#www_document_root /var/www
#
# *** Sufixo de arquivos considerados como dowloads no
# relatorio de downloads. Use 'none' para desabilitar
download_suffix "zip, arj, bzip, gz, ace, doc, iso, adt, bin, cab, com, dot, drv$, lha, lzh, mdb, mso, ppt, rtf, src, shs, sys, exe, dll, mp3, avi, mpg, mpeg"

Para gerar relatórios, vá ao terminal e digite:

# sarg

OBS: Abra com o browser o arquivo squid-reports gerado em /var/www/ ou abra o browser (firefox) e digite http://localhost/squid-reports.


Configurando o Squid 2.7 (Proxy Transparente) - Debian Lenny


Abra o arquivo /etc/squid/squid.conf e atualize para: 

# Configuração Geral
#*******************
#
http_port 3128 transparent
cache_mem 32 MB
cache_dir ufs /var/spool/squid 100 16 256
cache_access_log /var/log/squid/access.log
cache_log /var/log/squid/cache.log
cache_store_log /var/log/squid/store.log
pid_filename /var/run/squid.pid
error_directory /usr/share/squid/errors/Portuguese
emulate_httpd_log on
visible_hostname servidor.4pef
cache_mgr taylor@pop.com.br
#
# acl - Recomendadas
#*******************
#
acl all src 0.0.0.0/0.0.0.0
acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl SSL_ports port 443 563 # https, snews
acl SSL_ports port 873 # rsync
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 563 # https, snews
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl Safe_ports port 631 # cups
acl Safe_ports port 873 # rsync
acl Safe_ports port 901 # SWAT
acl purge method PURGE
acl CONNECT method CONNECT
#
# acl - Personalizadas
#*********************
#
# *** Define portas liberadas
acl Safe_ports port 3050 # Interbase/Firebird
acl Safe_ports port 23000 # Serpro
acl Safe_ports port 13352 # SIRF
acl Safe_ports port 500 # FAP Digital
#
# *** Define a rede interna (Intranet)
acl intranet src 10.0.0.0/255.0.0.0
#
# http_access - Recomendadas
#***************************
#
http_access allow manager localhost
http_access deny manager
http_access allow purge localhost
http_access deny purge
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
#
# http_access - Personalizadas
#*****************************
#
# *** Libera dowloads de ate 5 MB
reply_body_max_size 5242880 allow all !admin
#
# Permite acesso da rede interna (Intranet)
http_access allow intranet
#
# *** Nega tudo que não foi liberado ou negado
http_access deny all

Reinicie o squid: 

# squid -k reconfigure
(atualiza sem parar o serviço) 

Ou: 

# /etc/init.d/squid restart 

Iptables Firewall


Utilizaremos o iptables para: 

1) Proxy Transparente - Redirecionar o fluxo da porta 80 (http) para a porta 3128 (squid); 

2) Compartilhar a Internet; 

Para isto, crie o arquivo que conterá as regras: 

# touch /etc/init.d/iptables.conf
# chmod 755 /etc/init.d/iptables.conf
 

Abra o arquivo /etc/etc/init.d/iptables.conf e atualize para: 

#!/bin/bash
#
# /etc/etc/init.d/iptables.conf 
#
# Limpa e inicializa os modulos
#******************************
#
iptables -F
iptables -t nat -F
iptables -t mangle -F
modprobe iptable_nat
#
# Proxy transparente (Redireciona para o squid) - eth1 -> Placa de rede da intranet
#********************************************************
#
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 3128
#
# Compartilha Internet - eth0 -> Placa de rede da internet
#********************************************************
#
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward

Coloque o iptables.conf para rodar na inicialização: 

# cd /etc/rc2.d
# ln -s /etc/init.d/iptables.conf /etc/rc2.d/S99iptables.conf
 

Inicie o serviço: 

# /etc/init.d/iptables.conf 

Configurando duas placas de redes no Debian Lenny


Configure as placas de redes do servidor (deve haver duas)

Defina um IP fixo e máscara de rede para as duas placas de redes: 

Fica convencionado:
  • eth0 (internet) - inet 192.168.0.2 masca 255.255.255.0 (Recebe a Internet)
  • eth1 (intranet) - inet 10.0.0.1 masc 255.0.0.0
Perceba que, pelo exemplo acima, os computadores da rede deverão ter IP fixo 10.0.0.2, 10.0.0.3, 10.0.0.n. No nosso caso em particular, tais IPs fixos serão atribuídos pelo DHCP, sem a necessidade de configuração no cliente. 

Abra o arquivo /etc/network/interfaces e atualize para: 

# /etc/network/interfaces
#
# Interface de rede local - loopback
#***********************************
auto lo
iface lo inet loopback 
#
# Primeira placa de rede - Internet
#**********************************
# auto eth0
# iface eth0 inet dhcp
auto eth0
iface eth0 inet static
address 192.168.0.2
netmask 255.255.255.0
broadcast 192.168.0.255
network 192.168.0.0
gateway 192.168.0.1 # IP do roteador
#
# Segunda placa de rede - Intranet
#*********************************
auto eth1
iface eth1 inet static
address 10.0.0.1
netmask 255.0.0.0
broadcast 10.255.255.255
network 10.0.0.0
Reinicie a rede: 

# /etc/init.d/networking restart 


Utilizando o crontab


Mais uma super dica garimpada na internet pelo www.redesconexao.blogspot.com

Como utilizar o cron e os arquivos crontab para automatizar as tarefas do Linux, agendando qualquer tipo de coisa. Ótimo para quem quer poupar tempo e trabalho!

O “cron” é um programa de “agendamento de tarefas”. Com ele você pode programar para ser executado qualquer coisa numa certa periodicidade ou até mesmo em um exato dia, numa exata hora. Um uso bem comum do cron é o agendamento de tarefas administrativas de manutenção do seu sistema, como por exemplo, procura por links simbólicos quebrados, análise de segurança do sistema, backup, entre outros. Estas tarefas são programadas para todo dia, toda semana ou todo mês, serem automaticamente executadas através do crontab e um script shell comum. A configuração do cron geralmente é chamada de crontab.

Os sistemas Linux possuem o cron sempre presente. Pelo menos eu nunca vi nenhuma distribuição que não incluísse o tão útil cron. A configuração tem duas partes: Uma global, e uma por usuário. Na global, que é o root quem controla, o crontab pode ser configurado para executar qualquer tarefa de qualquer lugar, como qualquer usuário. Já na parte por usuário, cada usuário tem seu próprio crontab, sendo restringido àpenas ao que o usuário pode fazer (e não tudo, como é o caso do root).

Para configurar um crontab por usuário, utiliza-se o comando “crontab“, junto com um parâmetro, dependendo do que você quiser fazer. Abaixo uma relação:

ComandoFunção
crontab -eEdita o crontab atual do usuário
crontab -lExibe o atual conteúdo do crontab do usuário
crontab -rRemove o crontab do usuário

Se você quiser verificar os arquivos crontab dos usuários, você precisará ser root. O comando crontab coloca os arquivos dos usuários no diretório:

/var/spool/cron/usuario

Onde “usuario” corresponde ao usuário dono do arquivo crontab.

Agora se você quiser editar o crontab global, este fica no arquivo “/etc/crontab“, e só pode ser manipulado pelo root. E agora que já sabemos onde ficam os arquivos de configuração, vamos estudar o formato da linha do crontab, que é quem vai dizer o que executar e quando. Vamos ver um exemplo:

0 4 * * * who

Então como se pode ver, a linha é dividida em 6 campos separados por tabs ou espaço:

CampoFunção
1o.Minuto
2o.Hora
3o.Dia do mês
4o.Mês
5o.Dia da semana
6o.Programa para execução

Todos estes campos, sem contar com o 6o., são especificados por números. Veja a tabela abaixo para os valores destes campos:

CampoValores
Minuto0-59
Hora0-23
Dia do mês1-31
Mês1-12
Dia da semana0-6 (o “0″ é domingo), 1 é segunda, etc.

Então o que nosso primeiro exemplo estava dizendo? A linha está dizendo: “Execute o comando ‘who’ todo dia de todo mês sendo o dia qualquer dia da semana, às 4 horas e 0 minutos.“. Vamos pegar mais exemplos para analisar:

1,21,41 * * * * echo "Meu crontab rodou mesmo!"

Aqui está dizendo: “Executar o comando do sexto campo toda hora, todo dia, nos minutos 1, 21 e 41“.

30 4 * * 1 rm -rf /tmp/*

Aqui está dizendo: “Apagar todo conteúdo do diretório /tmp toda segunda-feira, as 4:30 da manhã.“.

45 19 1,15 * * /usr/local/bin/backup

Aqui está dizendo: “Executar o comando ‘backup’ todo dia 1 e 15 às 19:45.“.

E assim você pode ir montando inúmeros jeitos de agendamento possível. No arquivo do crontab global, o sexto campo pode ser substituído pelo nome do usuário, e um sétimo campo adicionado com o programa para a execução, como mostro no exemplo a seguir:

0-59/5 * * * * root /usr/bin/mrtg /etc/mrtg/mrtg.cfg

Aqui está dizendo: “Executar o mrtg como usuário root, durante 5 e 5 minutos dos minutos 0-59. Ou seja, executar de 5 em 5 minutos o mrtg sempre.“.

Em alguma distribuições, os agendamentos mais comuns estão programados para serem executados. Veja as linhas abaixo:

01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly

O programa “run-parts” executa todos os scripts executáveis dentro de um certo diretório. Então com essas linhas, temos diretórios programados para executar programas de hora em hora, diariamente, semanalmente ou mensalmente. Abaixo a tabela:

DiretórioPeríodo
/etc/cron.hourlyDe hora em hora
/etc/cron.dailyDiariamente
/etc/cron.weeklySemanalmente
/etc/cron.monthlyMensalmente

Então todos os arquivos executáveis dentro de cada diretório serão executados no seu correspondente período. Ou seja, posso colocar um certo conteúdo no arquivo “/etc/cron.daily/teste“, depois torná-lo executável através do comando “chmod +x /etc/cron.daily/teste“, e então ele será executado todo dia as 4:02 da manhã.

Bem é isso! Agora você já pode programar suas tarefas para serem automaticamente executadas e te poupar muito trabalho manual.