Best Venom code snippet using ssh.Run
ssh_no_privkey_passphase.go
Source:ssh_no_privkey_passphase.go
...160 }161 defer func() {162 // see: https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close163 //164 // sess.Run() ã¯ãã³ãã³ããå®è¡å¾ã«ã»ãã·ã§ã³ãcloseãã¦ãã.165 // ãã®ãããsess.Run() å¾ã« sess.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããã.166 // æ¢ã«ã»ãã·ã§ã³ã¯ sess.Run() ã§é©åã«ã¯ãã¼ãºããã¦ããããããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ã167 e := sess.Close()168 if e != nil && e != io.EOF {169 output.Stderrl("[sess.Close]", e)170 }171 }()172 // ãªã¢ã¼ããµã¼ãã§ã®ã³ãã³ãå®è¡çµæããã¼ã«ã«ã®æ¨æºåºåã¨æ¨æºã¨ã©ã¼ã¸æµã173 sess.Stdout = os.Stdout174 sess.Stderr = os.Stderr175 if err = sess.Run(command); err != nil {176 output.Stderrl("[sess.Run]", err)177 return execErrInSSHSession178 }179 return success180}181// (2) SSH æ¥ç¶ãã¦ã³ãã³ãå®è¡182// - ãã¹ã¯ã¼ãèªè¨¼183// - ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼ãã184func sshWithPasswordWithFixedHostKey() returnCode {185 // -------------------------------------------186 // ãªã¢ã¼ããµã¼ã ã® å
¬ééµ ãå¾ã187 //188 _, _, pubKey, _, _, err := ssh.ParseKnownHosts([]byte(hostKey))189 if err != nil {190 output.Stderrl("[ssh.ParseKnownHosts]", err)191 return parseErrPublicKey192 }193 // -------------------------------------------194 // SSH ã® æ¥ç¶è¨å® ãæ§ç¯195 //196 config := &ssh.ClientConfig{197 // SSH ã¦ã¼ã¶å198 User: sshUser,199 // èªè¨¼æ¹å¼200 Auth: []ssh.AuthMethod{201 // ãã¹ã¯ã¼ãèªè¨¼202 ssh.Password(sshPass),203 },204 // ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼205 HostKeyCallback: ssh.FixedHostKey(pubKey),206 }207 // -------------------------------------------208 // SSH 㧠æ¥ç¶209 //210 conn, err := ssh.Dial("tcp", sshHost, config)211 if err != nil {212 output.Stderrl("[ssh.Dial]", err)213 return connErrSSHClient214 }215 // -------------------------------------------216 // ã»ãã·ã§ã³ãéãã¦ãã³ãã³ããå®è¡217 //218 sess, err := conn.NewSession()219 if err != nil {220 output.Stderrl("[conn.NewSession]", err)221 return canNotCreateNewSSHSession222 }223 defer func() {224 // see: https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close225 //226 // sess.Run() ã¯ãã³ãã³ããå®è¡å¾ã«ã»ãã·ã§ã³ãcloseãã¦ãã.227 // ãã®ãããsess.Run() å¾ã« sess.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããã.228 // æ¢ã«ã»ãã·ã§ã³ã¯ sess.Run() ã§é©åã«ã¯ãã¼ãºããã¦ããããããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ã229 e := sess.Close()230 if e != nil && e != io.EOF {231 output.Stderrl("[sess.Close]", e)232 }233 }()234 // ãªã¢ã¼ããµã¼ãã§ã®ã³ãã³ãå®è¡çµæããã¼ã«ã«ã®æ¨æºåºåã¨æ¨æºã¨ã©ã¼ã¸æµã235 sess.Stdout = os.Stdout236 sess.Stderr = os.Stderr237 if err = sess.Run(command); err != nil {238 output.Stderrl("[sess.Run]", err)239 return execErrInSSHSession240 }241 return success242}243// (3) SSH æ¥ç¶ãã¦ã³ãã³ãå®è¡244// - éµèªè¨¼245// - ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼ããªã246func sshWithKeyFileWithInsecureHostKey() returnCode {247 // -------------------------------------------248 // $HOME/.ssh/id_rsa ãããã¼ã¿èªã¿åã249 //250 homeDir, err := os.UserHomeDir()251 if err != nil {252 output.Stderrl("[os.UserHomeDir]", err)253 return homedirNotFound254 }255 sshPrivKeyFile := filepath.Join(homeDir, ".ssh/id_rsa")256 privKey, err := os.ReadFile(sshPrivKeyFile)257 if err != nil {258 output.Stderrl("[os.ReadFile]", err)259 return readErrSSHPrivateKey260 }261 // -------------------------------------------262 // ç§å¯éµã渡ã㦠Signer ãåå¾263 //264 signer, err := ssh.ParsePrivateKey(privKey)265 if err != nil {266 output.Stderrl("[ssh.ParsePrivateKey]", err)267 return parseErrSSHPrivateKey268 }269 // -------------------------------------------270 // SSH ã® æ¥ç¶è¨å® ãæ§ç¯271 //272 config := &ssh.ClientConfig{273 // SSH ã¦ã¼ã¶å274 User: sshUser,275 // èªè¨¼æ¹å¼276 Auth: []ssh.AuthMethod{277 // éµèªè¨¼278 ssh.PublicKeys(signer),279 },280 // ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼ããªã281 HostKeyCallback: ssh.InsecureIgnoreHostKey(),282 }283 // -------------------------------------------284 // SSH 㧠æ¥ç¶285 //286 conn, err := ssh.Dial("tcp", sshHost, config)287 if err != nil {288 output.Stderrl("[ssh.Dial]", err)289 return connErrSSHClient290 }291 // -------------------------------------------292 // ã»ãã·ã§ã³ãéãã¦ãã³ãã³ããå®è¡293 //294 sess, err := conn.NewSession()295 if err != nil {296 output.Stderrl("[conn.NewSession]", err)297 return canNotCreateNewSSHSession298 }299 defer func() {300 // see: https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close301 //302 // sess.Run() ã¯ãã³ãã³ããå®è¡å¾ã«ã»ãã·ã§ã³ãcloseãã¦ãã.303 // ãã®ãããsess.Run() å¾ã« sess.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããã.304 // æ¢ã«ã»ãã·ã§ã³ã¯ sess.Run() ã§é©åã«ã¯ãã¼ãºããã¦ããããããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ã305 e := sess.Close()306 if e != nil && e != io.EOF {307 output.Stderrl("[sess.Close]", e)308 }309 }()310 // ãªã¢ã¼ããµã¼ãã§ã®ã³ãã³ãå®è¡çµæããã¼ã«ã«ã®æ¨æºåºåã¨æ¨æºã¨ã©ã¼ã¸æµã311 sess.Stdout = os.Stdout312 sess.Stderr = os.Stderr313 if err = sess.Run(command); err != nil {314 output.Stderrl("[sess.Run]", err)315 return execErrInSSHSession316 }317 return success318}319// (4) SSH æ¥ç¶ãã¦ã³ãã³ãå®è¡320// - éµèªè¨¼321// - ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼ãã322func sshWithKeyFileWithFixedHostKey() returnCode {323 // -------------------------------------------324 // $HOME/.ssh/id_rsa ãããã¼ã¿èªã¿åã325 //326 homeDir, err := os.UserHomeDir()327 if err != nil {328 output.Stderrl("[os.UserHomeDir]", err)329 return homedirNotFound330 }331 sshPrivKeyFile := filepath.Join(homeDir, ".ssh/id_rsa")332 privKey, err := os.ReadFile(sshPrivKeyFile)333 if err != nil {334 output.Stderrl("[os.ReadFile]", err)335 return readErrSSHPrivateKey336 }337 // -------------------------------------------338 // ç§å¯éµã渡ã㦠Signer ãåå¾339 //340 signer, err := ssh.ParsePrivateKey(privKey)341 if err != nil {342 output.Stderrl("[ssh.ParsePrivateKey]", err)343 return parseErrSSHPrivateKey344 }345 // -------------------------------------------346 // ãªã¢ã¼ããµã¼ã ã® å
¬ééµ ãå¾ã347 //348 _, _, pubKey, _, _, err := ssh.ParseKnownHosts([]byte(hostKey))349 if err != nil {350 output.Stderrl("[ssh.ParseKnownHosts]", err)351 return parseErrPublicKey352 }353 // -------------------------------------------354 // SSH ã® æ¥ç¶è¨å® ãæ§ç¯355 //356 config := &ssh.ClientConfig{357 // SSH ã¦ã¼ã¶å358 User: sshUser,359 // èªè¨¼æ¹å¼360 Auth: []ssh.AuthMethod{361 // éµèªè¨¼362 ssh.PublicKeys(signer),363 },364 // ãªã¢ã¼ããµã¼ãã®å
¬ééµãæ¤è¨¼365 HostKeyCallback: ssh.FixedHostKey(pubKey),366 }367 // -------------------------------------------368 // SSH 㧠æ¥ç¶369 //370 conn, err := ssh.Dial("tcp", sshHost, config)371 if err != nil {372 output.Stderrl("[ssh.Dial]", err)373 return connErrSSHClient374 }375 // -------------------------------------------376 // ã»ãã·ã§ã³ãéãã¦ãã³ãã³ããå®è¡377 //378 sess, err := conn.NewSession()379 if err != nil {380 output.Stderrl("[conn.NewSession]", err)381 return canNotCreateNewSSHSession382 }383 defer func() {384 // see: https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close385 //386 // sess.Run() ã¯ãã³ãã³ããå®è¡å¾ã«ã»ãã·ã§ã³ãcloseãã¦ãã.387 // ãã®ãããsess.Run() å¾ã« sess.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããã.388 // æ¢ã«ã»ãã·ã§ã³ã¯ sess.Run() ã§é©åã«ã¯ãã¼ãºããã¦ããããããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ã389 e := sess.Close()390 if e != nil && e != io.EOF {391 output.Stderrl("[sess.Close]", e)392 }393 }()394 // ãªã¢ã¼ããµã¼ãã§ã®ã³ãã³ãå®è¡çµæããã¼ã«ã«ã®æ¨æºåºåã¨æ¨æºã¨ã©ã¼ã¸æµã395 sess.Stdout = os.Stdout396 sess.Stderr = os.Stderr397 if err = sess.Run(command); err != nil {398 output.Stderrl("[sess.Run]", err)399 return execErrInSSHSession400 }401 return success402}...
root.go
Source:root.go
...25var rootCmd = &cobra.Command{26 Use: "mq",27 Short: "mq or MultiQuery is a cli tool to perform mysql queries on multiple databases",28 Long: "mq or MultiQuery is a cli tool to perform mysql queries on multiple databases\n\nCreated by Markus Tenghamn (m@rkus.io)",29 Run: run,30}31type ViaSSHDialer struct {32 client *ssh.Client33 _ *context.Context34}35func (d *ViaSSHDialer) Dial(ctx context.Context, addr string) (net.Conn, error) {36 return d.client.Dial("tcp", addr)37}38func run(cmd *cobra.Command, args []string) {39 if sshHost != "" {40 runOverSSH(runMysql, "mysql+tcp")41 } else {42 cfg, err := ini.Load(dbConf)43 if err == nil {44 loadMyCnf(cfg)45 }46 runMysql("tcp")47 }48 log.Println("done")49}50func runMysql(dbNet string) {51 log.Println("Running mysql")52 var databasesToQuery []string53 if db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@%s(%s:%s)/%s?parseTime=true", dbUser, dbPass, dbNet, dbHost, dbPort, dbName)); err == nil {54 defer db.Close()55 if rows, err := db.Query("SHOW DATABASES"); err == nil {56 for rows.Next() {57 var databaseName string58 _ = rows.Scan(&databaseName)59 if dbIgnore != "" && strings.Contains(databaseName, dbIgnore) {60 // Skip if dbIgnore matches61 continue62 }63 if dbPrefix != "" {64 if strings.HasPrefix(databaseName, dbPrefix) {65 databasesToQuery = append(databasesToQuery, databaseName)66 }67 } else {68 databasesToQuery = append(databasesToQuery, databaseName)69 }70 }71 } else {72 log.Fatal(err)73 }74 }75 if len(databasesToQuery) < 1 {76 log.Fatal("No databases found")77 }78 log.Println("Running queries")79 // Run the query80 if dbQuery != "" {81 queries := make(chan string)82 var executedDbs []string83 for _, databaseName := range databasesToQuery {84 if threaded {85 go executeThreadedQuery(dbNet, databaseName, queries)86 } else {87 executeQuery(dbNet, databaseName)88 }89 }90 for {91 msg := <-queries92 executedDbs = append(executedDbs, msg)93 if len(executedDbs) == len(databasesToQuery) {94 break95 }96 }97 }98}99func executeThreadedQuery(dbNet string, databaseName string, queries chan string) {100 executeQuery(dbNet, databaseName)101 queries <- databaseName102}103func executeQuery(dbNet string, databaseName string) {104 log.Printf("Running query on %s\n", databaseName)105 if db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@%s(%s:%s)/%s?parseTime=true", dbUser, dbPass, dbNet, dbHost, dbPort, databaseName)); err == nil {106 defer db.Close()107 if rows, err := db.Query(dbQuery); err == nil {108 cols, err := rows.Columns()109 if err != nil {110 fmt.Println("Failed to get columns", err)111 return112 }113 // Result is your slice string.114 rawResult := make([][]byte, len(cols))115 result := make([]string, len(cols))116 dest := make([]interface{}, len(cols)) // A temporary interface{} slice117 for i, _ := range rawResult {118 dest[i] = &rawResult[i] // Put pointers to each string in the interface slice119 }120 for rows.Next() {121 err = rows.Scan(dest...)122 if err != nil {123 fmt.Println("Failed to scan row", err)124 return125 }126 for i, raw := range rawResult {127 if raw == nil {128 result[i] = "\\N"129 } else {130 result[i] = string(raw)131 }132 }133 fmt.Printf("%s: %#v\n", databaseName, result)134 }135 } else {136 log.Fatal(err)137 }138 }139}140func runOverSSH(mysqlFunc func(dbNet string), dbNet string) {141 // Attempt to read sshEnabled config file142 sshHostName := ssh_config.Get(sshHost, "HostName")143 sshPort := ssh_config.Get(sshHost, "Port")144 sshIdentityFile := ssh_config.Get(sshHost, "IdentityFile")145 sshUser := ssh_config.Get(sshHost, "User")146 if sshHostName != "" {147 sshHost = sshHostName148 }149 if sshPort == "" {150 sshPort = sshPort151 }152 if sshIdentityFile != "~/.sshEnabled/identity" && privkeyPath == defaultKeyPath {153 privkeyPath = sshIdentityFile154 }155 if sshUser != "root" && sshUser != "" {156 sshUser = sshUser157 }158 if strings.Contains(privkeyPath, "~/") {159 usr, err := user.Current()160 if err != nil {161 log.Fatal(err)162 }163 privkeyPath = path.Join(usr.HomeDir, strings.Replace(privkeyPath, "~", "", 1))164 }165 sshHost = fmt.Sprintf("%s:%s", sshHost, sshPort)166 key, err := ioutil.ReadFile(privkeyPath)167 if err != nil {168 log.Fatalf("Unable to read private key: %v", err)169 }170 signer, err := ssh.ParsePrivateKey(key)171 if err != nil {172 CheckPassword()173 der := decrypt(key, password)174 key, err := x509.ParsePKCS1PrivateKey(der)175 if err != nil {176 log.Fatalf("Unable to parse private key: %v", err)177 }178 signer, err = ssh.NewSignerFromKey(key)179 if err != nil {180 log.Fatalf("Unable to get signer from private key: %v", err)181 }182 }183 var agentClient agent.Agent184 // Establish a connection to the local ssh-agent185 if conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {186 defer conn.Close()187 // Create a new instance of the ssh agent188 agentClient = agent.NewClient(conn)189 }190 // The client configuration with configuration option to use the ssh-agent191 sshConfig := &ssh.ClientConfig{192 User: sshUser,193 Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},194 HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {195 return nil196 },197 }198 // When the agentClient connection succeeded, add them as AuthMethod199 if agentClient != nil {200 sshConfig.Auth = append(sshConfig.Auth, ssh.PublicKeysCallback(agentClient.Signers))201 }202 // When there's a non empty password add the password AuthMethod203 if sshPass != "" {204 sshConfig.Auth = append(sshConfig.Auth, ssh.PasswordCallback(func() (string, error) {205 return sshPass, nil206 }))207 }208 log.Println("Connecting to ssh")209 // Connect to the SSH Server210 if sshcon, err := ssh.Dial("tcp", sshHost, sshConfig); err == nil {211 defer sshcon.Close()212 session, _ := sshcon.NewSession()213 defer session.Close()214 var stdoutBuf bytes.Buffer215 session.Stdout = &stdoutBuf216 session.Run(fmt.Sprintf("cat %s", dbConf))217 mycnfBytes := stdoutBuf.Bytes()218 if len(mycnfBytes) > 0 {219 cfg, err := ini.Load(mycnfBytes)220 if err != nil {221 panic(err)222 }223 loadMyCnf(cfg)224 }225 dialer := ViaSSHDialer{client: sshcon}226 // Now we register the ViaSSHDialer with the ssh connection as a parameter227 mysql.RegisterDialContext("mysql+tcp", dialer.Dial)228 // once we are connected to mysql over ssh we can run the mysql stuff as we normally would229 mysqlFunc(dbNet)230 } else {...
ssh_run_without_close.go
Source:ssh_run_without_close.go
...5 "os"6 "github.com/devlights/gomy/output"7 "golang.org/x/crypto/ssh"8)9// SSHSessionCloseAfterRun -- ssh.Run() ãå¼ãã å¾ã« ssh.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããããã¨ã確èªãããµã³ãã«ã§ã.10//11// REFERENCES:12// - https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close13func SSHSessionCloseAfterRun() error {14 // -----------------------------------------------------------------------------------------15 // ssh.Run() ããå¾ã« ssh.Close() ãã㨠io.EOF ãè¿å´ããã件16 //17 // çç±ã¨ãã¦ã¯ãssh.Run() ãå®è¡ããã¨å
é¨ã§ã»ãã·ã§ã³ã Close ãã¦ããããã18 // é©åã« ã»ãã·ã§ã³ ã¯éãããã¦ããã®ã§ããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ãã19 // -----------------------------------------------------------------------------------------20 var (21 sshUser = os.ExpandEnv("${SSH_USER}")22 sshPass = os.ExpandEnv("${SSH_PASS}")23 sshHost = os.ExpandEnv("${SSH_HOST}")24 )25 if sshUser == "" {26 return fmt.Errorf("[error] %s ãè¨å®ããã¦ãã¾ãã", "${SSH_USER}")27 }28 if sshPass == "" {29 return fmt.Errorf("[error] %s ãè¨å®ããã¦ãã¾ãã", "${SSH_PASS}")30 }31 if sshHost == "" {32 return fmt.Errorf("[error] %s ãè¨å®ããã¦ãã¾ãã", "${SSH_HOST}")33 }34 config := &ssh.ClientConfig{35 User: sshUser,36 Auth: []ssh.AuthMethod{37 ssh.Password(sshPass),38 },39 HostKeyCallback: ssh.InsecureIgnoreHostKey(),40 }41 conn, err := ssh.Dial("tcp", sshHost, config)42 if err != nil {43 output.Stderrl("[ssh.Dial]", err)44 return err45 }46 sess, err := conn.NewSession()47 if err != nil {48 output.Stderrl("[conn.NewSession]", err)49 return err50 }51 defer func() {52 // see: https://stackoverflow.com/questions/60879023/getting-eof-as-error-in-golang-ssh-session-close53 //54 // sess.Run() ã¯ãã³ãã³ããå®è¡å¾ã«ã»ãã·ã§ã³ãcloseãã¦ãã.55 // ãã®ãããsess.Run() å¾ã« sess.Close() ãå¼ã¶ã¨ io.EOF ãè¿å´ããã.56 // æ¢ã«ã»ãã·ã§ã³ã¯ sess.Run() ã§é©åã«ã¯ãã¼ãºããã¦ããããããã®ã¨ã©ã¼ã¯ç¡è¦ãã¦ãè¯ã57 e := sess.Close()58 if e != nil && e != io.EOF {59 output.Stderrl("[sess.Close]", e)60 }61 }()62 // ãªã¢ã¼ããµã¼ãã§ã®ã³ãã³ãå®è¡çµæããã¼ã«ã«ã®æ¨æºåºåã¨æ¨æºã¨ã©ã¼ã¸æµã63 sess.Stdout = os.Stdout64 sess.Stderr = os.Stderr65 if err = sess.Run(command); err != nil {66 output.Stderrl("[sess.Run]", err)67 return err68 }69 return nil70}...
Run
Using AI Code Generation
1import (2func main() {3 key, err := ioutil.ReadFile("/home/sshkey")4 if err != nil {5 panic("Failed to read private key")6 }7 signer, err := ssh.ParsePrivateKey(key)8 if err != nil {9 panic("Failed to parse private key")10 }11 client, err := ssh.Dial("tcp", "
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!