Minha caixa de ferramentas no GNU/Linux

Neste artigo apresento um apanhado de scripts que uso em meu cotidiano com GNU/Linux.

[ Hits: 51.903 ]

Por: Fábio Berbert de Paula em 06/06/2012 | Blog: https://www.instagram.com/alexabolada/


Introdução



Todo sysadmin possui sua própria coleção de scripts úteis (ou não). No meu caso utilizo scripts que vão do auxílio na manutenção de servidores remotos à conversão de formatos de vídeo.

Pensando em quão amigos eles são (os scripts), resolvi abrir minha caixa de ferramentas e compartilhá-la com a comunidade.

Na pior das hipóteses, se por acaso nenhum dos scripts lhe for útil, pelo menos o artigo servirá de backup de meus códigos. Se por acaso eu perder meus dados ou for instalar um novo desktop, posso consultar este texto e baixar minhas ferramentinhas novamente. :)

Acompanhando entregas dos Correios

Vez ou outra posto camisetas pelos Correios. Para acompanhar o andamento da entrega uso o seguinte script:

#!/bin/bash
#
# Script para rastreamento de objetos nos correios
# Desenvolvendor: Jamilson S. Carmo - 08/07/09 às 16:30hs
#
# Caso você não use proxy retirar o parâmetro -pauth="jamilson:ViViane" da linha do lynx, caso use proxy somente troque o usuário e a senha
# As vezes o site de busca dos correios fica fora do ar, com isso não retornando nada.

# Código para teste: RE419472475BR

http_proxy="http://fabio:jedipass@174.123.53.162:33128"
export http_proxy

endereco="http://websro.correios.com.br/sro_bin/txect01$.inexistente?p_itemcode=&p_lingua=001&p_teste=&p_tipo=003&z_action=&p_cod_lis=$1"
site=$(lynx -pauth="fabio:jedipass" -dump $endereco | grep -A 2 [0-3][0-9]\/[0-1][0-9]\/"20"[0-1][0-9]\ [0-2][0-9]\:[0-5][0-9])


if [ "$endereco" = "" ]; then
   echo -e "\nSite temporariamente fora do ar!\n"
   exit 1
fi

