Last active
February 13, 2023 03:18
-
-
Save blacknon/c915d15f825624893d3983b8b462155e to your computer and use it in GitHub Desktop.
Golang ssh client (support Control key)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
"golang.org/x/crypto/ssh" | |
"golang.org/x/crypto/ssh/terminal" | |
) | |
func main() { | |
host := "target.host.local" | |
port := "22" | |
user := "user" | |
pass := "password" | |
// Create sshClientConfig | |
sshConfig := &ssh.ClientConfig{ | |
User: user, | |
Auth: []ssh.AuthMethod{ | |
ssh.Password(pass), | |
}, | |
HostKeyCallback: ssh.InsecureIgnoreHostKey(), | |
} | |
// SSH connect. | |
client, err := ssh.Dial("tcp", host+":"+port, sshConfig) | |
// Create Session | |
session, err := client.NewSession() | |
defer session.Close() | |
// キー入力を接続先が認識できる形式に変換する(ここがキモ) | |
fd := int(os.Stdin.Fd()) | |
state, err := terminal.MakeRaw(fd) | |
if err != nil { | |
fmt.Println(err) | |
} | |
defer terminal.Restore(fd, state) | |
// ターミナルサイズの取得 | |
w, h, err := terminal.GetSize(fd) | |
if err != nil { | |
fmt.Println(err) | |
} | |
modes := ssh.TerminalModes{ | |
ssh.ECHO: 1, | |
ssh.TTY_OP_ISPEED: 14400, | |
ssh.TTY_OP_OSPEED: 14400, | |
} | |
err = session.RequestPty("xterm", h, w, modes) | |
if err != nil { | |
fmt.Println(err) | |
} | |
session.Stdout = os.Stdout | |
session.Stderr = os.Stderr | |
session.Stdin = os.Stdin | |
err = session.Shell() | |
if err != nil { | |
fmt.Println(err) | |
} | |
// ターミナルサイズの変更検知・処理 | |
signal_chan := make(chan os.Signal, 1) | |
signal.Notify(signal_chan, syscall.SIGWINCH) | |
go func() { | |
for { | |
s := <-signal_chan | |
switch s { | |
case syscall.SIGWINCH: | |
fd := int(os.Stdout.Fd()) | |
w, h, _ = terminal.GetSize(fd) | |
session.WindowChange(h, w) | |
} | |
} | |
}() | |
err = session.Wait() | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment