



Fala galera do Show Delphi, tudo beleza?
Vamos a mais uma super dica, adicionar regras no firewall do Windows 10.
Isso é muito útil quando queremos automatizar liberações de nossas aplicações.
Bem, para funcionar via Delphi, vamos utilizar via ShellExecute o aplicativo nativo do Windows netsh.exe.
Para facilitar o seu uso, criei uma unit para já deixar prontas as funções de adicionar regras de portas ou programas.
Vamos ao código da unit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | unit UWindowsFirewall; interface uses ShellAPi, Forms, Windows, SysUtils, StrUtils; procedure PortToFirewall(EntryName : String; PortNumber : Cardinal; Allow : Boolean = True); procedure ApplicationToFirewall(EntryName : String; ApplicationPathAndExe : String; Allow : Boolean = True); implementation procedure PortToFirewall(EntryName : String; PortNumber : Cardinal; Allow : Boolean = True); begin ShellExecute(Application.Handle, nil, 'netsh.exe', PChar( 'advfirewall firewall add rule name = "' + EntryName +'" dir = in action = '+ IfThen(Allow, 'allow', 'block') +' protocol = TCP localport = ' + IntToStr(PortNumber) ), nil, SW_HIDE); end; procedure ApplicationToFirewall(EntryName : String; ApplicationPathAndExe : String; Allow : Boolean = True); begin ShellExecute(Application.Handle, nil, 'netsh.exe', PChar( 'advfirewall firewall add rule name = "' + EntryName +'" dir = in action = '+ IfThen(Allow, 'allow', 'block') +' protocol = ANY program = ' + ApplicationPathAndExe ), nil, SW_HIDE); end; end. |
Exemplo – liberando porta
1 2 3 4 5 | procedure TForm1.BtnRegraPortaClick(Sender: TObject); begin PortToFirewall(EdtDescricaoRegraPorta.Text, EdtRegraPorta.Value, CheckPortaPermitir.Checked); end; |
Exemplo – liberando programa
1 2 3 4 5 | procedure TForm1.BtnProgramaAplicaClick(Sender: TObject); begin ApplicationToFirewall(EdtNomePrograma.Text, EdtPathPrograma.Text, CheckProgramaPermitir.Checked); end; |
Também gravei um vídeo pessoal, demonstrando o uso.
Testei no Windows 10, mas acredito que deva funcionar no Windows 8, 7 também.
Também disponibilizei os fontes do exemplo para download.
[download id=”3903″]
Espero que tenham gostado pessoal.
Dúvidas ou sugestões? Deixe o seu comentário.
Até a próxima. Valeu!