Rss

  • youtube
  • linkedin
  • google

Archives for : December2015

Naming files using list from 0 to Z

Today I was coding some scripts and found a little trouble to use a defined pattern.

The pattern is to create files where the sequence starts in 0 (zero) and cannot be repeated until Z.

Example:

myfile0.ext, myfile1.ext, myfile2.ext, (...), myfile9.ext, myfileA.ext, myfileB.txt, (...), myfileZ.txt

Well, this is not a big trouble so I did use this code.

// Filename
$seq = $last_used_seq = '';
$seqs = array_merge(range('0','9'), range('A', 'Z'));]
$l = 1;
while (!in_array($seq, $seqs)) {
    $seq = chr(ord($last_used_seq) + $l++);
}

But

$seq

did not gave the expected value of 0 (zero) on first run. Instead, it was blank.

Debugging the variables, I saw that the while never evaluates to true. Attempting to reproduce on command line I saw that

in_array($seq, $seqs);

always return true. I tryed to use “”, “R” and no matter what value I used, still returning true.

So I change to use STRICT argument for in_array to true and works for ‘A’ through ‘Z’, but not for ‘0’ through ‘9’.

while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($last_used_seq) + $l++);
}

Damn… PHP is right, “0” is not strictly equals to 0. The Chr function return string and

range('0', '9')

creates an array with integer values.

So, I changed the approach to evaluate all values with STRICT, because I would like to create a nice and clean code without no other functions to be used.

This is the final code that I’m using:

// Initial values 
$seq = '';
$seqs = array_merge(range(ord('0'),ord('9')), range(ord('A'), ord('Z')));
$seqs = array_map('chr', $seqs);
$l = 1;
while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($infos['last_seq']) + $l++);
}

// Filenames
foreach ($itens_for_files as $key => $itens) {
    // ... Another codes to fill file    
    $seq = chr(ord($seq) + 1);
    while (!in_array($seq, $seqs, true)) {
    $seq = chr(ord($seq) + 1);
    $filename = 'myfile' . $seq . '.ext';
    // ...
}

How you can see, I changed the $seqs initial values from ‘0’ to your ASCII code and get back to your value that gave me an array with all values in string type.

See you!

PHP Comparison Error

Today, I was writing a script in PHP to be used in the command line when I came across unexpected behavior (at least on my part).
The script should receive three arguments, the last of them a list containing one or more numeric codes.
Trying to validate this last argument was getting a different result than imagined.
See the code snippet that I was using:

// test.php
if (php_sapi_name() == 'cli') {
    $di = isset($argv[1]) ? $argv[1] : date('Y-m-d'); // Initial Date
    $df = isset($argv[2]) ? $argv[2] : date('Y-m-d'); // Final Date
    $prods = isset($argv[3]) ? explode(',', $argv[3]) : array(); // Code List

    ##### Validating
    // Initial Date
    if ($di != date('Y-m-d', strtotime($di))) {
        echo "\n";
        echo "ERROR! Invalid INITIAL DATE!\n";
        exit;
    }
    // Final Date
    if ($df != date('Y-m-d', strtotime($df))) {
        echo "\n";
        echo "ERRO! Invalid FINAL DATE!\n";
        exit;    
    }

    // Codes
    if (count($prods) > 0) {
        foreach ($prods as $prod) {
            if ($prod != (int)$prod) {
                echo "\n";
                echo "ERROR! The CODE " . $prod . " is invalid!\n" ;
                exit;
            }
        }
    }
    echo "DONE!";
}

Continue Reading >>

Como corrigir Data/hora no Centos 6.X para seu timezone inclusive nos logs

Hoje eu me deparei com um problema ao utilizar o Fail2ban que me ajuda demais a manter o servidor no ar mesmo sob ataques de brute-force.

Um dos meus filtros não estavam barrando as diversas tentativas de autenticação em um dos meus serviços embora estivesse tudo certo. Resolvi aumentar o tempo de Findtime na configuração comum e ele começou a barrar.

Então era hora de entender porque com um findtime baixo ele não conseguia barrar. Comecei a checar detalhadamente as configurações e percebi que mesmo tendo alterado a hora para meu timezone para o horario oficial de Brasilia, os logs continuavam a exibir o horario em UTC. Desconfiei que pudesse ser isso e resolvi alterar o horário que é colocado nos logs (/var/log/messages).

Bingo!

Após a alteração e confirmar que os logs estavam usando o mesmo horario que o reportado em

date 

mudei o findtime para os valores que desejava e tudo funcionou como esperado.

Segue a receita para alterar o horario.

As informações de Timezone ficam no arquivo /etc/localtime e caso ele não esteja no que você quer basta substitui-lo pelo que deseja e que esteja presente em /usr/share/zoneinfo/. No meu caso, como queria o horario de Brasília, utilizei /usr/share/zoneinfo/America/Sao_Paulo.

# ln -sf /usr/share/zoneinfo/America/Sao_Paulo /etc/localtime

Agora é só testar usando o comando date e verificar a saída que deverá ser algo como:

# date
Wed Dec 9 15:55:58 BRST 2015

Mesmo após essas mudanças, os logs continuarão a terem o horário da forma antiga. Para alterar isso edite o arquivo /etc/sysconfig/clock e adicione as linhas abaixo para refletir também o seu timezone.

ZONE="America/Sao_Paulo"
UTC=false
ARC=false

No meu caso, precisei reiniciar o servidor para que as alterações surtissem efeito mas pode ser que apenas reiniciando o serviço rsyslog já resolva.

# service rsyslog restart

Até a próxima.

Como corrigir erro de LOCALE no Linux Debian/Ubuntu

Hoje precisei olhar os logs de um servidor FTP que roda sob o pure-ftp e percebi que os horários estavam todos em UTC .
Como eu precisava enviar parte dos logs a um terceiro que faz uso dele e não está familiarizado com sistemas, poderia acabar ocorrendo algum mal entendido. Resolvi então que deveria manter os logs de todas as aplicações no fuso horário brasileiro.
De acordo com a documentação do pure-ftp ele utiliza as variáveis de ambiente para determinar qual será o horário incluído nos logs

Continue Reading >>