if [ -e `which lynx` ]; then
   if [ $# -eq 1 ]; then
      echo -e "\n"
      
      if [ "$site" != "" ]; then
         echo -ne "$site"
      else
         echo -ne "Objetos não encontrados \nCódigo: $1"
      fi
  
      echo -e "\n\n"
   else    
      echo -ne "\nInforme o código para rastrear o produto. Ex.: RE419472475BR\n\n"
   fi  
else
   echo -e "\nVocê precisa instalar o lynx\n"
   echo -e "Como instalar o lynx: "
   echo -e "  --Debian/Ubuntu: apt-get install lynx"
   echo -e "  --Arch Linux: pacman -S lynx"
   echo -e "  --Fedora: yum install lynx"
   echo -e "  --Gentoo: emerge lynx\n"
fi

Download: correios.sh

Exemplo de uso:

./correios.sh PB501392125BR

   27/04/2012 17:42 CEE RECIFE - RECIFE/PE                  Entrega Efetuada
   27/04/2012 13:16 CEE RECIFE - RECIFE/PE                  Saiu para entrega
   27/04/2012 12:34 CTE RECIFE - RECIFE/PE                  Encaminhado
                    Encaminhado para CEE RECIFE - RECIFE/PE
   19/04/2012 15:07 ACF AUGUSTO CARDOSO - NOVA FRIBURGO /RJ Encaminhado
                    Em trânsito para CTE BENFICA - RIO DE JANEIRO/RJ
   19/04/2012 10:56 ACF AUGUSTO CARDOSO - NOVA FRIBURGO /RJ Postado


Verificando lista de e-mails válidos

Você precisa enviar uma newsletter, tem um arquivo com uma lista de e-mails e precisa verificar quais deles são endereços válidos.

#!/usr/bin/perl
#
# # check_email.pl
# # Recebe um arquivo contendo uma lista de e-mails separados por
# # quebra de linha e um servidor de DNS e retorna somente endereços válidos com MX válidos.
# # Date == begin == 16/09/03
# # Produced by  -->
# #
# #      .....
# #   ,,$$$$$$$$$,    Alberto Pereira  
# #  ;$'      '$$$$:  Analista de suporte
# #  $:         $$$$:  
# #   $       o_)$$$: -"E ai linux, o que faremos hoje a noite??"
# #   ;$,    _/\ &&:' -"O que fazemos todas as noites link,
# #     '     /( &&&    tentaremos dominar o mundo"
# #         \_&&&&'    
# #        &&&&.      -DEBIAN, THE CHOICE OF NEW GNU LINUX GENERATION!!!!
# #  &&&&&&&:          
# #
# # No Debian Woody necessários instalar os seguintes pacotes:
# # apt-get install libemail-valid-perl libnet-dns-perl
#

use strict;
use Net::DNS;
use Mail::Address;

my $file = shift or die "Use: $0 arquivo servidor\n";
my $nameserver = shift or die "Use: $0 arquivo servidor\n";

if (! -f $file) {
   print "Erro: $file não é um arquivo válido!\n";
}


my $res = Net::DNS::Resolver->new;

$res->nameservers($nameserver);

open(READ, $file);

while(<READ>) {
   chomp;
   my @addrs = Mail::Address->parse($_);
   foreach my $addr (@addrs) {
      my $no = 0;
      my $user = $addr->user;
      my $domain = $addr->host;
      if ($user =~ m/[a-zA-Z0-9_\.\-]/g) {
         if ($user =~ m/\//g) { $no = 1;}
         if ($domain =~ m/[a-zA-Z0-9\.\-]/g) {
            if ($domain =~ m/\//g) { $no = 1; }
            if ($domain =~ m/\.$/g) { $no = 1; }
            if ($domain =~ m/^\./g) { $no = 1; }
            if ($domain =~ m/\'/g) { $no = 1; }
             my @mx = mx($res, $domain);
             if (!@mx) { $no = 1;}
             print $addr->format,"\n" if (!$no);
         }
      }
   }
}

Download: check-mail.pl

Exemplo de uso:

./check-mail.pl emails.txt

Onde emails.txt é um arquivo texto que contém a lista de e-mails, um por linha.

    Próxima página

Páginas do artigo
   1. Introdução
   2. Convertendo ISO8859-1 em UTF-8 e substituição de strings em arquivos
   3. PageRank e localidade geográfica de um IP
   4. Monitorar load do servidor e vigiar serviços
   5. OGV e RMVB para AVI e títulos de páginas
Outros artigos deste autor

Usando o "at" para agendamento de tarefas

Integrando o Exim4 com o SendGrid

O Surgimento do Linux

A função DATE_FORMAT() do MySQL

Como Turbinar sua Produtividade com VIM - Guia Definitivo do Desenvolvedor

Leitura recomendada

XML de NF-e ou CT-e ou MDF-e - Como validar usando os pacotes de esquemas do Governo

NetProfiler - Um solução para quem passeia por várias redes

Formatando o bash com cores e efeitos

Criando uma ISO bootável do OpenBSD

Xdialog - Programação Gráfica Útil

  
Comentários
[1] Comentário enviado por removido em 06/06/2012 - 13:27h

Show bola grande fábio !

[ ]'s

[2] Comentário enviado por danniel-lara em 06/06/2012 - 13:35h

Parabéns , ficou bem Bagual esse Artigo

[3] Comentário enviado por felipe300194 em 06/06/2012 - 14:04h

muito bom, provavelmente todos os usuarios poderão retirar algo de importante para o seu cotidiano

[4] Comentário enviado por julio_hoffimann em 06/06/2012 - 19:47h

Parabéns Fábio, ótimas ferramentas. :-)

Abraço!

[5] Comentário enviado por rai3mb em 06/06/2012 - 22:26h

Favoritado!! Alguns script vão para o meu util.lib que importo ao logar com meu usuario, assim todas as funções ficam disponíveis assim que logo no sistema ;-)

[6] Comentário enviado por hellnux em 06/06/2012 - 22:32h

Boa Fábio!

Só deixando uma contribuição e uma pergunta. Por que usou Perl no script de load se o "grosso" é shell script? Por conta do shell só trabalhar como números inteiros? Acredito que isso não impeça, só transformar em int, já que o loadLimit será sempre inteiro mesmo. xD

Segue código:
#!/bin/bash
loadLimit=1
checkTimer=60
while [ 1 ]; do
load=$(awk '{print $1}' /proc/loadavg | cut -d '.' -f1)
if [ $load -ge $loadLimit ]; then
echo "Load alto: $load"
echo "Load alto: $load" | mail -s "LOAD" fberbert@gmail.com
exit 2
fi
sleep $checkTimer
done

[7] Comentário enviado por iz@bel em 07/06/2012 - 14:59h

Já favoritei, tem scripts muito bom...

O de substituir palavras em múltiplos arquivos valeu por tudo, eu preciso muito disso, valeu!

Nota 100000000......

[8] Comentário enviado por removido em 08/06/2012 - 09:08h

Gostei particulamente do "Descobrir localidade geográfica de um IP".

Só não me lembro agora qual foi a última rede que "malei" fazendo port scan. Eh! Eh! :-)

[9] Comentário enviado por coelhoposa em 08/06/2012 - 17:36h

Muito legal... posso incluir alguns no easy-tools? O easy-tools é um kit de ferramentas destinado a facilitar certas funções ao sistema, seja Arch, seja Fedora ou seja Debian...

[10] Comentário enviado por fabio em 08/06/2012 - 17:39h

@milesmaverick

Será uma honra, nem precisava perguntar.

[11] Comentário enviado por jacksonsantana em 09/06/2012 - 19:23h

muito interessante.

[12] Comentário enviado por xjc em 09/06/2012 - 22:27h

cara os scripts em peral estão dando erro pra baixar, tenta compacta-los

[13] Comentário enviado por fabio em 10/06/2012 - 14:37h

Olá xjc,

Problema resolvido! Obrigado por avisar.

[]'s

[14] Comentário enviado por jaircs em 10/06/2012 - 20:17h

Excelente artigo.

[15] Comentário enviado por fabio em 11/06/2012 - 04:21h


[6] Comentário enviado por hellnux em 06/06/2012 - 22:32h:

Boa Fábio!

Só deixando uma contribuição e uma pergunta. Por que usou Perl no script de load se o "grosso" é shell script? Por conta do shell só trabalhar como números inteiros? Acredito que isso não impeça, só transformar em int, já que o loadLimit será sempre inteiro mesmo. xD

Segue código:
#!/bin/bash
loadLimit=1
checkTimer=60
while [ 1 ]; do
load=$(awk '{print $1}' /proc/loadavg | cut -d '.' -f1)
if [ $load -ge $loadLimit ]; then
echo "Load alto: $load"
echo "Load alto: $load" | mail -s "LOAD" fberbert@gmail.com
exit 2
fi
sleep $checkTimer
done


Nem sei porque usei Perl. Talvez seja porque me sinto mais a vontade com ele. Obrigado por sua contribuição, já adicionei sua versão à minha caixa de ferramentas :)

