dotfiles/home/private_bin/executable_tunnel

65 lines
1.2 KiB
Text
Raw Normal View History

2024-08-02 11:21:19 -05:00
#!/usr/bin/env nu
2024-08-08 11:59:53 -05:00
2024-08-06 11:30:56 -05:00
use std log
2024-08-02 11:21:19 -05:00
def start-ssh-controller [host: string] {
2024-08-08 11:59:53 -05:00
log info $"initializing connection to ($host)"
2024-08-02 11:21:19 -05:00
ssh -M -f -N $host
}
def is-null [ name: string, arg: any] {
if $arg == null {
2024-08-08 11:59:53 -05:00
log error $"expected argument for --($name)"; exit 1
2024-08-02 11:21:19 -05:00
}
}
# script `--help` will improve :)
# https://github.com/nushell/nushell/pull/13445
# control background tunnels
# usage:
2024-08-08 11:59:53 -05:00
# tunnel up -p 4321 computer
# tunnel down computer
2024-08-02 11:21:19 -05:00
def main [] {
print "use subcommands up/down to control ssh tunnels"
help main
}
# activate ssh tunnel
def "main up" [
2024-08-08 11:59:53 -05:00
host: string # host name
--port: int # port number
2024-08-02 11:21:19 -05:00
] {
is-null "port" $port
if (ssh -O check $host | complete).exit_code != 0 {
start-ssh-controller $host
}
ssh -fNL $"($port):localhost:($port)" $host
}
# shutdown ssh tunnels on host
def "main down" [
2024-08-08 11:59:53 -05:00
host: string # host name
2024-08-02 11:21:19 -05:00
] {
2024-08-08 11:59:53 -05:00
log info $"exiting connection to ($host)"
2024-08-02 11:21:19 -05:00
ssh -O exit $host
}
2024-08-06 11:30:56 -05:00
def "main show" [] {
2024-08-08 11:59:53 -05:00
let sockets = (
ls ~/.ssh/
| where name =~ control
| get name
)
2024-08-06 11:30:56 -05:00
let n_sockets = $sockets | length
if $n_sockets > 0 {
print $"($n_sockets) active connections"
2024-08-08 11:59:53 -05:00
$sockets
| split column "-"
| get column2
2024-08-06 11:30:56 -05:00
} else {
log info "no open connections"
}
}