RaspberryPI – Transferindo arquivos com netcat

Depois de alguns meses pois fui aos poucos trabalhando em cima de um kernel redondinho e o mais leve possível para a minha aplicação, rootfs apenas com o que eu classifiquei como importante, visto que não demandaria acesso via web, e nem com nenhum tipo de configurador apenas coletar dados, salvar em um banco de dados e exibir algumas informações na display (vídeo) conectado no HDMI do RaspberryPI.

Até tem uma sacadinha que é chamada no xinetd para atualizar o software mas é algo bem restrito assim como os que são chamados na comunicação, enfim…

Algo me ocorreu esta semana, onde após gravar no SD Card subir o sistema e ficar horas em testes precisei subir 2 scripts (Shell) que fariam coisas bobas, porém eu não tinha um sftp, Ftpd igual nos roteadores que tem por ae, SSH? Não instalei nem openssh-server quanto menos dropbear, com o dropbear acho que seria suficiente apesar de não permitir transferência de arquivo me parece já ter visto algumas vezes uma “gambizinha” com scp, porém eu não poderia instalar algo com ipkg apenas para subir dois scripts, o que fazer?

1) Abrir os scripts em outro local e ir passando o código na mão?

3) Desligar o RaspberryPI que estava com uptime dos testes com mais de 5 dias e copiar os scripts :( ?

2) Tirar as crianças da sala, regaçar as mangas e mostrar porque sua mulher te escolheu :) ?

Brincadeiras a parte, mas no momento em que eu estava desligando o brinquedo lembrei de uma ferramenta que é show de bola e já salvou muita gente, o netcat (nc).

Segundo o Wikipedia netcat foi escrito em março de 1996 ( ele tem 18 anos, já pode tirar carta :) ), conheço ele faz tempo mais digo que foi em torno de 2006, onde eu procurava algo para transferir arquivo :), mas ele vai além disso, realizando as combinações dos seus parâmetros ele pode se tornar um port scan, servidor tcp ou udp, um chatzinho, além de outras outras mais maldosas.

Vamos dar uma olhada no help desse cara:

cleiton@nb-bueno ~/projeto/shell_script $ man nc
NC(1) BSD General Commands Manual

NAME
nc -- arbitrary TCP and UDP connections and listens

SYNOPSIS
nc [-46DdhklnrStUuvzC] [-i interval] [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol] [-x
proxy_address[:port]] [hostname] [port[s]]

DESCRIPTION
The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, send UDP packets, lis-
ten on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6. Unlike telnet(1), nc scripts nicely, and separates error
messages onto standard error instead of sending them to standard output, as telnet(1) does with some.

Common uses include:

o simple TCP proxies
o shell-script based HTTP clients and servers
o network daemon testing
o a SOCKS or HTTP ProxyCommand for ssh(1)
o and much, much more

The options are as follows:

-4 Forces nc to use IPv4 addresses only.

-6 Forces nc to use IPv6 addresses only.
...
-l Used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host. It is an error to use
this option in conjunction with the -p, -s, or -z options. Additionally, any timeouts specified with the -w option are ignored.

-n Do not do any DNS or service lookups on any specified addresses, hostnames or ports.

-P proxy_username
Specifies a username to present to a proxy server that requires authentication. If no username is specified then authentication will not be
attempted. Proxy authentication is only supported for HTTP CONNECT proxies at present.

-p source_port
Specifies the source port nc should use, subject to privilege restrictions and availability. It is an error to use this option in conjunc-
tion with the -l option.

-r Specifies that source and/or destination ports should be chosen randomly instead of sequentially within a range or in the order that the
system assigns them.
...
-s source_ip_address
Specifies the IP of the interface which is used to send the packets. It is an error to use this option in conjunction with the -l option.

-u Use UDP instead of the default option of TCP.

-v Have nc give more verbose output.

-w timeout
If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. The -w flag has no effect on the
-l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.

...

CLIENT/SERVER MODEL
It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For
example:

$ nc -l 1234

nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:

$ nc 127.0.0.1 1234

There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After
the connection has been set up, nc does not really care which side is being used as a 'server' and which side is being used as a 'client'. The con-
nection may be terminated using an EOF ('^D').

DATA TRANSFER
The example in the previous section can be expanded to build a basic data transfer model. Any information input into one end of the connection will
be output to the other end, and input and output can be easily captured in order to emulate file transfer.