[16] Comentário enviado por cesar em 11/06/2012 - 08:37h

Muito bom, não fazia nem ideia de como era a sua caixa de ferramentas para administrar o VOL.

Excelentes script's!

[]'s




[17] Comentário enviado por leoberbert em 12/06/2012 - 12:05h

Fábio,

Muito bom, é difícil uma pessoa compartilhar seus scripts assim :)... Conheci o código do Alberto ai rapidim heheheheh

Parabéns.

[18] Comentário enviado por m4cgbr em 18/06/2012 - 06:26h

Muito legal sua iniciativa.

Parabéns e obrigado.

[19] Comentário enviado por cycne em 31/08/2012 - 19:00h

Contribuição para melhorar os scripts:

-> "ogv2avi" e "rmvb2avi":
ffmpeg está obsoleto , o projeto ativo é o avconv, que usa praticamente a mesma sintaxe do ffmpeg.
para usuarios debian/ubuntu: apt-get install libav-tools
no script é só substituir "ffmpeg" por "avconv" , os parametros continuam os mesmos.
o comando "ogv2avi" poderia se chamar "all2avi" , pois o avconv reconhece praticamente qualquer formato de entrada. sendo assim ele já faz a mesma função do "rmvb2avi".


-> "titulo" pode ser simplificado e mais eficiente.
a saida aqui do comando com a URL exemplo foi

