utils/tunnel-nim/tunnel.nim

46 lines
1.5 KiB
Nim
Raw Normal View History

2024-08-16 14:07:25 -05:00
import std/[os, osproc, sequtils, strformat, strutils, sugar]
import cligen
proc checkHost(host: seq[string]): string =
case host.len:
of 1: return host[0]
2024-08-16 15:39:21 -05:00
of 0: quit "expected hostname"
else: quit "expected one positinal argument"
2024-08-16 14:07:25 -05:00
2024-08-16 15:39:21 -05:00
proc check(name: string): bool = (execCmd &"ssh -O check {name}") == 0
proc startSsh(name: string) = discard execCmd &"ssh -M -f -N {name}"
proc activateTunnel(name: string, port: int): int = execCmd &"""ssh -fNL "{port}:localhost:{port}" {name}"""
proc exitSsh(name: string):int = execCmd &"ssh -O exit {name}"
2024-08-16 14:07:25 -05:00
2024-08-16 15:39:21 -05:00
proc up(port: int, host: seq[string]) =
2024-08-16 14:07:25 -05:00
## activate a tunnel
let name = checkHost host
2024-08-27 13:18:05 -05:00
echo "activating connection to: ", name
2024-08-16 14:07:25 -05:00
if not check(name):
startSsh(name)
quit activateTunnel(name, port)
2024-08-16 15:39:21 -05:00
proc down(host: seq[string]) =
2024-08-16 14:07:25 -05:00
## disable all tunnels
let name = checkHost host
2024-08-27 13:18:05 -05:00
echo "deactivating connection to: ", name
2024-08-16 14:07:25 -05:00
quit exitSsh(name)
proc show() =
## show active connections
let sshDir = (getEnv "HOME") / ".ssh"
2024-08-16 15:39:21 -05:00
let controllers =
2024-08-16 14:07:25 -05:00
collect(for _,p in walkDir(sshDir): p)
.map(extractFilename)
.filterIt(it.startsWith("control"))
echo &"{controllers.len} active connections"
if controllers.len == 0: quit 0
echo "hosts:"
echo controllers.mapIt(" " & it.split('-')[1]).join("\n")
2024-08-16 15:39:21 -05:00
const
hostUsage = "$command [flags] hostname\n${doc}Options:\n$options"
2024-08-16 14:07:25 -05:00
usage = "$command [flags]\n${doc}Options:\n$options"
dispatchMulti([up, usage=hostUsage], [down, usage=hostUsage], [show, usage=usage])