我就废话不多说了,大家还是直接看代码吧~
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{