⚡ Secure shell (ssh) client in 80 lines of Go code

preview_player
Показать описание
Sometimes you need a tool or service to run a command on a remote system and capture its output safely. Secure shell has long been the tool for making such remote connections. Thankfully, Go comes with the standard crypto/ssh package which has full support for creating both ssh clients and servers. But with all that power it can be hard to just do the regular easy stuff, like just run a command and get its output. This process can be simplified by making some sensible assumptions about default settings. Here's how to do that in Go.

One great advantage of this approach is that there is absolutely no requirement to install any ssh packages on the host system at all. The Go crypto/ssh library covers all the bases enabling things like FROM SCRATCH containers that encapsulate a single binary that includes a light-weight, fully functional ssh client.

1. Get the user and target host IP and port
2. Create an SSH client and dial a TCP connection
3. Create a Session and set parameters and stdin (if we have it)
4. Run the Session to execute the command remotely
5. Buffer the stdout, stderr into strings
6. Return the stdout, stderr, and errors (if any)

Bonus: timeout after a reasonable about of time.

Thanks sponsors, subs, and followers:

Рекомендации по теме
Комментарии
Автор

Skip to 23:00 or 29:00 if you already know well the background, context and history. This ranks pretty high for "youtube golang ssh" so you may want to skip forward if all you're looking for is the Go specifics. Cheers and TY Rob.

thisisreallyme
Автор

Hey Rob at 35:12 you discuss mention not getting the exit code, and having to parse. The Python Paramiko library has nearly the same limitation: you can ask the library for the exit code, or you can ask the library for the STDOUT, but you can not ask Paramiko for BOTH details. (Or, this was true a fw years ago... maybe it's improved). So this feels like some inherent limitation of SSH libraries.

thisisreallyme
Автор

Wanted to say that your Go videos got me inspired to start learning it and is such a "just works" - "get things done" language, which is amazing, keep the good work going

kenneth_mata
Автор

Very interesting and informative video. Thanks a lot for going into the small details.

dzilbxp