{"id":775,"date":"2014-04-10T00:19:22","date_gmt":"2014-04-10T03:19:22","guid":{"rendered":"http:\/\/www.viazap.com.br\/?p=775"},"modified":"2014-04-10T00:19:22","modified_gmt":"2014-04-10T03:19:22","slug":"shell-script-para-web","status":"publish","type":"post","link":"https:\/\/blog.clusterweb.com.br\/?p=775","title":{"rendered":"Shell Script para WEB"},"content":{"rendered":"<p>&nbsp;<\/p>\n<table width=\"100%\" border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n<tbody>\n<tr>\n<td colspan=\"2\"><b>Iniciando \/ Vari\u00e1veis de ambiente<\/b><\/p>\n<div>\n<h1>Iniciando<\/h1>\n<p>Nas configura\u00e7\u00f5es padr\u00f5es do\u00a0<em>Apache<\/em>, existe um diret\u00f3rio j\u00e1 pr\u00e9-definido para scripts CGI rodarem. \u00c9 o\u00a0<span>\/<\/span>usr\/lib\/cgi-bin\/.<\/p>\n<p>Irei criar um arquivo com o nome\u00a0<span>tutorial.sh<\/span>. Nos scripts CGI, a sa\u00edda dos scripts (<span>\/dev\/stdout<\/span>\u00a0e\u00a0<span>\/dev\/stderr<\/span>), s\u00e3o enviadas para o cliente, as primeiras linhas do script ser\u00e3o o cabe\u00e7alho de resposta da requisi\u00e7\u00e3o HTTP.<\/p>\n<p>Desse modo, podemos for\u00e7ar o download de arquivos, fazer redirecionamentos, etc, a quebra de linha \u00e9 que separa o que ser\u00e1 o cabe\u00e7alho e o que ser\u00e1 o resto da resposta.<\/p>\n<p>Voltando ao arquivo\u00a0<span>tutorial.sh<\/span>, dentro do arquivo, coloque as seguintes linhas:<\/p>\n<div>#!\/bin\/bash<br \/>\necho -e &#8220;Content-Type: text\/plain\\n&#8221;\u00a0\u00a0\u00a0\u00a0# \u00c9 o Cabe\u00e7alho, e a quebra de linha<br \/>\necho &#8220;Hello World&#8221;\u00a0\u00a0\u00a0\u00a0# Agora \u00e9 o resto do request, o conte\u00fado que \u00e9 exibido pelos navegadores.<\/div>\n<p>Salve o arquivo e deixe as permiss\u00f5es como 775 (lembrando: r = 4, w = 2, x = 1).<\/p>\n<p>Acesse o link:\u00a0<span>http:\/\/localhost\/cgi-bin\/tutorial.sh<\/span>\u00a0E ver\u00e1 a mensagem:\u00a0<span>Hello World<\/span><\/p>\n<p>Por padr\u00e3o, o Apache j\u00e1 configura o cabe\u00e7alho de resposta.<\/p>\n<p>Se n\u00e3o quiser, voc\u00ea pode p\u00f4r no come\u00e7o do script:\u00a0<span>echo -e &#8220;\\n&#8221; ou printf &#8220;\\n\\n&#8221;<\/span>, e deixar que o Apache configure o cabe\u00e7alho, que normalmente, ser\u00e1 algo parecido com isso:\u00a0<!--more--><\/p>\n<div>HTTP\/1.1 200 OK<br \/>\nDate: [&#8230;]<br \/>\nServer: Apache [&#8230;]<br \/>\nContent-Type: text\/x-sh<\/div>\n<h1>Vari\u00e1veis de ambiente<\/h1>\n<p>Em Shell Script, podemos ver quais s\u00e3o as vari\u00e1veis de ambiente, usando o comando\u00a0<span>env<\/span>. Se voc\u00ea digitar esse comando em um terminal, ser\u00e3o listadas diversas vari\u00e1veis, como SHELL, HOME, USERNAME, etc.<\/p>\n<p>Para listarmos as vari\u00e1veis de ambiente no Apache, basta incluir no script o comando\u00a0<span>env<\/span>, ficando da seguinte forma:<\/p>\n<div>#!\/bin\/bash<br \/>\necho -e &#8220;Content-Type: text\/plain\\n&#8221;<br \/>\nenv<\/div>\n<p>Salvei esse arquivo e acessei a p\u00e1gina WEB usando o comando\u00a0<span>curl<\/span>. O resultado, foi:<\/p>\n<p><strong>$ curl -i localhost\/cgi-bin\/tutorial.sh<\/strong><br \/>\n<sub><\/sub><sub>HTTP\/1.1 200 OK<br \/>\nDate: Tue, 25 Mar 2014 00:24:04 GMT<br \/>\nServer: Apache\/2.2.22 (Debian)<br \/>\nVary: Accept-Encoding<br \/>\nTransfer-Encoding: chunked<br \/>\nContent-Type: text\/plain<\/p>\n<p>SERVER_SIGNATURE=<\/sub><\/p>\n<address>Apache\/2.2.22 (Debian)<br \/>\nServer at localhost Port 80<\/address>\n<p><sub><\/p>\n<p>HTTP_USER_AGENT=curl\/7.26.0<br \/>\nSERVER_PORT=80<br \/>\nHTTP_HOST=localhost<br \/>\nDOCUMENT_ROOT=\/var\/www<br \/>\nSCRIPT_FILENAME=\/usr\/lib\/cgi-bin\/tutorial.sh<br \/>\nREQUEST_URI=\/cgi-bin\/tutorial.sh<br \/>\nSCRIPT_NAME=\/cgi-bin\/tutorial.sh<br \/>\nREMOTE_PORT=46944<br \/>\nPATH=\/usr\/local\/bin:\/usr\/bin:\/bin<br \/>\nPWD=\/usr\/lib\/cgi-bin<br \/>\nSERVER_ADMIN=webmaster@localhost<br \/>\nHTTP_ACCEPT=*\/*<br \/>\nREMOTE_ADDR=127.0.0.1<br \/>\nSHLVL=1<br \/>\nSERVER_NAME=localhost<br \/>\nSERVER_SOFTWARE=Apache\/2.2.22 (Debian)<br \/>\nQUERY_STRING=<br \/>\nSERVER_ADDR=127.0.0.1<br \/>\nGATEWAY_INTERFACE=CGI\/1.1<br \/>\nSERVER_PROTOCOL=HTTP\/1.1<br \/>\nREQUEST_METHOD=GET<br \/>\n_=\/usr\/bin\/env\u00a0<\/sub><\/p>\n<p>Entendendo algumas vari\u00e1veis:<\/p>\n<ul>\n<li><span>HTTP_USER_AGENT<\/span>\u00a0:: User-agent que o cliente est\u00e1 usando. Pode ser usada para pegar informa\u00e7\u00f5es sobre quem visita a sua p\u00e1gina (navegador e sistema operacional).<\/li>\n<li><span>REQUEST_METHOD<\/span>\u00a0:: M\u00e9todo de requisi\u00e7\u00e3o utilizado, exemplo: GET, PUT, POST, OPTIONS, HEAD. Pode ser bem \u00fatil, pelo menos para mim, j\u00e1 foi.<\/li>\n<li><span>QUERY_STRING<\/span>\u00a0:: Dados enviados via GET. Exemplo:\u00a0<span>localhost\/cgi-bin\/tutorial.sh?a=f&amp;b=f<\/span>\u00a0(sendo: a = f e b = f).<\/li>\n<li><span>REMOTE_ADDR<\/span>\u00a0:: IP do cliente.<\/li>\n<\/ul>\n<p>Exemplo de utiliza\u00e7\u00e3o de vari\u00e1veis de ambiente:<\/p>\n<div>#!\/bin\/bash<\/p>\n<p>cat &lt;&lt;a<br \/>\nContent-Type: text\/plain<\/p>\n<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br \/>\nSeu User-agent =&gt; $HTTP_USER_AGENT<br \/>\nSeu I.P =&gt; $REMOTE_ADDR<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br \/>\nA<\/p><\/div>\n<p>Testando:<\/p>\n<p><strong>$ curl localhost\/cgi-bin\/tutorial.sh<\/strong><br \/>\n<sub>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br \/>\nSeu User-agent =&gt; curl\/7.26.0<br \/>\nSeu I.P =&gt; 127.0.0.1<br \/>\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;\u00a0<\/sub><\/p>\n<\/div>\n<\/td>\n<\/tr>\n<tr>\n<td colspan=\"2\"><b>POST e GET \/ Exemplos finais<\/b><\/p>\n<div>\n<h1>Pegando dados enviados via POST e GET<\/h1>\n<p>Quando trabalhamos com desenvolvimento WEB, \u00e9 comum receber dados via POST e\/ou GET. Come\u00e7arei com o GET, para POST, \u00e9 praticamente a mesma coisa, s\u00f3 muda mesmo quando se faz upload de arquivos.<\/p>\n<p>Em bash script, a vari\u00e1vel IFS funciona como uma fun\u00e7\u00e3o split. Colocamos o que ser\u00e1 delimitado, a vari\u00e1vel seguinte se transforma em um vetor. Depois, usando o la\u00e7o\u00a0<span>for<\/span>, podemos extrair os campos e valores respectivos enviados via GET:<\/p>\n<div>d#!\/bin\/bash\u00a0echo -e &#8220;\\n&#8221;<br \/>\nIFS=&#8217;=&amp;&#8217;<br \/>\nGET=($QUERY_STRING)<\/p>\n<p>for ((i=0; i&lt;${#GET[@]}; i+=2))<br \/>\ndo<br \/>\necho &#8220;${GET[@]:$i:1} = ${GET[@]:$i+1:1}&#8221;<br \/>\ndone<\/p><\/div>\n<p>Testando:<\/p>\n<p><strong>$ curl &#8216;localhost\/cgi-bin\/tutorial.sh?teste=ffff&amp;teste2=xxxxx&#8217;<\/strong><br \/>\n<sub>\u00a0teste\u00a0=\u00a0ffff<br \/>\nteste2\u00a0=\u00a0xxxxx\u00a0<\/sub><\/p>\n<p>Com POST, a \u00fanica diferen\u00e7a \u00e9 que n\u00e3o existe uma vari\u00e1vel de ambiente com os valores. Para obter esses valores, basta o seguinte comando:\u00a0<strong>read variavel<\/strong><\/p>\n<p>Os dados enviados via POST ficam em\u00a0<span>\/dev\/stdin<\/span>, por isso, quando utilizamos o\u00a0<span>read<\/span>, esses valores s\u00e3o obtidos. Feito isso, \u00e9 s\u00f3 trocar o GET por POST:<\/p>\n<div>#!\/bin\/bash<br \/>\necho -e &#8220;\\n&#8221;<br \/>\nread var<br \/>\nIFS=&#8217;=&amp;&#8217;<br \/>\nPOST=($var)<\/p>\n<p>for ((i=0; i&lt;${#POST[@]}; i+=2))<br \/>\ndo<br \/>\necho &#8220;${POST[@]:$i:1} = ${POST[@]:$i+1:1}&#8221;<br \/>\ndone<\/p><\/div>\n<p>Testando:<\/p>\n<p><strong>$ curl localhost\/cgi-bin\/tutorial.sh &#8211;data &#8220;autor=mmxm&amp;blog=hc0der.blogspot.com&#8221;<\/strong><br \/>\n<sub>\u00a0autor\u00a0=\u00a0mmxm<br \/>\nblog\u00a0=\u00a0hc0der.blogspot.com\u00a0<\/sub><\/p>\n<h1>Exemplos finais<\/h1>\n<p>Alguns exemplos que podem ser \u00fateis (hehe).<\/p>\n<p>Redirecionamento, usando\u00a0<span>header<\/span>:<\/p>\n<div>#!\/bin\/bash<\/p>\n<p>printf &#8220;Status: 302 Found\\n&#8221;<br \/>\nprintf &#8220;Location: http:\/\/hc0der.blogspot.com\\n\\n&#8221;;<\/p><\/div>\n<p>Testando:<\/p>\n<p><strong>$ curl localhost\/cgi-bin\/tutorial.sh -i<\/strong><br \/>\n<sub>HTTP\/1.1 302 Found<br \/>\nDate: Wed, 26 Mar 2014 00:01:08 GMT<br \/>\nServer: Apache\/2.2.22 (Debian)<br \/>\nLocation: http:\/\/hc0der.blogspot.com<br \/>\nContent-Length: 0<br \/>\nContent-Type: text\/x-sh\u00a0<\/sub><\/p>\n<p>Falso &#8220;404 not found&#8221;:<\/p>\n<div>#!\/bin\/bash<\/p>\n<p>printf &#8220;Status: 404 Not Found\\n\\n&#8221;<\/p><\/div>\n<p>Testando:<\/p>\n<p><strong>$ curl localhost\/cgi-bin\/tutorial.sh -i<\/strong><br \/>\n<sub>HTTP\/1.1 404 Not Found<br \/>\nDate: Wed, 26 Mar 2014 00:06:53 GMT<br \/>\nServer: Apache\/2.2.22 (Debian)<br \/>\nContent-Length: 0<br \/>\nContent-Type: text\/x-sh\u00a0<\/sub><\/p>\n<p>Fazendo download de arquivos:<\/p>\n<div>#!\/bin\/bash<\/p>\n<p>arquivo_local=\/etc\/issue stat -c &#8220;Content-Length: %s&#8221; $arquivo_local # enviar tamanho do arquivo em bytes<br \/>\nprintf &#8220;Content-Disposition: attachment; filename=$(basename $arquivo_local)\\n&#8221;<br \/>\nprintf &#8220;Content-Type: application\/octet-stream\\n\\n&#8221;<br \/>\ncat $arquivo_local<\/p><\/div>\n<p>Testando:<\/p>\n<p>$<strong>\u00a0curl localhost\/cgi-bin\/tutorial.sh -i<\/strong><br \/>\n<sub>HTTP\/1.1 200 OK<br \/>\nDate: Wed, 26 Mar 2014 00:13:32 GMT<br \/>\nServer: Apache\/2.2.22 (Debian)<br \/>\nContent-Disposition: attachment; filename=issue<br \/>\nContent-Length: 17<br \/>\nVary: Accept-Encoding<br \/>\nContent-Type: application\/octet-stream<\/p>\n<p>nao te interessa\u00a0<\/sub><\/p>\n<p>E, via browser:<\/p>\n<div><img loading=\"lazy\" decoding=\"async\" alt=\"Linux: Shell Script para WEB\" src=\"http:\/\/img.vivaolinux.com.br\/imagens\/artigos\/comunidade\/1395873404.download.png\" width=\"451\" height=\"348\" \/><\/div>\n<h1>Conclus\u00e3o<\/h1>\n<p>Para uma introdu\u00e7\u00e3o, est\u00e1 de bom tamanho. Bash Script \u00e9 complicado, conhecendo bem as ferramentas do seu sistema, n\u00e3o h\u00e1 limites para o que voc\u00ea pode fazer =&gt;.<\/p><\/div>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; Iniciando \/ Vari\u00e1veis de ambiente Iniciando Nas configura\u00e7\u00f5es padr\u00f5es do\u00a0Apache, existe um diret\u00f3rio j\u00e1 pr\u00e9-definido para scripts CGI rodarem. \u00c9 o\u00a0\/usr\/lib\/cgi-bin\/. Irei criar um arquivo com o nome\u00a0tutorial.sh. Nos scripts CGI, a sa\u00edda dos scripts (\/dev\/stdout\u00a0e\u00a0\/dev\/stderr), s\u00e3o enviadas para o cliente, as primeiras linhas do script ser\u00e3o o cabe\u00e7alho de resposta da requisi\u00e7\u00e3o HTTP. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[1,42,501],"tags":[355,502,64,416],"class_list":["post-775","post","type-post","status-publish","format-standard","hentry","category-viazap","category-leitura-recomendada","category-shell-script","tag-para","tag-script","tag-shell","tag-web"],"_links":{"self":[{"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/posts\/775","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=775"}],"version-history":[{"count":1,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/posts\/775\/revisions"}],"predecessor-version":[{"id":776,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=\/wp\/v2\/posts\/775\/revisions\/776"}],"wp:attachment":[{"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=775"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=775"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.clusterweb.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=775"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}