-
-
Save GrimTheReaper/6ed8db83f4a6dfd5a06861a42aab5032 to your computer and use it in GitHub Desktop.
golang mysql throught a tunnel
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 | |
// based on gist | |
// https://gist.github.com/ir4y/11146415 | |
// http://stackoverflow.com/questions/21417223/simple-ssh-port-forward-in-golang | |
// obro conexio ssh amb el server remot. | |
// tot el que envio al port local ho copio al port remote | |
// a traves de la conexio remota. Per tant he d'obrir un | |
// port a la maquina remota? | |
import ( | |
"code.google.com/p/go.crypto/ssh" | |
"database/sql" | |
"fmt" | |
_ "github.com/hgfischer/mysql" | |
"io" | |
"log" | |
"net" | |
) | |
func main() { | |
config := &ssh.ClientConfig{ | |
User: "user", | |
Auth: []ssh.AuthMethod{ | |
ssh.Password("password"), | |
}, | |
} | |
// remote connection | |
conn, err := ssh.Dial("tcp", "ipadress:22", config) | |
if err != nil { | |
log.Fatalf("Unable to connect %s", err) | |
} | |
defer conn.Close() | |
// local connection | |
remote, err := conn.Dial("tcp", "localhost:3306") | |
if err != nil { | |
log.Fatalf("Unable to connect %s", err) | |
} | |
defer remote.Close() | |
local, err := net.Listen("tcp", "localhost:3306") | |
if err != nil { | |
log.Fatalf("Unable to connect %s", err) | |
} | |
defer local.Close() | |
go func() { | |
for { | |
l, err := local.Accept() | |
if err != nil { | |
log.Fatalf("listen Accept failed %s", err) | |
} | |
go func() { | |
_, err := io.Copy(l, remote) | |
if err != nil { | |
log.Fatalf("io.Copy failed: %v", err) | |
} | |
}() | |
go func() { | |
_, err := io.Copy(remote, l) | |
if err != nil { | |
log.Fatalf("io.Copy failed: %v", err) | |
} | |
}() | |
} | |
}() | |
dsn := "user:pass@tcp(127.0.0.1:3306)/bdd?charset=utf8" | |
db, err := sql.Open("mysql", dsn) | |
if err != nil { | |
log.Fatalf("Error connecting to database %s", err) | |
} | |
var count uint64 | |
row := db.QueryRow("SELECT COUNT(*) FROM auth_user") | |
err = row.Scan(&count) | |
if err != nil { | |
log.Fatalf("Error on query database %s", err) | |
} | |
fmt.Printf("total registros %d", count) | |
//fmt.Printfln("Total %d", count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment