Skip to content

Commit

Permalink
expose tssh as a library
Browse files Browse the repository at this point in the history
  • Loading branch information
lonnywong committed Jul 13, 2024
1 parent c5263cb commit f6d0e73
Show file tree
Hide file tree
Showing 14 changed files with 224 additions and 46 deletions.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,44 @@ trzsz-ssh ( tssh ) offers additional useful features:
- Download from the [GitHub Releases](https://github.com/trzsz/trzsz-ssh/releases), unzip and add to `PATH` environment.
## Development
The `github.com/trzsz/trzsz-ssh/tssh` can be used as a library, for example:
```go
package main
import (
"log"
"os"
"github.com/trzsz/trzsz-ssh/tssh"
)
func main() {
// Example 1: execute command on remote server
client, err := tssh.SshLogin(&tssh.SshArgs{Destination: "[email protected]"})
if err != nil {
log.Fatal(err)
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
output, err := session.CombinedOutput("whoami")
if err != nil {
log.Fatal(err)
}
log.Printf("I'm %s", string(output))
// Example 2: run the tssh program
code := tssh.TsshMain([]string{"-t", "[email protected]", "bash -l"})
os.Exit(code)
}
```
## Contributing
Welcome and thank you for considering contributing. We appreciate all forms of support, from coding and testing to documentation and CI/CD improvements.
Expand Down
2 changes: 1 addition & 1 deletion cmd/tssh/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ import (
)

func main() {
os.Exit(tssh.TsshMain())
os.Exit(tssh.TsshMain(os.Args[1:]))
}
4 changes: 2 additions & 2 deletions tssh/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func getAgentClient(args *sshArgs, param *sshParam) agent.ExtendedAgent {
return agentClient
}

func forwardToRemote(client sshClient, addr string) error {
func forwardToRemote(client SshClient, addr string) error {
channels := client.HandleChannelOpen(kAgentChannelType)
if channels == nil {
return fmt.Errorf("agent: already have handler for %s", kAgentChannelType)
Expand Down Expand Up @@ -122,7 +122,7 @@ func forwardAgentRequest(channel ssh.Channel, addr string) {
forwardChannel(channel, conn)
}

func requestAgentForwarding(session sshSession) error {
func requestAgentForwarding(session SshSession) error {
ok, err := session.SendRequest(kAgentRequestName, true, nil)
if err != nil {
return err
Expand Down
6 changes: 3 additions & 3 deletions tssh/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ type tsshConfig struct {
wildcardPatterns []*ssh_config.Pattern
}

var userConfig = &tsshConfig{}
var userConfig *tsshConfig

func parseTsshConfig() {
path := filepath.Join(userHomeDir, ".tssh.conf")
Expand Down Expand Up @@ -218,8 +218,8 @@ func showTsshConfig() {
}
}

func initUserConfig(configFile string) error {
var err error
func initUserConfig(configFile string) (err error) {
userConfig = &tsshConfig{}
userHomeDir, err = os.UserHomeDir()
if err != nil {
debug("user home dir failed: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion tssh/ctrl_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ func startControlMaster(args *sshArgs, sshPath string) error {
return nil
}

func connectViaControl(args *sshArgs, param *sshParam) sshClient {
func connectViaControl(args *sshArgs, param *sshParam) SshClient {
ctrlMaster := getOptionConfig(args, "ControlMaster")
ctrlPath := getOptionConfig(args, "ControlPath")

Expand Down
2 changes: 1 addition & 1 deletion tssh/ctrl_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (
"strings"
)

func connectViaControl(args *sshArgs, param *sshParam) sshClient {
func connectViaControl(args *sshArgs, param *sshParam) SshClient {
ctrlMaster := getOptionConfig(args, "ControlMaster")
ctrlPath := getOptionConfig(args, "ControlPath")

Expand Down
2 changes: 1 addition & 1 deletion tssh/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func getSetEnvs(args *sshArgs) ([]*sshEnv, error) {
return envs, nil
}

func sendAndSetEnv(args *sshArgs, session sshSession) (string, error) {
func sendAndSetEnv(args *sshArgs, session SshSession) (string, error) {
sendEnvs, err := getSendEnvs(args)
if err != nil {
return "", err
Expand Down
14 changes: 7 additions & 7 deletions tssh/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ func listenOnLocal(args *sshArgs, addr *string, port string) (listeners []net.Li
return
}

func listenOnRemote(args *sshArgs, client sshClient, addr *string, port string) (listeners []net.Listener) {
func listenOnRemote(args *sshArgs, client SshClient, addr *string, port string) (listeners []net.Listener) {
listen := func(network, address string) {
listener, err := client.Listen(network, address)
if err != nil {
Expand All @@ -251,7 +251,7 @@ func listenOnRemote(args *sshArgs, client sshClient, addr *string, port string)
return
}

func stdioForward(client sshClient, addr string) (*sync.WaitGroup, error) {
func stdioForward(client SshClient, addr string) (*sync.WaitGroup, error) {
conn, err := client.DialTimeout("tcp", addr, 10*time.Second)
if err != nil {
return nil, fmt.Errorf("stdio forward failed: %v", err)
Expand Down Expand Up @@ -283,7 +283,7 @@ func (d sshResolver) Resolve(ctx context.Context, name string) (context.Context,
return ctx, []byte{}, nil
}

func dynamicForward(client sshClient, b *bindCfg, args *sshArgs) {
func dynamicForward(client SshClient, b *bindCfg, args *sshArgs) {
server, err := socks5.New(&socks5.Config{
Resolver: &sshResolver{},
Dial: func(ctx context.Context, network, addr string) (net.Conn, error) {
Expand Down Expand Up @@ -334,7 +334,7 @@ func netForward(local, remote net.Conn) {
<-done
}

func localForward(client sshClient, f *forwardCfg, args *sshArgs) {
func localForward(client SshClient, f *forwardCfg, args *sshArgs) {
remoteAddr := joinHostPort(f.destHost, strconv.Itoa(f.destPort))
for _, listener := range listenOnLocal(args, f.bindAddr, strconv.Itoa(f.bindPort)) {
go func(listener net.Listener) {
Expand All @@ -360,7 +360,7 @@ func localForward(client sshClient, f *forwardCfg, args *sshArgs) {
}
}

func remoteForward(client sshClient, f *forwardCfg, args *sshArgs) {
func remoteForward(client SshClient, f *forwardCfg, args *sshArgs) {
localAddr := joinHostPort(f.destHost, strconv.Itoa(f.destPort))
for _, listener := range listenOnRemote(args, client, f.bindAddr, strconv.Itoa(f.bindPort)) {
go func(listener net.Listener) {
Expand All @@ -386,7 +386,7 @@ func remoteForward(client sshClient, f *forwardCfg, args *sshArgs) {
}
}

func sshForward(client sshClient, args *sshArgs, param *sshParam) error {
func sshForward(client SshClient, args *sshArgs, param *sshParam) error {
// clear all forwardings
if strings.ToLower(getOptionConfig(args, "ClearAllForwardings")) == "yes" {
return nil
Expand Down Expand Up @@ -451,7 +451,7 @@ type x11Request struct {
ScreenNumber uint32
}

func sshX11Forward(args *sshArgs, client sshClient, session sshSession) {
func sshX11Forward(args *sshArgs, client SshClient, session SshSession) {
if args.NoX11Forward || !args.X11Untrusted && !args.X11Trusted && strings.ToLower(getOptionConfig(args, "ForwardX11")) != "yes" {
return
}
Expand Down
10 changes: 5 additions & 5 deletions tssh/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,7 @@ func getNetworkAddressFamily(args *sshArgs) string {
}
}

func sshConnect(args *sshArgs, client sshClient, proxy string) (sshClient, *sshParam, bool, error) {
func sshConnect(args *sshArgs, client SshClient, proxy string) (SshClient, *sshParam, bool, error) {
param, err := getSshParam(args)
if err != nil {
return nil, nil, false, err
Expand Down Expand Up @@ -1028,7 +1028,7 @@ func sshConnect(args *sshArgs, client sshClient, proxy string) (sshClient, *sshP

network := getNetworkAddressFamily(args)

proxyConnect := func(client sshClient, proxy string) (sshClient, *sshParam, bool, error) {
proxyConnect := func(client SshClient, proxy string) (SshClient, *sshParam, bool, error) {
debug("login to [%s], addr: %s", args.Destination, param.addr)
conn, err := client.DialTimeout(network, param.addr, 10*time.Second)
if err != nil {
Expand Down Expand Up @@ -1078,7 +1078,7 @@ func sshConnect(args *sshArgs, client sshClient, proxy string) (sshClient, *sshP
}

// has proxies
var proxyClient sshClient
var proxyClient SshClient
for _, proxy = range param.proxy {
proxyClient, _, _, err = sshConnect(&sshArgs{Destination: proxy}, proxyClient, proxy)
if err != nil {
Expand All @@ -1088,7 +1088,7 @@ func sshConnect(args *sshArgs, client sshClient, proxy string) (sshClient, *sshP
return proxyConnect(proxyClient, proxy)
}

func keepAlive(client sshClient, args *sshArgs) {
func keepAlive(client SshClient, args *sshArgs) {
getOptionValue := func(option string) int {
value, err := strconv.Atoi(getOptionConfig(args, option))
if err != nil {
Expand Down Expand Up @@ -1129,7 +1129,7 @@ func keepAlive(client sshClient, args *sshArgs) {
}()
}

func sshAgentForward(args *sshArgs, param *sshParam, client sshClient, session sshSession) {
func sshAgentForward(args *sshArgs, param *sshParam, client SshClient, session SshSession) {
if args.NoForwardAgent || !args.ForwardAgent && strings.ToLower(getOptionConfig(args, "ForwardAgent")) != "yes" {
return
}
Expand Down
14 changes: 10 additions & 4 deletions tssh/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,16 @@ func cleanupAfterLogin() {

var isTerminal bool = isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd())

func TsshMain() int {
// TrzMain is the main function of tssh program.
func TsshMain(argv []string) int {
// parse ssh args
var args sshArgs
parser := arg.MustParse(&args)
parser, err := arg.NewParser(arg.Config{Out: os.Stderr, Exit: os.Exit}, &args)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return -1
}
parser.MustParse(argv)

// debug log
if args.Debug {
Expand All @@ -129,7 +136,6 @@ func TsshMain() int {
defer cleanupOnExit()

// print message after stdin reset
var err error
defer func() {
if err != nil {
fmt.Fprintf(os.Stderr, "%v\r\n", err)
Expand All @@ -149,7 +155,7 @@ func TsshMain() int {
}

// execute local tools if necessary
if code, quit := execLocalTools(&args); quit {
if code, quit := execLocalTools(argv, &args); quit {
return code
}

Expand Down
Loading

0 comments on commit f6d0e73

Please sign in to comment.