segunda-feira, março 27, 2017

How to disable SMB 1 on Windows 7 via Group Policy

In case you have not got the message yet SMB 1 protocol Bad and that according to Microsoft you should “Stop using SMB1”. Not that I should have to explain, but in case you need a refresher it is old (30 years old); it is slow (especially over high-latency links); and its was superseded over a decade ago with the release of Windows Vista, that’s right… VISTA!!!! So, by now you should be convinced that SMB 1 is really bad and that you need to banish the protocol from your network.
If you want any more convincing we are now 30 years in the future from the release of the original SMB 1 protocol (and the Back to the Future movie). While we still don’t have flying cars, at least we can get rid of SMB 1…. right!
Before you start it is always a good idea to check that all your servers in your environment support SMB 2.0 or later. For Windows server this is easy as any OS more recent that Windows Vista or Windows Server 2008 natively support SMB 2 and have it enabled by default. What might take a little more time is testing all the non-windows server in your environment. In this case what i recommend you do is just disabled SMB 1 manually on a few test computers and just see what breaks. This is a sure fire way to ensure if the server is running SMB 2+ as if the SMB 1 client is disabled then the file share almost certainly has to be SMB 2 or later.
To manually disable SMB 1 on your test workstations simple running the following commands from an elevated command prompt:
sc.exe config lanmanworkstation depend= bowser/mrxsmb20/nsi
sc.exe config mrxsmb10 start= disabled
Now that you have done your testing and you are confident that you want to disable SMB 1 you now need a way to make this change to all your Windows 7 clients quickly and easily. Unfortunately, there is no Group Policy setting or registry key that you can apply to Windows 7 to disable SMB1. So, even thought I can’t believe I am saying this, I recommend that you create a logon script to run the command that disables the protocol. While even the very mention of logon scripts for a Group Policy guy like my self it total blasphemy in this case, I would certainly consider it the lesser of two evils.
As always to begin you need to create a Group Policy object to the computer that you want to apply the settings. Then you need to edit the policy and navigate to Computer Configuration > Windows Settings > Scripts. Then double click on “Startup” and then click the “Show Files…” button.
Windows Explorer will now open up to the Scripts folder in the GPO you have created and here you can just right click and create a New “Text Document”.
Here just create a text file with the two command line as per above and save the file as disablesmb1.cmd (or something like that).
image
Now go back to the “Startup Properties” windows and click “Add” then click “Browse” and select the file you just created and then click “ok”.
The policy will now run a logon script then next time the computer reboots. It will disable the SMB 1 protocol the next reboot after that and you will will very quickly have disabled it on all you Windows 7 computers.
Note: This will work on Windows 8.1 or later as well but in that case it would be far better to just run the one line Powershell command that just simple removes the feature from the OS.
Disable-WindowsOptionalFeature -Online -FeatureName smb1protocol
Note: This will work on Windows 8.1 or later as well but in that case it would be far better to just run the one line Powershell command that just simple removes the feature from the OS.
Additional References:

domingo, março 26, 2017

De volta as origens. #emoji #egypt #hieroglyphs #voltaIRCestasperdoado


via Instagram http://ift.tt/2ojIyar

quinta-feira, março 23, 2017

Conheça 8 curiosidades sobre cabos de rede submarinos

je em dia, as informações podem atravessar o mundo para chegar em sua casa, e tudo isso é feito através de cabos submarinos enormes que conectam continentes e países. Sobre cada um deles existem curiosidades e histórias interessantes que você possivelmente não sabia!

Confira agora oito curiosidades incríveis sobre redes submarinas.

1) Criação

As linhas de redes submarinas nasceram em 1854, com o primeiro cabo telegráfico cruzando o Atlântico e ligando a ilha de Terra Nova, no Canadá, à Irlanda.
O navio que lançou a fiação foi o HMS Agamemnon.  Porém, a primeira transmissão de dados foi feita apenas quatro anos depois.