Start by using nc to listen on a specific port, with output captured into a file:

$ nc -l 1234 > filename.out

Using a second machine, connect to the listening nc process, feeding it the file which is to be transferred:

$ nc host.example.com 1234 < filename.in

After the file has been transferred, the connection will close automatically.

...

PORT SCANNING
It may be useful to know which ports are open and running services on a target machine. The -z flag can be used to tell nc to report open ports,
rather than initiate a connection. For example:

$ nc -z host.example.com 20-30
Connection to host.example.com 22 port [tcp/ssh] succeeded!
Connection to host.example.com 25 port [tcp/smtp] succeeded!

The port range was specified to limit the search to ports 20 - 30.

...

EXAMPLES
Open a TCP connection to port 42 of host.example.com, using port 31337 as the source port, with a timeout of 5 seconds:

$ nc -p 31337 -w 5 host.example.com 42

Open a UDP connection to port 53 of host.example.com:

$ nc -u host.example.com 53

Open a TCP connection to port 42 of host.example.com using 10.1.2.3 as the IP for the local end of the connection:

$ nc -s 10.1.2.3 host.example.com 42

Create and listen on a Unix Domain Socket:

$ nc -lU /var/tmp/dsocket

Connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4, port 8080. This example could also be used by ssh(1); see the ProxyCommand
directive in ssh_config(5) for more information.

$ nc -x10.2.3.4:8080 -Xconnect host.example.com 42

The same example again, this time enabling proxy authentication with username ``ruser'' if the proxy requires it:

$ nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

SEE ALSO
cat(1), ssh(1)

AUTHORS
Original implementation by *Hobbit* <[email protected]>.
Rewritten with IPv6 support by Eric Jackson <[email protected]>.

Eu cortei alguns pedaços, deixei os parâmetros que irei utilizar e alguns outros interessantes que você pode brincar ae, no próprio man dele já tirou minhas duvidas quanto a transferir arquivos em DATA TRANSFER, o que nos interessa são -l para iniciar o socket em escuta ou melhor roda em modo servidor, -v maior detalhamento na saída e -n que não resolve nomes DNS neste caso sem utilidade então não precisa resolver.
Então no RaspberryPI que irá receber os scripts atuará como servidor, e o meu notebook como cliente que irá enviar o script, abaixo o comando no RaspberryPI:

pi@raspberrypi ~ $ nc -nlv 5670 > cpu_load.sh
Listening on [0.0.0.0] (family 0, port 5670)
Connection from [192.168.0.50] port 5670 [tcp/*] accepted (family 2, sport 47445)
pi@raspberrypi ~ $

No notebook ficou assim:

cleiton@nb-bueno ~/projeto/shell_script $ nc 192.168.0.12 5670 < cpu_load.sh
cleiton@nb-bueno ~/projeto/shell_script $

No meu caso 192.168.0.50 é o meu notebook e 192.168.0.12 é o RaspberryPI.

Depois de transferido é automaticamente fechado, nos dois lados! Um detalhe importante a ser tomado é que a transferência não é criptografada, então como solução não é interessante pois qualquer sniffer conseguiria abstrair a sua informação.

Tem várias outras opções legais para serem usadas como -w para timeout, caso for abrir a conexão para alguém estipule um tempo, para não acabar abrindo brecha né ;), lembro-me muito bem de uma opção onde era possível executar um comando após “bater” em uma porta do netcat em escuta, mas pelo que vi removeram pelo menos dessa versão que estou usando, e dando uma pesquisada achei alguém explicando aqui, gostei de ver suporte a ipv4 e ao ipv6 isso é muito legal e o -P para passar autenticação de um proxy, show de bola também.

Pessoal a ideia do post era essa, ou seja, um problema que encontrei e como fiz para resolver que com certeza poderá ajudar vocês quando precisar transferir algo com Linux e não tiver internet para pesquisar ou até mesmo em um local remoto.

Espero que tenham gostado e até a próxima!

Referências

http://www.pedropereira.net/netcat-nc-tutorial-linux-windows/
http://www.vivaolinux.com.br/artigo/Tutorial-Netcat/
http://www.dicas-l.com.br/arquivo/usando_o_netcat.php
http://www.cooperati.com.br/2011/10/13/netcat-um-comando-multiplataforma-e-multiuso/

Share Button

CC BY-NC-SA 4.0 RaspberryPI – Transferindo arquivos com netcat by Cleiton Bueno is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.