作者:afaj
项目:ctr
func getConn(host *host.Host) (*ssh.ClientConn, error) {
hostkey := host.Id
if con, ok := conns[hostkey]; ok {
return con, nil
}
if host.User == "" {
return nil, fmt.Errorf("user not set")
}
for _, keyfile := range host.Keyfiles {
// TODO add key to global keyring, ok?
if err := keys.loadPEM(keyfile); err != nil {
return nil, fmt.Errorf("unable to load %s: %v", keyfile, err)
}
}
config := &ssh.ClientConfig{
User: host.User,
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(keys),
},
}
conn, err := ssh.Dial("tcp", host.ConnStr(), config)
if err != nil {
return nil, fmt.Errorf("unable to connect to %s: %v", host, err)
}
conns[hostkey] = conn
return conn, nil
}
作者:pavel-paula
项目:mobile_per
func (h *RemoteHelper) runCmd(host, cmd string) string {
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", host), h.config)
if err != nil {
log.Fatalf("Failed to dial: " + err.Error())
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
log.Fatal("unable to create session: %s", err)
}
defer session.Close()
err = session.RequestPty("xterm", 80, 40, ssh.TerminalModes{})
if err != nil {
log.Fatal("request for pseudo terminal failed: %s", err)
}
var b bytes.Buffer
session.Stdout = &b
err = session.Run(cmd)
if err != nil {
log.Fatal("Failed to run: " + err.Error())
}
return strings.Replace(strings.Replace(b.String(), "\n", "", -1), "\r", "", -1)
}
作者:postfi
项目:sshPortForwar
func forward(localConn net.Conn, config *ssh.ClientConfig, serverAddrString, remoteAddrString string) {
// Setup sshClientConn (type *ssh.ClientConn)
sshClientConn, err := ssh.Dial("tcp", serverAddrString, config)
if err != nil {
log.Fatalf("ssh.Dial failed: %s", err)
}
//defer sshClientConn.Close()
// Setup sshConn (type net.Conn)
sshConn, err := sshClientConn.Dial("tcp", remoteAddrString)
if err != nil {
log.Fatalf("sshClientConn.Dial failed: %s", err)
}
//defer sshConn.Close()
// Copy localConn.Reader to sshConn.Writer
go func() {
_, err = io.Copy(sshConn, localConn)
if err != nil {
log.Printf("io.Copy from local to remote failed: %v", err)
}
}()
// Copy sshConn.Reader to localConn.Writer
go func() {
_, err = io.Copy(localConn, sshConn)
if err != nil {
log.Printf("io.Copy from remote to local failed: %v", err)
}
}()
}
作者:Civi
项目:goss
func TestSshCmd(t *testing.T) {
kc := new(keychain)
kc.load()
config := &ssh.ClientConfig{
User: os.Getenv("USER"),
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(kc),
},
}
client, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
panic("Failed to run: " + err.Error())
}
log.Printf("Result of running whoami via ssh: %s\n", b)
//fmt.Println(b.String())
}
作者:smallen
项目:etcd-load-generato
// Dials to setup tcp connection to remote host, used for memory information
func dialClient() {
t_key, _ := getKeyFile()
if err != nil {
panic(err)
}
key = t_key
config := &ssh.ClientConfig{
User: remote_host_user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
t_client, err := ssh.Dial("tcp", remote_host+":"+ssh_port, config)
if err != nil {
fmt.Println("\n", "Failed to dial: "+err.Error())
fmt.Println("Unable to establish connection to remote machine.")
fmt.Println("Make sure that password-less connection is possible.")
fmt.Println("************************************")
mem_flag = false
return
}
ssh_client = t_client
}
作者:johnza
项目:goshi
// remoteCmdOutput runs the given command on a remote server at the given hostname as the given user.
func remoteCmdOutput(username, hostname, cmd string, privateKey []byte) (b []byte, err error) {
p, err := ssh.ParseRawPrivateKey(privateKey)
if err != nil {
return b, err
}
s, err := ssh.NewSignerFromKey(p)
if err != nil {
return b, err
}
pub := ssh.PublicKeys(s)
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{pub},
}
client, err := ssh.Dial("tcp", hostname, clientConfig)
if err != nil {
return b, errors.New("ERROR: Failed to dial: " + err.Error())
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return b, errors.New("ERROR: Failed to create session: " + err.Error())
}
defer session.Close()
b, err = session.Output(cmd)
if err != nil {
return b, fmt.Errorf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
}
return b, nil
}
作者:nizsheane
项目:ri
func ExecuteCmd(cmd, hostname string, config *ssh.ClientConfig, stdout chan string, stderr chan error) {
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
stderr <- err
return
}
session, err := conn.NewSession()
defer session.Close()
if err != nil {
stderr <- err
return
}
pipe, _ := session.StdoutPipe()
session.Start(cmd)
buffer := bufio.NewReader(pipe)
for {
line, err := buffer.ReadString('\n')
if len(line) > 0 {
stdout <- line
}
if err != nil {
if err == io.EOF {
close(stdout)
return
} else {
stderr <- err
return
}
}
}
}
作者:jakecoffma
项目:ssh
func main() {
if len(os.Args) < 2 {
usage()
return
}
username, hostnames, pass := parse()
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(string(pass)),
},
}
hosts := []*Host{}
for _, host := range hostnames {
client, err := ssh.Dial("tcp", host+":22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
hosts = append(hosts, &Host{host, client})
}
lock := make(chan string)
for {
fmt.Print("$ ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
log.Fatal("Error getting user input: ", err)
}
for _, host := range hosts {
go func(host *Host) {
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := host.client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run(input); err != nil {
lock <- fmt.Sprintf("%v\n%v", host.hostname, err)
} else {
lock <- fmt.Sprintf("%v\n%v", host.hostname, b.String())
}
}(host)
}
for _ = range hosts {
fmt.Println(<-lock)
}
}
}
作者:routelastresor
项目:go-netcon
func NewTranportSSH(target string, config *ssh.ClientConfig) (*TransportSSH, error) {
if !strings.Contains(target, ":") {
target = fmt.Sprintf("%s:%d", target, SSH_DEFAULT_PORT)
}
conn, err := ssh.Dial("tcp", target, config)
if err != nil {
return nil, err
}
sess, err := conn.NewSession()
if err != nil {
return nil, err
}
si, err := sess.StdinPipe()
if err != nil {
return nil, err
}
so, err := sess.StdoutPipe()
if err != nil {
return nil, err
}
if err := sess.RequestSubsystem(SSH_NETCONF_SUBSYSTEM); err != nil {
return nil, err
}
return &TransportSSH{sshConn: conn, sshSession: sess, sshStdin: si, sshStdout: so}, nil
}
作者:zhongxingzh
项目:gitlab-ci-multi-runne
func (s *Command) Connect() error {
host := helpers.StringOrDefault(s.Host, "localhost")
user := helpers.StringOrDefault(s.User, "root")
port := helpers.StringOrDefault(s.Port, "22")
methods, err := s.getSSHAuthMethods()
if err != nil {
return err
}
config := &ssh.ClientConfig{
User: user,
Auth: methods,
}
connectRetries := s.ConnectRetries
if connectRetries == 0 {
connectRetries = 3
}
var finalError error
for i := 0; i < connectRetries; i++ {
client, err := ssh.Dial("tcp", host+":"+port, config)
if err == nil {
s.client = client
return nil
}
time.Sleep(sshRetryInterval * time.Second)
finalError = err
}
return finalError
}
作者:hermanschaa
项目:goshi
func remoteCmdOutput(username, hostname, privateKey, cmd string) []byte {
block, _ := pem.Decode([]byte(privateKey))
rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
clientKey := &keychain{rsakey}
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(clientKey),
},
}
client, err := ssh.Dial("tcp", hostname, clientConfig)
if err != nil {
log.Println("ERROR: Failed to dial: " + err.Error())
return []byte{}
}
session, err := client.NewSession()
if err != nil {
log.Println("ERROR: Failed to create session: " + err.Error())
return []byte{}
}
defer session.Close()
output, err := session.Output(cmd)
if err != nil {
log.Printf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
return []byte{}
}
return output
}
作者:johntdye
项目:golang-devops-stuf
func getConnection(hostname string) (conn *ssh.ClientConn, err error) {
connectedHostsMutex.Lock()
conn = connectedHosts[hostname]
connectedHostsMutex.Unlock()
if conn != nil {
return
}
defer func() {
if msg := recover(); msg != nil {
err = errors.New("Panic: " + fmt.Sprint(msg))
}
}()
conn, err = ssh.Dial("tcp", hostname+":22", makeConfig())
if err != nil {
return
}
sendProxyReply(&ConnectionProgress{ConnectedHost: hostname})
connectedHostsMutex.Lock()
connectedHosts[hostname] = conn
connectedHostsMutex.Unlock()
return
}
作者:jaibhee
项目:tras
func main() {
key, err := getKeyFile()
if err != nil {
panic(err)
}
config := &ssh.ClientConfig{
User: "jaibheemsen",
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
}
client, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
panic(err)
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
panic(err.Error())
}
fmt.Println(b.String())
} //godoc -http=:1989 -index=true
作者:keysonZZ
项目:km
//TODO 某种认证方法只有一个会被使用,需要多次猜测
func DialInConsole(addr string, username string) (client *ssh.Client, err error) {
//find cert file
pathList := certFilePathList()
authList := []ssh.AuthMethod{}
for _, path := range pathList {
clientKeyBytes, err := ioutil.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err)
}
} else {
signer, err := ssh.ParsePrivateKey(clientKeyBytes)
if err != nil {
return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err)
}
//clientKey := &keychain{signer}
authList = append(authList, ssh.PublicKeys(signer))
}
}
authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) {
fmt.Printf("[ssh] password for %[email protected]%s", username, addr)
secret = string(gopass.GetPasswd())
return
}))
clientConfig := &ssh.ClientConfig{
User: username,
Auth: authList,
}
client, err = ssh.Dial("tcp", addr, clientConfig)
if err != nil {
return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error())
}
return
}
作者:dictyBas
项目:webhook
func getSftpClient(conf Config) []*sftp.Client {
// process the keyfile
buf, err := ioutil.ReadFile(conf.KeyFile)
if err != nil {
log.Fatalf("error in reading private key file %s\n", err)
}
key, err := ssh.ParsePrivateKey(buf)
if err != nil {
log.Fatalf("error in parsing private key %s\n", key)
}
// client config
config := &ssh.ClientConfig{
User: conf.User,
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
}
// connection
clients := make([]*sftp.Client, 0)
for _, r := range conf.Remotes {
c, err := ssh.Dial("tcp", r, config)
if err != nil {
log.Fatalf("error in ssh connection %s\n", err)
}
// sftp handler
sftp, err := sftp.NewClient(c)
if err != nil {
log.Fatalf("error in sftp connection %s\n", err)
}
clients = append(clients, sftp)
}
return clients
}
作者:VukDuki
项目:gotill
func (c *SftpClient) Connect() error {
auth := []ssh.AuthMethod{}
if c.authMethod == "key" {
key, _ := c.GetKey(c.keyPath)
auth = []ssh.AuthMethod{
ssh.PublicKeys(key),
}
} else if c.authMethod == "password" {
auth = []ssh.AuthMethod{
ssh.Password(c.password),
}
}
config := &ssh.ClientConfig{
User: c.username,
Auth: auth,
}
sHost := strings.Join([]string{c.hostname, strconv.FormatInt(c.port, 10)}, ":")
sshClient, err := ssh.Dial("tcp", sHost, config)
if err != nil {
return err
}
sftpClient, err := sftp.NewClient(sshClient)
if err == nil {
c.Client = sftpClient
}
return err
}
作者:rphillip
项目:loo
// connect is a private function to set up the ssh connection. It is called at the beginning of every public
// function.
func (config *Config) connect() (*ssh.Session, error) {
sshconfig := &ssh.ClientConfig{
User: config.User,
}
if config.User == "" {
u, err := user.Current()
if err != nil {
return nil, err
}
sshconfig.User = u.Username
}
if config.Password != "" {
sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password))
}
// By default, we try to include ~/.ssh/id_rsa. It is not an error if this file
// doesn't exist.
keyfile := os.Getenv("HOME") + "/.ssh/id_rsa"
pkey, err := parsekey(keyfile)
if err == nil {
sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
}
// Include any additional key files
for _, keyfile = range config.KeyFiles {
pkey, err = parsekey(keyfile)
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
}
host := config.Host
if strings.Contains(host, ":") == false {
host = host + ":22"
}
client, err := ssh.Dial("tcp", host, sshconfig)
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
session, err := client.NewSession()
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
return session, err
}
作者:IPyand
项目:gopkg
/*
Find or create our connection to the named host. If a connection doesn't
exist, then we'll create one. If the rsync data is present, then we'll
rsynch stuff over while we have the lock.
*/
func (b *Broker) connect2(host string) (c *connection, err error) {
err = nil
need_sync := false // must detect early and execute late so flag if needed
if b == nil || b.was_closed {
err = fmt.Errorf("run_cmd: broker pointer was nil, or broker has been closed")
return
}
if strings.Index(host, ":") < 0 {
host = host + ":22" // add default port if not supplied
}
b.conns_lock.RLock() // get a read lock
c = b.conns[host]
b.conns_lock.RUnlock()
if c != nil && c.active { // we've already connected, just return
return
}
if b.rsync_src != nil && b.rsync_dir != nil { // no connection, rsynch if we need to
need_sync = true // but wait until we auth the connection to prevent prompt
}
b.conns_lock.Lock() // get a write lock
defer b.conns_lock.Unlock() // hold until we return
c = b.conns[host]
if c != nil { // created while we were waiting on lock or existed but not active
if c.active {
return // if active, then safe to send it back now
}
} else {
c = &connection{host: host}
c.retry_ch = make(chan *Broker_msg, 1024) // the host retry queue
}
c.schan, err = ssh.Dial("tcp", host, b.config) // establish the tcp session (ssh channel)
if err != nil {
c = nil
return
}
if need_sync {
toks := strings.Split(host, ":") // must split off port for rsynch
err = b.synch_host(&toks[0])
if err != nil {
err = fmt.Errorf("unable to rsynch to %s: %s", host, err)
c.schan.Close() // if rsynch fails connection "fails"
c.active = false
return
}
}
c.last_cmd = time.Now().Unix()
c.active = true
b.conns[host] = c // finally, add to our map (host:port)
return
}
作者:hut
项目:sandho
func main() {
logger = log.New(os.Stdout, "wam: ", log.LstdFlags|log.Lshortfile)
logger.Println("sandhog")
configData, err := loadConfig()
if err != nil {
printUsage()
logger.Fatalln(err)
}
keyring, err := LoadKeyring(configData.keyPath)
if err != nil {
logger.Fatalln(err)
}
logger.Printf("loaded keyring: %s", keyring)
sshConfig := &ssh.ClientConfig{
User: "wam",
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(keyring),
},
}
logger.Printf("created SSH client config: %s", sshConfig)
// Dial your ssh server.
logger.Println("connecting")
conn, err := ssh.Dial("tcp", "localhost:22", sshConfig)
if err != nil {
logger.Fatalf("unable to connect: %s\n", err)
}
defer conn.Close()
logger.Println("connected!")
// Request the remote side to open port 8080 on all interfaces.
// When they
remoteListenEndpoint := fmt.Sprintf("127.0.0.1:%d", configData.remotePort)
logger.Printf("requesting remote host listen on: %s\n", remoteListenEndpoint)
listener, err := conn.Listen("tcp", remoteListenEndpoint)
if err != nil {
log.Fatalf("unable to register tcp forward: %s", err)
}
defer listener.Close()
logger.Printf("remote host listening on %s\n", remoteListenEndpoint)
for {
conn, err := listener.Accept()
if err != nil {
logger.Println(err)
break
}
go handleConn(conn, *configData)
}
// Serve HTTP with your SSH server acting as a reverse proxy.
http.Serve(listener, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
fmt.Fprintf(resp, "Hello world!\n")
}))
}
作者:davechene
项目:websomte
func main() {
flag.Parse()
config := &ssh.ClientConfig{
User: *sshuser,
Auth: []ssh.ClientAuth{
ssh.ClientAuthPassword(password(*sshpass)),
},
}
conn, err := ssh.Dial("tcp", *sshhost+":22", config)
if err != nil {
log.Fatalf("unable to connect: %s", err)
}
log.Println("connected to ssh server")
defer conn.Close()
http.HandleFunc("/", home)
if *debug {
http.HandleFunc("/resend", resend)
}
http.Handle("/stream", websocket.Handler(streamMail))
sln, err := conn.Listen("tcp", *smtpListen)
if err != nil {
log.Fatalf("error listening for SMTP: %v", err)
}
hln, err := conn.Listen("tcp", *webListen)
if err != nil {
log.Fatalf("error listening for HTTP: %v", err)
}
log.Printf("websomtep listening for HTTP on %q and SMTP on %q\n", *webListen, *smtpListen)
go http.Serve(hln, nil)
s := &smtpd.Server{
OnNewMail: func(c smtpd.Connection, from smtpd.MailAddress) (smtpd.Envelope, error) {
log.Printf("New message from %q", from)
e := &Message{
From: from.Email(),
}
return e, nil
},
}
smtpCountListener := &countingListener{
Listener: sln,
fn: func(count int) {
broadcast(&Message{msg: &SMTPStat{NumSenders: count}})
},
}
err = s.Serve(smtpCountListener)
if err != nil {
log.Fatalf("ListenAndServe: %v", err)
}
}