2) Positivo e operante

Não, os tubarões não estão comendo a internet, pelo menos segundo o Comitê Internacional de Proteção dos Cabos (International Cable Protection Committee).
Sim, existe um comitê exclusivamente para cuidar desses objetos tão frágeis.
Durante o período de 2007 a 2014, nenhuma falha relacionada a esses animais foi registrada. Porém, atividades de pesca e ancoragem feitas por humanos foram responsáveis por 75% de todas as falhas dos cabos submarinos.

3) Duração tão grande quanto o tamanho

Essa fiação submarina tem uma vida útil longa! O tempo de existência que podem alcançar é de 25 anos. No entanto, alguns podem durar mais ainda caso haja poucos danos em sua estrutura.

4) Viajando para a lua

Imenso! Esta é a palavra que define o comprimento do cabo mais longo. A rede submarina chamada SEA-ME-WE-3 mede cerca de 39 mil km, conectando 33 países em quatro continentes. Com todo esse tamanho, ela equivale a cerca de 10% da distância entre a Lua e a Terra.

5) Tráfego intenso

Segundo o relatório sobre a Confiabilidade da Infraestrutura Global de Comunicações por Cabos Submarinos de 2010, quase 100% de todo o tráfego global entre continentes proveniente de comunicações eletrônicas são feitos por meio da infraestrutura desses fios.

6) Pinguins desconectados

Sim, ainda hoje a Antártida é o único continente que não está conectado por cabos submarinos. Isso é devido ao movimento das placas de gelo, que chegam a até 10 metros de deslocamento por ano, e também ao fato de a população do local ser espalhada geograficamente. Então, por ser um ambiente desafiador para a fiação, melhor deixar pra lá, ao menos por enquanto.

7) Poderoso, porém frágil

Deslizamentos submarinos, fortes correntes e maremotos podem causar danos à fiação debaixo do mar. Casos como esses aconteceram em 2006 na costa de Taiwan e em 2011 na costa do Japão.

8) Teia digital

Embaixo dos nossos mares existem 358 fios de redes subaquáticas que conectam os países e continentes do mundo todo, segundo a base de dados online de cabos submarinos TeleGeography. Saiba mais: Mapa revela as conexões e os cabos submarinos da internet 
Apesar de o número ser menor que os 2,2 mil satélites que estão em órbita, a fiação debaixo da água é tão importante quanto os nossos transmissores espaciais.
...
Quase desconhecida, essa estrutura completa que atravessa oceanos tem grande trabalho ao levar informações importantes para os computadores de todo o mundo. Mesmo tendo grandes desafios em seu caminho, os cabos cumprem suas responsabilidades para nos manter conectados.


fonte https://www.tecmundo.com.br/internet/115193-conheca-principais-curiosidades-cabos-rede-submarinos.htm

quarta-feira, março 22, 2017

A EXPERIÊNCIA DE REALIDADE VIRTUAL DA DISNEY QUE CHEGOU À HOMEPAGE DO REDDIT

É raro o dia em que não aparece uma notícia sobre realidade virtual (VR) nos nossos feeds.
 Seja pelo lançamento de um equipamento, por uma nova aplicação ou jogo ou pelo anúncio de uma experiência excitante, o VR está na ordem do dia mas são poucos os que já tiveram acesso a esta nova dimensão.

Ao contrário de outras tecnologias, o VR só se percebe experimentando e, talvez por isso, a atenção que damos às notícias sobre este tema seja escassa. Mas nem sempre é assim. No Reddit, onde uma grande parte das discussões online acontecem, há uma novidade de VR que está a suscitar a curiosidade dos utilizadores. Com mais de 20 mil upvotes, chegou à homepage do fórum. O assunto em questão é este GIF:
O GIF anterior é o resultado de uma experiência da Disney que mostra que é possível apanhar objectos reais, como uma bola de ténis, enquanto estamos imersos num ambiente de realidade virtual. Eis o vídeo completo da experiência:

Os investigadores da Disney criaram um sistema em que a bola é rastreada virtualmente enquanto está no ar e que é capaz de prever a trajectória e comportamento do objecto, ajudando o utilizador a saber quando precisa de apanhá-la. Isto pode parecer algo muito básico, mas interagir com um movimento real enquanto imerso num ambiente virtual não é fácil, não só porque a nossa percepção das coisas diminui mas também pelo atraso que pode existir entre as duas realidades, entre outros motivos.
Podes conhecer esta experiência em detalhe aqui.

Fonte https://shifter.pt/2017/03/realidade-virtual-disney-reddit/

Timeout no arranque de serviços do SQL Server


Em determinadas circunstâncias os serviços do SQL Server podem não arrancar automaticamente quando o Windows inicia. No meu caso passaram a existir problemas, no Windows 10, após uma determinada atualização recente (KB3201845). Mesmo após remover esta atualização e efetuar ao restart ao sistema, o serviço do SQL Server não arrancava automaticamente e como consequência o ERP Primavera não abria. Se o serviço fosse iniciado manualmente, aí sim, arrancava com normalidade. Após analisar os eventos do Windows detetei que existia um tempo limite de arranque que tinha sido atingido (ID do evento: 7009). O serviço tenta arrancar dentro de um determinado tempo estabelecido. Se não conseguir por qualquer motivo, deixa de tentar novamente.
image

Uma das formas de ultrapassar e contornar este problema pode passar por aumentar o tempo limite para um valor superior (o dobro ou o triplo por exemplo). Para esse efeito criei uma nova chave no registo do Windows, conforme imagem em baixo.
image
Como proceder?:
Abra o registo do Windows (tecla Windows+R) e escreva regedit. Navegue até:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
Agora, com o botão direito em cima de Control, crie uma nova chave do tipo DWORD. Altere o nome da chave para ServicesPipeTimeout. Modifique a chave de acordo com a imagem acima (“Base” e “Dados do valor”). No campo do valor coloque o valor pretendido, em milissegundos. Reinicie o computador e teste.


Artigos relacionados:

How to disable SSL v2 and SSL v3 on Windows Server via Group Policy

n this article I will show you how to disable the SSL v2 and SSL v3 protocols on the Windows Server so that it no longer offers the depreciated (a.k.a. Broken) SSL v2 and v3 security protocols. It also does not hurt if you apply this policy settings to your Windows client computers in case any of them have IIS with digital certificate enabled.
Note: That if you are running a non Microsoft web server such as Apache then you will need to contact that vendor for specific instructions on how to disabled the protocol.

The first step will be to create a Group Policy that is targeted to the servers that you want to disable SSL. Then open up Computer Configuration > Preferences > Windows Settings > Registry. Then create two new “Registry Items” as per follows:
Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server
Name: Enabled
Value: Reg_Dword 0
image
Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server
Name: Enabled
Value: Reg_Dword 0
image
Restart the server and you should now be done.
Alternatively, if your server is not domain joined then you can save the below registry key information as a .Reg file and just manually apply it to your server.
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server] “Enabled”=dword:00000000 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server] “Enabled”=dword:00000000
Once you have applied the setting to the server it would be best to reboot to ensure that the setting is properly applied. If you web server is on the internet then you can ensure that is has worked by using the http://ssllabs.com/ web site to perform a test against you site.
As you can see with the examples below, having SSL v2 and v3 enabled can make the world of difference in the of security of your web site.
image
image
Additional references: http://disablessl3.com/

Windows 3.10 to Windows 10

Na execução de um experimento mais do que curioso, Andrew Tait, responsável pelo canal TheRasteri no YouTube, decidiu instalar e atualizar em um mesmo computador todas as principais versões do Windows já lançadas. No vídeo, é possível ver (em velocidade aumentada) a instalação e o uso de cada uma delas enquanto o responsável pela proeza narra (em inglês) todas as dificuldades pelas quais passou durante o processo.
Começando do zero, com um computador formatado, Tait partiu da versão 3.10 do MS DOS – que nem era vendida na época, apenas a partir da versão 5 – e passou por cada uma das edições já lançadas do Windows nos últimos 36 anos de Microsoft. A única versão que ele pulou foi o Windows ME, pois ele não permite que se faça uma atualização para o Windows 2000, o que interromperia a sequência.
Algumas versões do Windows: curioso como o logo do Windows 8 se parece com o da primeira edição

Incrível jornada

O processo demorou três dias para ser concluído até o Windows 10 e, desse período, 12 horas foram gastas apenas para as instalações. Durante essa “aventura”, Tait ainda pode relembrar programas e jogos nostálgicos, como o Pagemaker, o Paintbrush, Doom 2 e Monkey Island. Os games, inclusive, funcionaram normalmente através das atualizações até o Windows 7, surpreendentemente.
Confira no vídeo abaixo essa jornada que condensa 36 anos de Microsoft e três dias de trabalho em menos de 10 minutos:



terça-feira, março 21, 2017

PFsence 2.0.2 Release Now Available!

pfSense 2.0.2 is a maintenance release with some bug and security fixes since 2.0.1 release. You can upgrade from any previous release to 2.0.2.

Heads up for those upgrading

Auto Update URL – For those upgrading from a prior release, first please make sure you’re on the correct auto-update URL. Tens of thousands of installs were from 2.0 pre-release snapshots which had their update URL set to the snapshot server rather than the stable release updates. Others had manually set their architecture incorrectly at some point and had failed upgrades because of it. Just browse to System>Firmware, Updater Settings tab. From the “Default Auto Update URLs” drop down box, pick either the stable i386 or amd64 depending on which version you have installed, and click Save. Then you can use the auto-update and be ensured you’re pulling from the correct location.
PPP-assigned DNS server problem – those with PPP type WANs (PPP, PPPoE) using the DNS servers assigned by their ISP rather than ones defined under System>General Setup, be aware those DNS servers will not be used. There are two work arounds detailed here.

FreeBSD Security Advisories

Base OS updated to 8.1-RELEASE-p13 to address the following FreeBSD Security Advisories:
  • NOTE: FreeBSD-SA-12:03.bind, FreeBSD-SA-12:05.bind, and FreeBSD-SA-12:06.bind do not apply to us, since we do not use nor include bind. FreeBSD-SA-12:08.linux does not apply since we do not use nor include the Linux compatibility layer of FreeBSD. FreeBSD-SA-12:02.crypt doesn’t apply because we don’t use DES in that context.

PPTP

  • Added a warning to PPTP VPN configuration page: PPTP is no longer considered a secure VPN technology because it relies upon MS-CHAPv2 which has been compromised. If you continue to use PPTP be aware that intercepted traffic can be decrypted by a third party, so it should be considered unencrypted. We advise migrating to another VPN type such as OpenVPN or IPsec.
  • Fix reference to PPTP secondary RADIUS server shared secret.
  • PPTP 1.x to 2.x config upgrade fixes.

NTP Changes

  • OpenNTPD was dropped in favor of the ntp.org NTP daemon, used by FreeBSD.
  • Status page added (Status > NTP) to show status of clock sync
  • NTP logging fixed.
  • NOTE: ntpd will bind/listen to all interfaces by default, and it has to in order to receive replies. You can still do selective interface binding to control which IPs will accept traffic, but be aware that the default behavior has changed.

Dashboard & General GUI Fixes

  • Various fixes for typos, wording, and so on.
  • Do not redirect on saving services status widget.
  • Don’t use $pconfig in widgets, it has unintended side effects.
  • Fix display of widgets with configuration controls in IE.
  • Changed some padding/margin in the CSS in order to avoid wrapping the menu.
  • #2165 Change to embed to prevent IE9 from misbehaving when loading the Traffic Graph page

OpenVPN Fixes

  • Safer for 1.2.3 upgrades to assume OpenVPN interface == any, since 1.2.3 didn’t have a way to bind to an interface. Otherwise people accepting connections on OPT interfaces on 1.2.3 will break on upgrade until the proper interface is selected in the GUI
  • Don’t ignore when multiple OpenVPN DNS, NTP, WINS, etc servers were specified in 1.2.3 when upgrading. 1.2.3 separated by ;, 2.x uses separate vars.
  • Fix upgrade code for 1.2.3 with assigned OpenVPN interface.
  • Fix LZO setting for Upgraded OpenVPN (was turning compression on even if old config had it disabled.)
  • Be more intelligent when managing OpenVPN client connections bound to CARP VIPs. If the interface is in BACKUP status, do not start the client. Add a section to rc.carpmaster and rc.carpbackup to trigger this start/stop. If an OpenVPN client is active on both the master and backup system, they will cause conflicting connections to the server. Servers do not care as they only accept, not initiate.

IPsec fixes

  • Only do foreach on IPsec p2′s if it’s actually an array.
  • #2201 Don’t let an empty subnet into racoon.conf, it can cause parse errors.
  • #2201 Reject an interface without a subnet as a network source in the IPsec Phase 2 GUI.
  • Add routes even when IPsec is on WAN, as WAN may not be the default gateway.
  • #1986 Revamped IPsec status display and widget to properly account for mobile clients.
  • Fixed a bug that caused the IPsec status and widget to display slowly when mobile clients were enabled.

User Manager Fixes

  • #2066 Improve adding/removing of users accounts to the underlying OS, especially accounts with a numeric username.
  • Include admin user in bootup account sync
  • Fix permission and certificate display for the admin user
  • Fix ssh key note to refer to DSA not just RSA since both work.
  • “:” chars are invalid in a comment field, filter them out.
  • When renaming a user, make sure to remove the previous user or it gets left in /etc/passwd.
  • #2326 Do not allow empty passwords since this might cause problems for some authentication servers like LDAP.

Captive Portal Fixes

  • Take routing table into account when figuring out which IP address to use for talking to CP clients.
  • Prevent browser auto-fill username and password on voucher config, as it can interfere with the settings being properly saved if sync isn’t fully configured, which this can make happen accidentally.
  • Correct the Called-Station-Id attribute setting to be the same on STOP/START packets
  • Correct the Called-Station-Id attribute setting to be consistent on the data sent
  • #2082 Correct the log to display the correct information about an existing session
  • #2052 Remove duplicate rule
  • Fix which roll to write when writing the active voucher db
  • Always load ipfw when enabling CP to ensure the pfil hooks are setup right
  • #2378 Fix selection of CP interfaces when using more than 10 opt interfaces.
  • Strengthen voucher randomization.

NAT/Firewall Rules/Alias Fixes

  • #2327 Respect the value of the per-rule “disable reply-to” checkbox.
  • #1882 Fix an invalid pf rule generated from a port forward with dest=any on an interface with ip=none
  • #2163 1:1 Reflection fixes for static route subnets and multiple subnets on the same interface.
  • Better validation on URL table alias input from downloaded files.
  • #2293 Don’t put an extra space after “pass” when assuming it as the default action or later tests will fail to match this as a pass rule.
  • Update help text for Host aliases to indicate FQDNs are allowed.
  • #2210 Go back to scrub rather than “scrub in”, the latter breaks MSS clamping for egress traffic the way we use it.
  • Fix preservation of the selection of interfaces on input errors for floating rules.
  • Fix URL table update frequency box.
  • Fix input validation for port forwards, Local Port must be specified.
  • Added a setting to increase the maximum number of pf tables, and increased the default to 3000.
  • Properly determine active GUI and redirect ports for anti-lockout rule, for display and in the actual rule.
  • Handle loading pf limits (timers, states, table/entry limits, etc) in a separate file to avoid a chicken-and-egg scenario where the limits would never be increased properly.

Interface/Bridging Fixes

  • Correct checking if a gif is part of bridge so that it actually works correctly adding a gif after having created it on bootup
  • Use the latest functions from pfSense module for getting interface list
  • Use the latest functions from pfSense module for creating bridges
  • Implement is_jumbo_capable in a more performant way. This should help with large number of interfaces
  • Since the CARP interface name changed to “vipN” from “carpN”, devd needs to follow that change as well.
  • #2242 Show lagg protocol and member interfaces on Status > Interfaces.
  • #2212 Correctly stop dhclient process when an interface is changed away from DHCP.
  • Fixed 3G SIM PIN usage for Huawei devices
  • Properly obey MTU set on Interface page for PPP type WANs.

Other Misc. Fixes

  • #2057 Add a checkbox that disables automatically generating negate rules for directly connected networks and VPNs.
  • Mark “Destination server” as a required field for DHCP Relay
  • Clarify the potential pitfalls when setting the Frequency Probe and Down parameters.
  • Add a PHP Shell shortcut to disable referer check (playback disablereferercheck)
  • #2040 Make Wireless Status tables sortable
  • #2068 Fix multiple keys in a file for RFC2136 dyndns updates.
  • Check to see if the pid file exists before trying to kill a process
  • #2144 Be smarter about how to split a Namecheap hostname into host/domain.
  • Add a small script to disable APM on ATA drives if they claim to support it. Leaving this on will kill drives long-term, especially laptop drives, by generating excessive Load Cycles. The APM bit set will persist until the drive is power cycled, so it’s necessary to run on each boot to be sure.
  • #2158 Change SNMP binding option to work on any eligible interface/VIP. If the old bindlan option is there, assume the lan interface for binding.
  • Fix reference to PPTP secondary RADIUS server shared secret.
  • #2147 Add button to download a .p12 of a cert+key.
  • #2233 Carry over the key length on input errors when creating a certificate signing request.
  • #2207 Use PHP’s built-in RFC 2822 date format, rather than trying to make our own.
  • Allow specifying the branch name after the repository URL for gitsync command-line arguments and remove an unnecessary use of the backtick operator.
  • Correct send_multiple_events to conform with new check_reload_status behaviour
  • Do not wipe logs on reboot on full install
  • Set FCGI_CHILDREN to 0 since it does not make sense for php to manage itself when lighttpd is doing so. This makes it possible to recover from 550-Internal… error.
  • Support for xmlrpcauthuser and xmlrpcauthpass in $g.
  • Fix Layer 7 pattern upload, button text check was incorrect.
  • Correct building of traffic shaping queue to not depend on parent mask
  • #2239 Add alias support to static routes
  • Use !empty instead of isset to prevent accidental deletion of the last used repository URL when firmware update gitsync settings have been saved without a repository URL.
  • Better error handling for crypt_data and also better password argument handling
  • Stop service needs to wait for the process to be stopped before trying to restart it.
  • Use a better default update url
  • Fix missing description in rowhelper for packages.
  • #2402#1564 Move the stop_packages code to a function, and call the function from the shell script, and call the function directly for a reboot.
  • #1917 Fix DHCP domain search list
  • Update Time Zone zoneinfo database using latest zones from FreeBSD
  • Handle HTTPOnly and Secure flags on cookies
  • Fixed notifications for firmware upgrade progress
  • Removed an invalid declaration that considered 99.0.0.0/8 a private address.
  • Fixed redirect request for IE8/9
  • #1049 Fix crashes on NanoBSD during package removal/reinstall. Could result in the GUI being inaccessible after a firmware update.
  • Fix some issues with upgrading NanoBSD+VGA and NanoBSD+VGA Image Generation
  • Fix issues upgrading from systems with the old “Uniprocessor” kernel which no longer exists.
  • Fix a few potential XSS/CSRF vectors. Thanks to Ben Williams for his assistance in this area.
  • Fixed issue with login page not showing the correct selected theme in certain configurations.
  • Fix limiters+multi-wan

