Created
October 22, 2023 18:00
-
-
Save Vostbur/86d479e35c1a832484bdd942df2e02c8 to your computer and use it in GitHub Desktop.
SSH Client with password auth
This file contains 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" | |
"log" | |
"os" | |
"strings" | |
"golang.org/x/crypto/ssh" | |
) | |
func main() { | |
if len(os.Args) < 4 { | |
log.Fatalf("Usage: %s <user> <host:port> <command>", os.Args[0]) | |
} | |
client, session, err := connectToHost(os.Args[1], os.Args[2]) | |
if err != nil { | |
panic(err) | |
} | |
command := strings.Join(os.Args[3:], " ") | |
log.Printf("Exec command '%s'", command) | |
out, err := session.CombinedOutput(command) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(out)) | |
client.Close() | |
} | |
func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) { | |
var pass string | |
fmt.Print("Password: ") | |
fmt.Scanf("%s\n", &pass) | |
sshConfig := &ssh.ClientConfig{ | |
User: user, | |
Auth: []ssh.AuthMethod{ssh.Password(pass)}, | |
} | |
sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey() | |
client, err := ssh.Dial("tcp", host, sshConfig) | |
if err != nil { | |
return nil, nil, err | |
} | |
session, err := client.NewSession() | |
if err != nil { | |
client.Close() | |
return nil, nil, err | |
} | |
modes := ssh.TerminalModes{ | |
// ssh.ECHO: 0, // disable echoing | |
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud | |
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud | |
} | |
if err := session.RequestPty("xterm", 80, 40, modes); err != nil { | |
session.Close() | |
return nil, nil, err | |
} | |
return client, session, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment