golang mysql 远程_golang 通过ssh代理连接mysql的操作

我就废话不多说了,大家还是直接看代码吧~

package main

import (

"bytes"

"context"

"database/sql"

"errors"

"fmt"

"github.com/go-sql-driver/mysql"

"golang.org/x/crypto/ssh"

"io"

"io/ioutil"

"net"

"os"

)

type ViaSSHDialer struct {

client *ssh.Client

_ *context.Context

}

func (self *ViaSSHDialer) Dial(context context.Context,addr string) (net.Conn, error) {

return self.client.Dial("tcp", addr)

}

type remoteScriptType byte

type remoteShellType byte

const (

cmdLine remoteScriptType = iota

rawScript

scriptFile

interactiveShell remoteShellType = iota

nonInteractiveShell

)

type Client struct {

client *ssh.Client

}

func main() {

client, err := DialWithPasswd("ip:port", "user", "password")

if err != nil {

panic(err)

}

out, err := client.Cmd("ls -l").Output()

if err != nil {

panic(err)

}

fmt.Println(string(out))

// Now we register the ViaSSHDialer with the ssh connection as a parameter

mysql.RegisterDialContext("mysql+tcp", (&ViaSSHDialer{client.client,nil}).Dial)

//mysql.RegisterDial("mysql+tcp", (&ViaSSHDialer{client.client}).Dial)

if db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s","Aiqitest", "uf6amk146d2aoemi7", "139.196.174.234:3306", "Aiqitest"));

err == nil {

fmt.Printf("Successfully connected to the db\n")

if rows, err := db.Query("SELECT id, name FROM table ORDER BY id"); err == nil {

for rows.Next() {

var id int64

var name string

rows.Scan(&id, &name)

fmt.Printf("ID: %d Name: %s\n", id, name)

}

rows.Close()

} else {

fmt.Printf("Failure: %s", err.Error())

}

db.Close()

}

}

// DialWithPasswd starts a client connection to the given SSH server with passwd authmethod.

func DialWithPasswd(addr, user, passwd string) (*Client, error) {

config := &ssh.ClientConfig{

User: user,

Auth: []ssh.AuthMethod{

ssh.Password(passwd),

},

HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),

}

return Dial("tcp", addr, config)

}

// DialWithKey starts a client connection to the given SSH server with key authmethod.

func DialWithKey(addr, user, keyfile string) (*Client, error) {

key, err := ioutil.ReadFile(keyfile)

if err != nil {

return nil, err

}

signer, err := ssh.ParsePrivateKey(key)

if err != nil {

return nil, err

}

config := &ssh.ClientConfig{

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值