Binary/Supporting Program Updates

  • Some cleanup to reduce overall image size
  • Fixes to ipfw-classifyd file reading and handling
  • Updated miniupnpd
  • ISC DHCPD 4.2.4-P1
  • mdp5 upgraded to 5.6
  • pftop updated
  • lighttpd updated to 1.4.32, for CVE-2011-4362 and CVE-2012-5533.

Upgrade Information

As always, information on upgrading can be found in the Upgrade Guide.

Download

Downloads for new installs can be found on the mirrors here.
Upgrades can be found here.
Note: some mirrors are still syncing, it will be several hours from the time of this post until all are synced.

Linux : comandos grep, fgrep e egrep





Sintaxe: 

grep [opções] padrão arquivos
fgrep [opções] padrão arquivos
egrep [opções] padrão arquivos 

Opções:


  • -F :: O mesmo que fgrep. Interpreta padrão como uma expressão regular sem metacaracteres.
  • -E :: Similar a egrep. Interpreta padrão como uma expressão regular estendida.
  • -r :: Faz procura recursiva.
  • -e expr :: Procura pela expressão regular expr.
  • -n :: Exibe o número de linhas que contém o padrão.
  • -c :: Exibe apenas o número de linhas que contém o padrão de busca.
  • -f arquivo :: Lê o padrão a partir do arquivo especificado.
  • -i :: Não diferencia maiúsculas de minúsculas na procura.
  • -l :: Exibe os nomes de arquivos que contém o padrão.
  • -v :: Exibe as linhas que não contém o padrão.
  • -w :: Procura apenas palavras inteiras.

Observação: recomenda-se que o padrão esteja entre apóstrofos ('), pois alguns caracteres tem significado especial para o shell e podem ser interpretados erroneamente. 

Exemplos: 

Procura a palavra "tee" dentro do arquivo /etc/info-dir e exibe o número da linha onde ela ocorre: 

grep -n tee /etc/info-dir
70:* tee: (sh-utils) tee invocation. Redirect to multiple files
Procura todos os arquivos abaixo de /etc que possuem a palavra mouse: 

grep -r mouse /etc/* 

SHELL SCRIPT : Reiniciar o Apache com Log


Para os que tem necessidade de reiniciar o apache todos os dias eis um script que é só colocar no crontab e resolvemos o problema:



  • Criar o Script restartapache.sh



#!/bin/bash

hoje=$(date +"%y_%m_%d")


/etc/init.d/apache2 restart


hora=$(date +"%H:%M:%S %Z")


echo -ne "[$hora]  o apache foi reiniciado. \r\n"  >> log_ResetApache.$hoje.txt




  • Transforme o script em executável:


#chmod +x restartapache.sh


  • Edição  Crontab

# crontab -e

Feito. Precisamos agora adicionar o período (tempo) que o cron deve chamar o nosso script de backup.

A sintaxe do crontab é bastante fácil de se trabalhar. A sintaxe para chamar nosso script deve ficar assim:

mm HH DD MM DS /usr/local/bin/restartapache.sh

Onde:

mm: minutos
HH: horas
DD: dia
MM: mês
DS: dia da semana
/usr/local/bin/backup.sh: tarefa a ser realizada

Neste exemplo, faríamos com que o script seja executado todos os dias as 22hrs. Veja:

00 22 * * * /usr/local/bin/restartapache.sh

Pronto. Salve o arquivo, e reinicie o cron para que a rotina funcione:

# /etc/init.d/cron restart

LinkWithin

Related Posts Widget for Blogs by LinkWithin