sábado, 24 de fevereiro de 2018

Eliminar pasta e arquivos automaticamente .BAT


Temos um servidor que faz backups diáriosdas bases de dados SQL  para o disco, para uma determinada pasta.
Ora, os ficheiros vão incrementando diariamente a não ser que se eliminem os mais antigos. E se essa eliminação puder ser colocada num batch file para ser executado automaticamente muito melhor.
A primeira tentativa foi verificar o comando de MS-DOS Delete ou  Erase. Nenhum dos dois tem possibilidades de calendarização. Pesquisando um pouco mais encontrei o comando ForFiles.exe.
Este comando existe por default nos servidores e pode também ser instalado nos desktops. O windows 7 já o tem incorporado.
Numa janela de MS-DOS poderemos ver as possibilidades deste comando:
C:\>forfiles /?
FORFILES [/P pathname] [/M searchmask] [/S]  [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
    Selects a file (or set of files) and executes a command on that file. This is helpful for batch jobs.
Parameter List:
    /P    pathname      Indicates the path to start searching.
                        The default folder is the current working  directory (.).
    /M    searchmask    Searches files according to a searchmask. The default searchmask is ‘*’ .
    /S                  Instructs forfiles to recurse into  subdirectories. Like “DIR /S”.
    /C    command       Indicates the command to execute for each file.
                        Command strings should be wrapped in double  quotes.
                        The default command is “cmd /c echo @file”.
                        The following variables can be used in the  command string:
                        @file    – returns the name of the file.
                        @fname   – returns the file name without extension.
                        @ext     – returns only the extension of the file.
                        @path    – returns the full path of the file.
                        @relpath – returns the relative path of the file.
                        @isdir   – returns “TRUE” if a file type is a directory, and “FALSE” for files.
                        @fsize   – returns the size of the file in bytes.
                        @fdate   – returns the last modified date of the file.
                        @ftime   – returns the last modified time of the file.
                        To include special characters in the command line, use the hexadecimal code for the character
                        in 0xHH format (ex. 0x09 for tab). Internal  CMD.exe commands should be preceded with
                        “cmd /c”.
    /D    date          Selects files with a last modified date greater  than or equal to (+), or less than or equal to
                        (-), the specified date using the”MM/dd/yyyy” format; or selects files with a  last modified date greater than or equal to (+)  the current date plus “dd” days, or less than or  equal to (-) the current date minus “dd” days. A  valid “dd” number of days can be any number in   the range of 0 – 32768.  “+” is taken as default sign if not specified.
    /?                  Displays this help message.
Examples:
    FORFILES /?
    FORFILES
    FORFILES /P C:\WINDOWS /S /M DNS*.*
    FORFILES /S /M *.txt /C “cmd /c type @file | more”
    FORFILES /P C:\ /S /M *.bat
    FORFILES /D -30 /M *.exe
             /C “cmd /c echo @path 0x09 was changed 30 days ago”
    FORFILES /D 01/01/2001
             /C “cmd /c echo @fname is new since Jan 1st 2001”
    FORFILES /D +7/10/2013 /C “cmd /c echo @fname is new today”
    FORFILES /M *.exe /D +1
    FORFILES /S /M *.doc /C “cmd /c echo @fsize”
    FORFILES /M *.txt /C “cmd /c if @isdir==FALSE notepad.exe @file”
No meu caso, para eliminar ficheiros de backup antigos, mais velhos que seis dias, utilizo o comando desta forma:
forfiles /P “F:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup” /S /M *.bak /D -6 /C “cmd /c del @PATH”
em que:
F:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup –> diretório onde tenho backups diários e desejo eliminar os ficheiros.
*.bak –> tipo de ficheiros a eliminar, neste caso todos que terminem em bak.
/D -6 –> eliminar ficheiros anteriores a seis dias, ou seja, quero preservar sempre os últimos 5 backups.
cmd /c del @PATH –> eliminar os ficheiros
Por fim, basta colocar este comando num batch file (ficheiro de texto com terminação bat) e fazer uma calendarização com a ferramenta do windows “Scheduled Tasks” presente nas “System Tools“.
Outro Ex:
echo  eliminando 8 dias atraz...
forfiles -p "C:\BACKUP\FULL & DIFF" -d -8 -s -m *.*  -c "cmd /c del /f /q @path"

echo eliminando 20 dias atraz...
forfiles -p "C:\BACKUP" -d -20 -s -m *.zip  -c "cmd /c del /f /q @path"

sábado, 17 de fevereiro de 2018

Convertendo e ativando o Windows Server Evaluation (Modo de avaliação) para modo Comercial.


Esse artigo será breve e direto ao ponto. Quem nunca perdeu o acesso ao VLSC (Volume Licensing Service Center) e teve que baixar a versão de avaliação do Windows, o famoso Trial ou Evaluation mode?
Esse cara “dura” por 180 dias sem ativação, o que é tempo suficiente para validar um ambiente ou testar funcionalidades até que as licenças cheguem. O grande lance é que, no momento em que vamos inserir a chave de ativação, na grande maioria das vezes, não funciona!
MAS COMO ASSIM?!?! EU COMPREI UMA LICENÇA ORIGINAL E NÃO VOU CONSEGUIR ATIVAR MEU WINDOWS? Hold your horses, vai conseguir ativar, mas não via “telinha”.
A dica de hoje está relacionada aos comandos necessários para ativação de uma versão “Evaluation” do Windows. Sim sim, o bom e nem tão velho PowerShell será necessário.
Vamos lá…é tudo muito simples, basta digitar alguns comandos e reiniciar o servidor uma vez e tudo estará funcionando. Let’s rock!
O primeiro passo é validar a versão de Windows que está instalada. Para isso, use o seguinte comando:
DISM /online /Get-CurrentEdition
Feito isso, é possível verificar quais as possíveis versões para ativação utilizando o comando
DISM /online /Get-TargetEditions
Vejam que o comando retorna as duas possíveis versões de upgrade, Standard e Data Center. Você selecionará o que for referente ao licenciamento que adquiriu. Pay attention!
Para finalizar, o comando que realizar o “upgrade” na versão e inseri a chave de licença adquirida.
DISM /online /Set-Edition:ServerStandard /ProductKey:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX /AcceptEula
Pronto! Feito isso será solicitado um reboot e seu sistema estará ativado!
Simples, fácil e super rápido! Compartilhe ai, tenho certeza que muita gente perde um tempo precioso por conta deste processo!

Autor:  NATHAN PINOTTI
http://nathanpinotti.azurewebsites.net/como-ativar-o-windows-server-evaluation-modo-de-avaliacao/ 

domingo, 11 de fevereiro de 2018

Acesso ao banco MariaDB no debia 9 (mysql) senha root.

ACESSO REMOTO ROOT NO MARIADB NO DEBIAN 9


O acesso remoto no MariaDB do Debian9 é bloqueado por questões de segurança. 

Caso queira, mesmo assim, acesso root remoto via Workbench ou PHPmyadmin, basta seguir os seguintes passos. 

Na máquina onde está instalado o MariaDB/Debian9 faça: 

# mysql -u root -p 

use mysql;
update user set plugin='' where User='root';
grant all privileges on *.* to 'root'@'%' identified by 'sua senha';
flush privileges;
exit 


Edite o arquivo /etc/mysql/mariadb.conf.d/50-server.cnf, colocando um "#" na linha: 

#bind-address

Reinicie o serviço: 

# service mysql restart


Autor: https://www.vivaolinux.com.br/dica/Acesso-remoto-root-no-MariaDB-no-Debian-9 

sábado, 10 de fevereiro de 2018

Lentidao Lerdeza performance do RDP no windows server 2008 R2 e 2012 R2 em VM maquina virtuais Vmware e Proxmox


Slow RDP performance on Windows 2008 R2 and 2012 R2 servers running on VMware and Proxmox

We were running several Windows 2012 R2 servers on a VMware ESX environment. And still, we experience a sluggish performance on the Windows 2012R2 server when connection them with any RDP-client. We tried different connections (wifi, 4G, LAN, etc.) and different clients (Windows 10 RDP, RoyalTS, Mac-RDP, etc.). The hardware could’t be a factor in the issue. So we searched to some finetune-settings in GPO and registry.

The hardware wasn’t an issue.

the servers did’t have a high overall load
there was no high CPU load
there was enough RAM
we used 15k HP SAS enterprise disks
there was no high IO
we had Teamed the NICs in VMware


This is what we did to solve the issue and get very fast RDP-performance.


Finetune “Remote Desktop Services” in Group Policy


Just wanted to post this for anyone else experiencing this issue. Seems the issue does not effect Windows Server 2012 R2, and turns out it might be related to the UDP packets getting fragmenting when creating a RDP session. Here’s the fix:


open prompt DOS:  gpedit.msc 





Computer Config > Windows Settings  > Administrative Templates > Windows  Components  > Remote Desktop Services > Remote Desktop Session Host >  Connections >  Select RDP transport protocol = Use only TCP











You can also set this on the client side by specifying:

Computer Config > Windows Settings > Admin Templates > Windows Components > Remote Desktop Services > Remote Desktop Connection Client > Turn off UDP on Client = Enabled











Disabling TCP Offloading in Windows Server 2012
We also add below registry setting to improve performance. A little explanation of TCP Offloading:

“TCP offload engine is a function used in network interface cards (NIC) to offload processing of the entire TCP/IP stack to the network controller. By moving some or all of the processing to dedicated hardware, a TCP offload engine frees the system’s main CPU for other tasks. However, TCP offloading has been known to cause some issues, and disabling it can help avoid these issues.”


----------  2º second option -----------


This is what you must do in the Registry (regedit)




1. Open RegEdit on the Windows Server machine.

2. Navigate to this registry key in the tree on the left:

3. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

4. Right-click on the right side, and add a new DWORD (32-bit) Value

5. Set the value name to DisableTaskOffload and the value data to 1

6. Reconnect to the Server via RDP (to a new session) and your performance should be normal.










*-------------------------------------------------------------------------------------------------*


On the Windows Server 2012 machine, disable the Large Send Offload via the following steps:

a. Open Network Connections.

b. Right-click the icon of the NIC which is responsible for the connection to terminal clients and select Properties.

c. In Networking tab, click Configure… button.

d. In the next window, switch to Advanced tab.

e. Click the Large Send Offload Version 2 (IPv4) and change the value to Disabled.















quinta-feira, 1 de fevereiro de 2018

Problema no remote desktop TS (RDP e MSTSC) do windows: copiar e colar parou de funcionar


A você que usa a área de trabalho remota do windows e sempre conseguiu compartilhar conteúdo de texto normalmente entre as máquinas com copiar e colar, mas desta vez teve a surpresa de ver o famoso CTRL+C  CTRL+V sem funcionar… segue o que pode ser uma simples solução do problema.
Verifique o gerenciador de tarefas da máquina remota e procure pelo processo rdpclip (remote desktop clipboard), responsável por gerenciar a área de transferência entre as máquinas. No meu caso o problema foi resolvido reiniciando esse processo:

  1. abra o gerenciador de tarefas (via CTRL+Shift+Esc) e escolha a aba Processes 
  2. selecione rdpclip.exe, depois End Process
  3. na aba Applications escolha New Task…
  4. digite rdpclip e confirme
Isso acontece tantas vezes, este processo é chato! O que eu faço para corrigi-lo definitivamente?
Infelizmente eu não sei por que rdpclip pára de funcionar nem como corrigi-lo permanentemente; no entanto, há uma maneira de torná-lo mais fácil se isso acontece muitas vezes.
Crie um novo arquivo bat e chamar do que quiser dizer, clipboard.bat.
Escreva os seguintes comandos em linhas separadas no novo arquivo bat
Taskkill.exe / im rdpclip.exe
Rdpclip.exe
Salve o arquivo bat e arrastá-lo para a seção de inicialização rápida da barra de ferramentas.
Agora, sempre que o seu copiar e colar operação falhar para restaurá-lo, tudo que você precisa fazer é clicar nesse novo arquivo de lote que vai matar rdpclip e reiniciá-lo. Ainda uma solução alternativa, mas pelo menos é um procedimento rápido.