Once in awhile sshd will break on your server, maybe after an update and you need to send long lines, maybe a cipher list from one server to another. Typing on console it’s an option but it will take a lot of time and it’s also error prone. If you’re using macOS you can use Automator to type in a long text, but still not as easy as using netcat and won’t transfer files.
With netcat/nc you can do a nice trick, on the destination you can start nc in server/listen mode and send the text from your client or source. Here is an example:
destination% % sudo nc -l 22 > /tmp/netcat_text
Now on the source computer do this:
source% nc destination 22
…press ctrl+c when done.
Let’s check the server:
destination% cat /tmp/netcat_text
There you go, you just transferred the text, now you can use netcat_text and append it to your sshd_config:
cat /tmp/netcat_text >> /etc/sshd/sshd_conf
What if you’d like to transfer a binary or package?
You can use scp. No, you just wish you could use scp, if your sshd is broken scp won’t work. The good new is, this can be done as well with nc just the file has to be converted to base64. On the destination you do similar as before for now:
destination% nc -l 22 > /tmp/file
On the source we’re going to create a base64 from the file and pipe it to netcat. In the following example I transferred an image:
source% base64 -i "Screenshot 2023-01-15 at 11.40.46.png" | nc destination 22
Remember, on destination this is a base64 encoded file, we need to decode it before using it:
destination% base64 -d /tmp/file > image.png
Before wrapping up let’s check if the files are the same:
source% file "Screenshot 2023-01-15 at 11.40.46.png"
Screenshot 2023-01-15 at 11.40.46.png: PNG image data, 911 x 630, 8-bit/color RGBA, non-interlaced
source% md5 "Screenshot 2023-01-15 at 11.40.46.png"
MD5 (Screenshot 2023-01-15 at 11.40.46.png) = adec48fd42852d574a918b35ca8cc7d9
destination% file image.png
image.png: PNG image data, 911 x 630, 8-bit/color RGBA, non-interlaced
destination% md5 image.png
MD5 (image.png) = adec48fd42852d574a918b35ca8cc7d9
Good, this is the same file!
Don’t forget to clean up after yourself and delete the base64 encoded files.
WARNING! Netcat does not encrypt the data, so keep that in mind! This is also a good reminder to keep unused ports closed on the firewall, only open the ones you really need, nothing else.
Note: stunnel can be used with netcat to encrypt the transfer, this is slightly more complicated but very useful