$ ./titulo "http://tinyurl.com/7kepltq"
Use Tennis Balls to Hold Just About Any Small Item Around the House (and Be Extremely Cute)<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
$

olha o <meta> saindo lá... vamos melhorar:

#!/bin/bash
wget -q -O - "$1" | sed -n 's/.*<title>\(.*\)<\/title>.*/\1/Ip'


testando....
$ ./title http://tinyurl.com/7kepltq
Use Tennis Balls to Hold Just About Any Small Item Around the House (and Be Extremely Cute)
$

Agooora sim :)

Abraços!

[20] Comentário enviado por darkstarfire em 28/09/2012 - 09:25h

@ cycne

Se o ffmpeg é obsoleto, me explique isso.

FFmpeg 1.0 "Angel"

1.0 was released on 2012-09-28. It is the latest stable FFmpeg release from the 1.0 release branch, which was cut from master on 2012-09-28. Amongst lots of other changes, it includes all changes from ffmpeg-mt, libav master of 2012-09-27, libav 0.8.3 as of 2012-09-27.

Download bzip2 tarball http://ffmpeg.org/releases/ffmpeg-1.0.tar.bz2

Changelog http://git.videolan.org/?p=ffmpeg.git;a=shortlog;h=n1.0

FFmpeg Reaches Version 1.0
Posted by Michael Larabel on September 28, 2012
http://www.phoronix.com/scan.php?page=news_item&px=MTE5NDM

Se prefere o "avconv", tudo bem, mas dizer que o "ffmpeg" está obsoleto, não cola.

Obs: ou você está desinformado, ou então é maldade sua.

[21] Comentário enviado por cycne em 01/10/2012 - 18:10h


@ darkstartfire

Maldade de que? venho até aqui postar para AJUDAR e que maldade estou fazendo??

A minha informação está baseada nisso, pelomenos no Debian:
# ffmpeg
ffmpeg version 0.8.3-6:0.8.3-7, Copyright (c) 2000-2012 the Libav developers
built on Aug 25 2012 13:25:50 with gcc 4.7.1
*** THIS PROGRAM IS DEPRECATED ***
This program is only provided for compatibility and will be removed in a future release. Please use avconv instead.
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Use -h to get full help or, even better, run 'man ffmpeg'
#


E tambem nesta postagem no site "http://libav.org" Jan 27 2012
-> "Furthermore, the legacy ffmpeg conversion tool has been removed. Only avconv is available now. "

Agora, se estou enganado e vão continuar o ffmpeg, ótimo!! Mas como o Fábio usa Debian, acho que a minha informação procede!
Então não sei onde há maldade nisso.




[22] Comentário enviado por darkstarfire em 01/10/2012 - 23:27h

@ cycne,
Peço-lhe desculpas por qualquer mau(L) entendido, que por ventura ouve na hora de interpretar meu cometário anterior

