How to use connectToHost method of ssh Package

Best Venom code snippet using ssh.connectToHost

main.go

Source:main.go Github

copy

Full Screen

...21func main() {22 if len(os.Args) < 3 {23 fmt.Println(version + " Usage: ssh-keyget <host:port> <type(dsa,rsa,ecdsa,ed25519)> <export(e)>")24 } else if len(os.Args) == 3 {25 connectToHost(os.Args[1], os.Args[2], "")26 } else if len(os.Args) == 4 {27 connectToHost(os.Args[1], os.Args[2], os.Args[3])28 } else {29 fmt.Println("Too many arguments")30 }31}32// truncateString truncate string to given size33func truncateString(s string, size int) string {34 ts := s35 if len(s) > size {36 ts = s[0:size]37 }38 return ts39}40// chunkString convert string to chunks of given size41func chunkString(s string, chunkSize int) []string {42 var chunks []string43 runes := []rune(s)44 if len(runes) == 0 {45 return []string{s}46 }47 for i := 0; i < len(runes); i += chunkSize {48 nn := i + chunkSize49 if nn > len(runes) {50 nn = len(runes)51 }52 chunks = append(chunks, string(runes[i:nn]))53 }54 return chunks55}56// getPublicKeyInfo gets the public key type and length57func getPublicKeyInfo(in []byte) (string, int, error) {58 pk, err := ssh.ParsePublicKey(in)59 if err != nil {60 if strings.Contains(err.Error(), "ssh: unknown key algorithm") {61 return "", 0, err62 }63 return "", 0, fmt.Errorf("ssh.ParsePublicKey: %v", err)64 }65 switch pk.Type() {66 case ssh.KeyAlgoDSA:67 w := struct {68 Name string69 P, Q, G, Y *big.Int70 }{}71 if err := ssh.Unmarshal(pk.Marshal(), &w); err != nil {72 return "", 0, err73 }74 return "dsa", w.P.BitLen(), nil75 case ssh.KeyAlgoRSA:76 w := struct {77 Name string78 E, N *big.Int79 }{}80 if err := ssh.Unmarshal(pk.Marshal(), &w); err != nil {81 return "", 0, err82 }83 return "RSA", w.N.BitLen(), nil84 case ssh.KeyAlgoECDSA256:85 return "ECDSA", 256, nil86 case ssh.KeyAlgoECDSA384:87 return "ECDSA", 384, nil88 case ssh.KeyAlgoECDSA521:89 return "ECDSA", 521, nil90 case ssh.KeyAlgoED25519:91 return "ED25519", 256, nil92 }93 return "", 0, fmt.Errorf("unsupported key type: %s", pk.Type())94}95// trustedHostKeyCallback host key callback from connect96func trustedHostKeyCallback(host string, export string) ssh.HostKeyCallback {97 return func(_ string, _ net.Addr, k ssh.PublicKey) error {98 ks := base64.StdEncoding.EncodeToString(k.Marshal())99 keytype, length, _ := getPublicKeyInfo(k.Marshal())100 fpmd5 := ssh.FingerprintLegacyMD5(k)101 fpsha256 := ssh.FingerprintSHA256(k)102 comment := keytype + " " + strconv.Itoa(length) + ", " + host103 if export == "e" {104 fmt.Println(ssh2Header)105 ssh2Comment := "Comment: " + comment106 fmt.Println(truncateString(ssh2Comment, ssh2Width - 1) + "\\")107 fmt.Println("MD5:" + fpmd5 + "\\")108 fmt.Println(fpsha256)109 fmt.Println(strings.Join(chunkString(ks, ssh2Width), "\n"))110 fmt.Println(ssh2Footer)111 } else {112 fmt.Println(k.Type() + " " + ks + " " + comment + ", MD5:" + fpmd5 + ", " + fpsha256)113 }114 return nil115 }116}117// connectToHost connect to host to get public key118func connectToHost(host string, keytype string, export string){119 if !strings.Contains(host, ":") {120 host = host + ":" + strconv.Itoa(sshDefaultPort)121 }122 sshConfig := &ssh.ClientConfig{123 User: "",124 Auth: []ssh.AuthMethod{ssh.Password("")},125 HostKeyCallback: trustedHostKeyCallback(host, export),126 }127 switch keytype {128 case "dsa":129 sshConfig.HostKeyAlgorithms = []string{ssh.KeyAlgoDSA}130 case "rsa":131 sshConfig.HostKeyAlgorithms = []string{ssh.KeyAlgoRSA}132 case "ecdsa":...

Full Screen

Full Screen

esxi_remote_cmds.go

Source:esxi_remote_cmds.go Github

copy

Full Screen

...9 "github.com/tmc/scp"10 "golang.org/x/crypto/ssh"11)12// Connect to esxi host using ssh13func connectToHost(esxiConnInfo ConnectionStruct, attempt int) (*ssh.Client, *ssh.Session, error) {14 sshConfig := &ssh.ClientConfig{15 User: esxiConnInfo.user,16 Auth: []ssh.AuthMethod{17 ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {18 // Reply password to all questions19 answers := make([]string, len(questions))20 for i, _ := range answers {21 answers[i] = esxiConnInfo.pass22 }23 return answers, nil24 }),25 },26 }27 sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()28 esxi_hostandport := fmt.Sprintf("%s:%s", esxiConnInfo.host, esxiConnInfo.port)29 //attempt := 1030 for attempt > 0 {31 client, err := ssh.Dial("tcp", esxi_hostandport, sshConfig)32 if err != nil {33 log.Printf("[runRemoteSshCommand] Retry connection: %d\n", attempt)34 attempt -= 135 time.Sleep(1 * time.Second)36 } else {37 session, err := client.NewSession()38 if err != nil {39 client.Close()40 return nil, nil, fmt.Errorf("Session Connection Error")41 }42 return client, session, nil43 }44 }45 return nil, nil, fmt.Errorf("Client Connection Error")46}47// Run any remote ssh command on esxi server and return results.48func runRemoteSshCommand(esxiConnInfo ConnectionStruct, remoteSshCommand string, shortCmdDesc string) (string, error) {49 log.Println("[runRemoteSshCommand] :" + shortCmdDesc)50 var attempt int51 if remoteSshCommand == "vmware --version" {52 attempt = 353 } else {54 attempt = 1055 }56 client, session, err := connectToHost(esxiConnInfo, attempt)57 if err != nil {58 log.Println("[runRemoteSshCommand] Failed err: " + err.Error())59 return "Failed to ssh to esxi host", err60 }61 stdout_raw, err := session.CombinedOutput(remoteSshCommand)62 stdout := strings.TrimSpace(string(stdout_raw))63 if stdout == "<unset>" {64 return "Failed to ssh to esxi host or Management Agent has been restarted", err65 }66 log.Printf("[runRemoteSshCommand] cmd:/%s/\n stdout:/%s/\nstderr:/%s/\n", remoteSshCommand, stdout, err)67 client.Close()68 return stdout, err69}70// Function to scp file to esxi host.71func writeContentToRemoteFile(esxiConnInfo ConnectionStruct, content string, path string, shortCmdDesc string) (string, error) {72 log.Println("[writeContentToRemoteFile] :" + shortCmdDesc)73 f, _ := ioutil.TempFile("", "")74 fmt.Fprintln(f, content)75 f.Close()76 defer os.Remove(f.Name())77 client, session, err := connectToHost(esxiConnInfo, 10)78 if err != nil {79 log.Println("[writeContentToRemoteFile] Failed err: " + err.Error())80 return "Failed to ssh to esxi host", err81 }82 err = scp.CopyPath(f.Name(), path, session)83 if err != nil {84 log.Println("[writeContentToRemoteFile] Failed err: " + err.Error())85 return "Failed to scp file to esxi host", err86 }87 client.Close()88 return content, err89}...

Full Screen

Full Screen

myssh.go

Source:myssh.go Github

copy

Full Screen

...11 Port string12 Password string13}14func (ssh_conf *MakeConfig) Run(command string) (string, error) {15 client, session, err := connectToHost(ssh_conf.User, ssh_conf.Password, ssh_conf.Server+":"+ssh_conf.Port)16 if err != nil {17 panic(err)18 }19 out, err := session.CombinedOutput(command)20 if err != nil {21 panic(err)22 }23 fmt.Println(string(out))24 client.Close()25 return string(out), err26}27func connectToHost(user, pass, host string) (*ssh.Client, *ssh.Session, error) {28 sshConfig := &ssh.ClientConfig{29 User: user,30 Auth: []ssh.AuthMethod{ssh.Password(pass)},31 }32 client, err := ssh.Dial("tcp", host, sshConfig)33 if err != nil {34 return nil, nil, err35 }36 session, err := client.NewSession()37 if err != nil {38 client.Close()39 return nil, nil, err40 }41 return client, session, nil...

Full Screen

Full Screen

connectToHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 privateKey, err := ioutil.ReadFile("id_rsa")4 if err != nil {5 panic("Failed to read private key")6 }7 signer, err := ssh.ParsePrivateKey(privateKey)8 if err != nil {9 panic("Failed to parse private key")10 }11 client, err := ssh.Dial("tcp", "

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Venom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful