Commit bc8029b9 authored by Boris Mühmer (ADESTIS)'s avatar Boris Mühmer (ADESTIS) 💬
Browse files

added various samples

parent 0a2d7ca1
Loading
Loading
Loading
Loading

.gitignore

0 → 100644
+6 −0
Original line number Diff line number Diff line
# === .gitignore ===

# generated files
*.exe

# === End Of File ===
 No newline at end of file

Makefile

0 → 100644
+16 −0
Original line number Diff line number Diff line
# === Makefile ===

all:

build: build-windows-exe

build-windows-exe: sshclient.exe

sshclient.exe: cmd/sshclient/main.go
	#GOOS=windows GOARCH=386 go build -ldflags "-s" -o $@ $<
	GOOS=windows GOARCH=386 go build -o $@ $<

clean:
	rm -f *.exe

# === End Of File ===
 No newline at end of file

cmd/persons/main.go

0 → 100644
+27 −0
Original line number Diff line number Diff line
package main

import (
	"fmt"
	"math/rand"
	"time"

	"repositories.muehmer.net/bsmrgo/playground/persons"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

// CLI usage: go run cmd/persons/main.go | grep -e '⚥'
func main() {
	fmt.Println("Persons")

	var ps [100]*persons.Person
	for i := range ps {
		ps[i] = persons.CreatePersonRandom()
	}

	for i, p := range ps {
		fmt.Printf("%03d: %s\n", i+1, p)
	}
}

cmd/sshclient/main.go

0 → 100644
+165 −0
Original line number Diff line number Diff line
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/user"

	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/knownhosts"
)

// manual pages:
// https://godoc.org/golang.org/x/crypto/ssh
// https://godoc.org/golang.org/x/crypto/ssh/knownhosts

// based on the following example(s):
// https://blog.ralch.com/tutorial/golang-ssh-connection/

// additional information
// https://en.wikibooks.org/wiki/OpenSSH/Client_Configuration_Files

const (
	formatDebugCleanup          = "deferred cleanup: %s\n"
	formatHostPort              = "%s:%s"
	formatUserSSHPrivateKeyFile = "%s/.ssh/id_rsa"
	formatUserSSHKnownHosts     = "%s/.ssh/known_hosts"
	formatResultDebug           = "result:\n%s"
	formatResultNormal          = "%s"
)

func main() {
	var u *user.User
	var err error
	var debug bool
	var host string
	var port string
	var login string
	var cmd string
	var sshPrivateKey ssh.AuthMethod
	var callbackHostKey ssh.HostKeyCallback
	var output []byte

	// access user name
	if u, err = user.Current(); err != nil {
		panic(err)
	}

	// command line parameters
	flag.BoolVar(&debug, "debug", false, "should program be debugged")
	flag.StringVar(&host, "host", "localhost", "hostname to connect to")
	flag.StringVar(&port, "port", "22", "port to connect to")
	flag.StringVar(&login, "login", u.Username, "login for connection")
	flag.StringVar(&cmd, "command", "hostname -f", "command to execute")
	flag.Parse()

	// show some information
	if debug {
		fmt.Fprintf(os.Stderr, "   login: %s\n", login)
		fmt.Fprintf(os.Stderr, "username: %s\n", u.Username)
		fmt.Fprintf(os.Stderr, "    name: %s\n", u.Name)
		fmt.Fprintf(os.Stderr, "     uid: %s\n", u.Uid)
		fmt.Fprintf(os.Stderr, "     gid: %s\n", u.Gid)
		fmt.Fprintf(os.Stderr, "home dir: %s\n", u.HomeDir)

		defer func() {
			fmt.Fprintf(os.Stderr, formatDebugCleanup, "main")
		} ()
	}

	// load user's known hosts
	if callbackHostKey, err = knownhosts.New(fmt.Sprintf(formatUserSSHKnownHosts, u.HomeDir)); err != nil {
		panic(err)
	}

	// load user's private key
	if sshPrivateKey, err = ReadSSHDefaultPrivateKey(u.HomeDir); err != nil {
		panic(err)
	}

	// setup ssh client configuration with user's private key
	sshConfig := &ssh.ClientConfig{
		User:            login,
		Auth:            []ssh.AuthMethod{sshPrivateKey},
		HostKeyCallback: callbackHostKey,
	}

	// establish a new SSH connection
	connection, err := ssh.Dial("tcp", fmt.Sprintf(formatHostPort, host, port), sshConfig)
	if err != nil {
		panic(err)
	}
	if debug {
		defer func() {
			fmt.Fprintf(os.Stderr, formatDebugCleanup, "connection")
			connection.Close()
		}()
	} else {
		defer connection.Close()
	}

	// create a new session
	session, err := connection.NewSession()
	if err != nil {
		panic(err)
	}
	if debug {
		defer func() {
			fmt.Fprintf(os.Stderr, formatDebugCleanup, "session")
			session.Close()
		}()
	} else {
		defer session.Close()
	}

	// execute command and capture output
	if output, err = session.CombinedOutput(cmd); err != nil {
		// process ExitError
		if ee := err.(*ssh.ExitError); ee != nil {
			if debug {
				fmt.Fprintf(os.Stderr, "status: %d\n", ee.ExitStatus())
				fmt.Fprintf(os.Stderr, "   msg: %s\n", ee.Msg())
				fmt.Fprintf(os.Stderr, "signal: %s\n", ee.Signal())
			}
			fmt.Fprintf(os.Stderr, "%s", string(output))
			os.Exit(ee.ExitStatus())
		}
		// process ExitMissingError
		if eme := err.(*ssh.ExitMissingError); eme != nil {
			fmt.Fprintf(os.Stderr, "session closed: %s\n", eme.Error())
			fmt.Fprintf(os.Stderr, "%s", string(output))
			os.Exit(-1)
		}
		// process all other errors
		panic(err)
	}

	// display result
	var formatResult string
	if debug {
		formatResult = formatResultDebug
	} else {
		formatResult = formatResultNormal
	}
	fmt.Printf(formatResult, string(output))
}

// ReadSSHDefaultPrivateKey reads the private SSH key from the default location: ~USER/.ssh/id_rsa
func ReadSSHDefaultPrivateKey(homepath string) (ssh.AuthMethod, error) {
	file := fmt.Sprintf(formatUserSSHPrivateKeyFile, homepath)
	buffer, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	key, err := ssh.ParsePrivateKey(buffer)
	if err != nil {
		return nil, err
	}

	return ssh.PublicKeys(key), nil
}

// End Of File
+1 −0
Original line number Diff line number Diff line
package concurrency
Loading