Não gosto e não costumo causar flame... apenas fiz uma observação no meu comentário anterio conforme listo aqui "Obs: ou você está desinformado, ou então é maldade sua.", usei o termo "desinformado" pois o ffmpeg "http://ffmpeg.org/" foi forcado no ano passado, dando origem ao libav "http://libav.org/"">http://libav.org/". Quanto ao termo "maldade sua" referia-me, caso você já soubesse da divisão do projeto ffmpeg e mesmo assim, seguindo o devs do libav, continuou aumentando o FUD.

Quanto a informação tirada do proprio pacote fornecido pela equipe do Debian, trata-se de um pequeno FUD, com um pouco de verdade, pois até a data da criação do pacote, ainda usava o nome "ffmpeg" linkado para o novo nome "avconv".
porque disse que era FUD? pois é isso mesmo FUD "*** THIS PROGRAM IS DEPRECATED ***" e pouco de verdade, se refere ao modo de compatibilidade para que os front end feitos para usar como base o "ffmpeg" podessem continuar funcionando...

sites para referência:

http://ffmpeg.org/
http://libav.org/
http://phoronix.com/forums/showthread.php?74004-FFmpeg-Reaches-Version-1-0#post288927
http://blog.pkh.me/p/13-the-ffmpeg-libav-situation.html




Obs: alguns textos tirados dos dois sites principais.

March 15, 2011

FFmpeg has been forked by some developers after their attempted takeover[1] two months ago did not fully succeed. During these two months their repository was listed here as main FFmpeg repository. We corrected this now and list the actual main repository and theirs directly below. All improvements of their fork have been merged into the main repository already.

Sadly we lost a not so minor part of our infrastructure to the forking side. We are still in the process of recovering, but web, git and issue tracker are already replaced.

Readers who want to find out more about the recent happenings are encouraged to read through the archives of the FFmpeg development mailing list[2]. There was also a bit of coverage on some news sites like here [3].

[1] Takeover: http://article.gmane.org/gmane.comp.video.ffmpeg.devel/123868
[2] GMANE FFmpeg development mailing list archive: http://dir.gmane.org/gmane.comp.video.ffmpeg.devel
[3] LWN.net Article: http://lwn.net/Articles/423702/




August 09 2011

Updated on 12.09.2011.

For consistency with our new name we have renamed ffplay to avplay, ffserver to avserver and ffprobe to avprobe. Their behavior is the same, just the names were changed.

With ffmpeg (the commandline tool) we decided to use this opportunity to fix some longstanding usability problems, which involves breaking compatibility. Therefore we have added a new tool named avconv which is based on ffmpeg, but has a different (hopefully more powerful and easier to use) syntax for some options. ffmpeg will be kept in its current state for some time, so no scripts or frontends using it will break. However it will not be developed further.

Differences between avconv and ffmpeg are:

The options placement is now strictly enforced! While in theory the options for ffmpeg should be given in [input options] -i INPUT [output options] OUTPUT order, in practice it was possible to give output options before the -i and it mostly worked. Except when it didn't - the behavior was a bit inconsistent. In avconv, it is not possible to mix input and output options. All non-global options are reset after an input or output filename.
All per-file options are now truly per-file - they apply only to the next input or output file and specifying different values for different files will now work properly (notably -ss and -t options).
All per-stream options are now truly per-stream - it is possible to specify which stream(s) should a given option apply to. See the Stream specifiers section in the avconv manual for details.
In ffmpeg some options (like -newvideo/-newaudio/...) are irregular in the sense that they're specified after the output filename instead of before, like all other options. In avconv this irregularity is removed, all options apply to the next input or output file.
-newvideo/-newaudio/-newsubtitle options were removed. Not only were they irregular and highly confusing, they were also redundant. In avconv the -map option will create new streams in the output file and map input streams to them. E.g. avconv -i INPUT -map 0 OUTPUT will create an output stream for each stream in the first input file.
The -map option now has slightly different and more powerful syntax:
Colons (':') are used to separate file index/stream type/stream index instead of dots. Comma (',') is used to separate the sync stream instead of colon.. This is done for consistency with other options.
It's possible to specify stream type. E.g. -map 0:a:2 creates an output stream from the third input audio stream.
Omitting the stream index now maps all the streams of the given type, not just the first. E.g. -map 0:s creates output streams for all the subtitle streams in the first input file.
Since -map can now match multiple streams, negative mappings were introduced. Negative mappings disable some streams from an already defined map. E.g. '-map 0 -map -0:a:1' means 'create output streams for all the stream in the first input file, except for the second audio stream'.
There is a new option -c (or -codec) for choosing the decoder/encoder to use, which allows to precisely specify target stream(s) consistently with other options. E.g. -c:v lib264 sets the codec for all video streams, -c:a:0 libvorbis sets the codec for the first audio stream and -c copy copies all the streams without reencoding. Old -vcodec/-acodec/-scodec options are now aliases to -c:v/a/s
It is now possible to precisely specify which stream should an AVOption apply to. E.g. -b:v:0 2M sets the bitrate for the first video stream, while -b:a 128k sets the bitrate for all audio streams. Note that the old -ab 128k syntax is deprecated and will stop working soon.
-map_chapters now takes only an input file index and applies to the next output file. This is consistent with how all the other options work.
-map_metadata now takes only an input metadata specifier and applies to the next output file. Output metadata specifier is now part of the option name, similarly to the AVOptions/map/codec feature above.
-metadata can now be used to set metadata on streams and chapters, e.g. -metadata:s:1 language=eng sets the language of the first stream to 'eng'. This made -vlang/-alang/-slang options redundant, so they were removed.
Presets in avconv are disabled, because only libx264 used them and presets for libx264 can now be specified using a private option -preset presetname.
-qscale option now uses stream specifiers and applies to all streams, not just video. I.e. plain -qscale number would now apply to all streams. To get the old behavior, use -qscale:v. Also there is now a shortcut -q for -qscale and -aq is now an alias for -q:a.
-vbsf/-absf/-sbsf options were removed and replaced by a -bsf option which uses stream specifiers. Use -bsf:v/a/s instead of the old options.
-itsscale option now uses stream specifiers, so its argument is only the scale parameter.
-intra option was removed, use -g 0 for the same effect.
-psnr option was removed, use -flags +psnr for the same effect.
-vf option is now an alias to the new -filter option, which uses stream specifiers.
-vframes/-aframes/-dframes options are now aliases to the new -frames option.
-vtag/-atag/-stag options are now aliases to the new -tag option.

Note that the avconv interface is not considered stable yet. More incompatible changes may come in the following weeks. We will announce here when avconv is stable.

[23] Comentário enviado por darkstarfire em 01/10/2012 - 23:30h

@ todos

Desculpas por meu péssimo Português.

[24] Comentário enviado por joanesduarte em 23/03/2013 - 22:39h

D+

Com certeza vou usar muitos trechos destes scripts

[25] Comentário enviado por rrodrigues345 em 03/04/2013 - 22:19h

Excelente artigo!

[26] Comentário enviado por hanunjunior em 30/05/2013 - 09:54h

Muito obrigado por compartilhar a sua experiencia, principalmente para quem esta começando, vai me ajudar bastante

[27] Comentário enviado por esmiril em 21/08/2013 - 16:34h

Parabens cara!!! Excelente artigo, ajuda muito os novatos em administração de sistemas, que é meu caso.

[28] Comentário enviado por QuestLoder em 18/09/2013 - 16:30h

Vlw e parabéns pelo artigo.

[29] Comentário enviado por julianoas em 01/10/2013 - 00:13h

Seria bom executar esses scripts com "nohup" para manter rodando mesmo depois de um logout!

Já está em uso aqui 2 deles.

Valeu e abraço.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts