Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "bytes"
- "fmt"
- "log"
- "net"
- "os"
- "os/signal"
- "golang.org/x/crypto/ssh"
- )
- func main() {
- server := "host:port"
- user := "user"
- password := "password"
- // Setup ssh config auth with username/password
- config := &ssh.ClientConfig{
- User: user,
- Auth: []ssh.AuthMethod{
- ssh.Password(password),
- },
- HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
- return nil
- },
- }
- // Connect to ssh server
- conn, err := ssh.Dial("tcp", server, config)
- if err != nil {
- panic("Failed to dail: " + err.Error())
- }
- fmt.Println("Connected")
- // Create new ssh session
- session, err := conn.NewSession()
- if err != nil {
- panic("Failed to create session: " + err.Error())
- }
- fmt.Println("Create new session")
- // For sending command ex: in.Write(cmd)
- in, _ := session.StdinPipe()
- var b bytes.Buffer
- session.Stdout = &b
- session.Stdout = os.Stdout
- // Start shell
- if err := session.Shell(); err != nil {
- log.Fatalf("failed to start shell: %s", err)
- }
- // Ctrl-C for stop and disconnect ssh
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt)
- go func() {
- for {
- <-c
- fmt.Fprint(in, "\n")
- fmt.Println("\nDisconnecting...")
- session.Close()
- conn.Close()
- os.Exit(3)
- }
- }()
- // Customize this for receive or send command
- for {
- reader := bufio.NewReader(os.Stdin)
- str, _ := reader.ReadString('\n')
- fmt.Fprint(in, str)
- // fmt.Println(b.String())
- }
- }
Add Comment
Please, Sign In to add comment