func DialSSH(addr string, username string, keyFilename string) (conn *SSHConn, err error) { conn = &SSHConn{} if keyFilename != "" { pemKey, err := ioutil.ReadFile(keyFilename) if err != nil { return } signer, err := ssh.ParsePrivateKey(pemKey) if err != nil { return } conn.Auth = ssh.PublicKeys(signer) } else { sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return } conn.Auth = ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers) } conn.Config = &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ conn.Auth, }, } conn.Client, err = ssh.Dial("tcp", fmt.Sprintf("%s:22", addr), conn.Config) return }
func ExampleClientAgent() { // ssh-agent has a UNIX socket under $SSH_AUTH_SOCK socket := os.Getenv("SSH_AUTH_SOCK") conn, err := net.Dial("unix", socket) if err != nil { log.Fatalf("net.Dial: %v", err) } agentClient := agent.NewClient(conn) config := &ssh.ClientConfig{ User: "******", Auth: []ssh.AuthMethod{ // Use a callback rather than PublicKeys // so we only consult the agent once the remote server // wants it. ssh.PublicKeysCallback(agentClient.Signers), }, } sshc, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatalf("Dial: %v", err) } // .. use sshc sshc.Close() }
func SSHAgent() ssh.AuthMethod { if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers) } return nil }
func Connection(info ConnetctionInfo) *ssh.Client { var auths []ssh.AuthMethod auths = append(auths, privateKey...) if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers)) } auths = append(auths, ssh.Password(info.Passwd)) config := ssh.ClientConfig{ User: info.User, Auth: auths, } for i := 0; i < 3; i++ { //conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", info.IP, info.Port), &config) conn, err := ssh.DialTimeOut("tcp", fmt.Sprintf("%s:%s", info.IP, info.Port), 30, &config) if err == nil { return conn } if i == 2 && err != nil { ErrorList = append(ErrorList, fmt.Sprintf("连接%s失败:%s\n", info.IP, err)) return nil } time.Sleep(1e9) } return nil }
func (sfs *SftpFileSystem) Connect() error { var auths []ssh.AuthMethod if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers)) } if len(sfs.sp.Password) != 0 { auths = append(auths, ssh.Password(sfs.sp.Password)) } config := ssh.ClientConfig{ User: sfs.sp.Username, Auth: auths, } var err error sfs.sshClient, err = ssh.Dial("tcp", sfs.sp.Server, &config) if err != nil { log.Println("unable to connect to [%s]: %v", sfs.sp.Server, err) return err } sfs.sftpClient, err = sftp.NewClient(sfs.sshClient) if err != nil { log.Println("unable to start sftp subsytem: %v", err) return err } return nil }
func (this *SSHExecutor) connect() error { // auths holds the detected ssh auth methods auths := []ssh.AuthMethod{} // figure out what auths are requested, what is supported if this.Password != "" { auths = append(auths, ssh.Password(this.Password)) } if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) defer sshAgent.Close() } config := &ssh.ClientConfig{ User: this.User, Auth: auths, } client, err := ssh.Dial("tcp", this.Hostname+":"+strconv.Itoa(this.Port), config) if err != nil { return err } session, err := client.NewSession() if err != nil { return err } this.Session = session return nil }
func main() { auth_socket := os.Getenv("SSH_AUTH_SOCK") if auth_socket == "" { log.Fatal(errors.New("no $SSH_AUTH_SOCK defined")) } conn, err := net.Dial("unix", auth_socket) if err != nil { log.Fatal(err) } defer conn.Close() ag := agent.NewClient(conn) auths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)} config := &ssh.ClientConfig{ User: Username, Auth: auths, HostKeyCallback: KeyScanCallback, } var wg sync.WaitGroup go out(&wg) reader := bufio.NewReader(os.Stdin) for { server, err := reader.ReadString('\n') if err == io.EOF { break } server = server[:len(server)-1] // chomp wg.Add(2) // dial and print go dial(server, config, &wg) } wg.Wait() }
func (conf *SshConfig) Client() (*ssh.Client, error) { auths := []ssh.AuthMethod{} if !Empty(conf.Password) { auths = append(auths, ssh.Password(conf.Password)) } if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) defer sshAgent.Close() } if pubkey, err := getKeyFile(conf.Key); err == nil { auths = append(auths, ssh.PublicKeys(pubkey)) } config := &ssh.ClientConfig{ User: conf.User, Auth: auths, } client, err := ssh.Dial("tcp", conf.Name+":"+conf.Port, config) if err != nil { return nil, err } return client, nil }
// connects to remote server using ClientSSH struct and returns *ssh.Session func (ssh_conf *ClientSSH) connect() (*ssh.Session, error) { // auths holds the detected ssh auth methods auths := []ssh.AuthMethod{} // figure out what auths are requested, what is supported if ssh_conf.Password != "" { auths = append(auths, ssh.Password(ssh_conf.Password)) } if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) defer sshAgent.Close() } if pubkey, err := getKeyFile(ssh_conf.Key); err == nil { auths = append(auths, ssh.PublicKeys(pubkey)) } config := &ssh.ClientConfig{ User: ssh_conf.User, Auth: auths, } client, err := ssh.Dial("tcp", ssh_conf.Server+":"+ssh_conf.Port, config) if err != nil { return nil, err } session, err := client.NewSession() if err != nil { return nil, err } return session, nil }
func sshClient(username, host string) (*ssh.Client, error) { agentconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return nil, err } aclient := agent.NewClient(agentconn) conf := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(aclient.Signers), }, } if strings.Index(host, ":") < 0 { host = host + ":22" } cli, err := ssh.Dial("tcp", host, conf) if err != nil { return nil, err } return cli, nil }
func (ctx *ExecContext) reconnect() (err error) { if ctx.hostname != "" { ctx.isReconnecting = true username := ctx.username addr := fmt.Sprintf("%s:%d", ctx.hostname, ctx.port) ctx.unlock() agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { ctx.lock() ctx.isReconnecting = false return err } defer agentConn.Close() ag := agent.NewClient(agentConn) auths := []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)} config := &ssh.ClientConfig{ User: username, Auth: auths, } conn, err := net.DialTimeout("tcp", addr, networkTimeout) if err != nil { ctx.lock() ctx.isReconnecting = false return err } timeoutConn := &Conn{conn, networkTimeout, networkTimeout} c, chans, reqs, err := ssh.NewClientConn(timeoutConn, addr, config) if err != nil { ctx.lock() ctx.isReconnecting = false return err } client := ssh.NewClient(c, chans, reqs) // Send periodic keepalive messages go func() { t := time.NewTicker(networkTimeout / 2) defer t.Stop() for { <-t.C _, _, err := client.Conn.SendRequest("*****@*****.**", true, nil) if err != nil { ctx.lock() if ctx.sshClient == client { ctx.isConnected = false } ctx.unlock() return } } }() ctx.lock() ctx.isReconnecting = false ctx.sshClient = client } ctx.isConnected = true return nil }
func sshAgent() (ssh.AuthMethod, func(), error) { sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return nil, func() {}, err } method := ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers) return method, func() { _ = sshAgent.Close() }, nil }
func loadEnvAgent() (auths []ssh.AuthMethod, err error) { sshAuthSock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return } defer sshAuthSock.Close() ag := agent.NewClient(sshAuthSock) auths = []ssh.AuthMethod{ssh.PublicKeysCallback(ag.Signers)} return }
func getAgentAuth() (auth ssh.AuthMethod, ok bool) { if sock := os.Getenv("SSH_AUTH_SOCK"); len(sock) > 0 { if agconn, err := net.Dial("unix", sock); err == nil { ag := agent.NewClient(agconn) auth = ssh.PublicKeysCallback(ag.Signers) ok = true } } return }
func setupSshClient() (*ssh.Client, net.Conn, error) { agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return nil, nil, err } agentClient := agent.NewClient(agentConn) client, err := ssh.Dial("tcp", Config.Host, &ssh.ClientConfig{ User: Config.Username, Auth: []ssh.AuthMethod{ssh.PublicKeysCallback(agentClient.Signers)}, }) return client, agentConn, err }
func (r *SSHCmd) UseAgent() error { if r.connected { return fmt.Errorf("Cannot add authentication methods while being connected") } sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return err } r.config.Auth = append(r.config.Auth, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) return nil }
// SSHConfigPubKeyAgent is a convience function that takes a username and // returns a new ssh.Clientconfig setup to pass credentials received from // an ssh agent func SSHConfigPubKeyAgent(user string) (*ssh.ClientConfig, error) { c, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return nil, err } return &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(agent.NewClient(c).Signers), }, }, nil }
// connects to remote server using MakeConfig struct and returns *ssh.Session func (ssh_conf *MakeConfig) Connect() (*ssh.Session, error) { auths := []ssh.AuthMethod{} // Parse ssh config hosts, err := config.ParseSSHConfig(os.Getenv("HOME") + "/.ssh/config") if err == nil { for _, host := range hosts { if stringInSlice(ssh_conf.Server, host.Host) { ssh_conf.Server = host.HostName ssh_conf.User = host.User ssh_conf.Port = strconv.Itoa(host.Port) ssh_conf.Key = []string{host.IdentityFile} } } } var keys []ssh.Signer for _, v := range ssh_conf.Key { pubkey, err := getKeyFile(v) if err != nil { continue } keys = append(keys, pubkey) } // in POSIX systems, try ssh auth sock if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)) defer sshAgent.Close() } auths = append(auths, ssh.PublicKeys(keys...)) config := &ssh.ClientConfig{ User: ssh_conf.User, Auth: auths, } client, err := ssh.Dial("tcp", ssh_conf.Server+":"+ssh_conf.Port, config) if err != nil { return nil, err } session, err := client.NewSession() if err != nil { return nil, err } return session, nil }
func main() { var auths []ssh.AuthMethod if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers)) } if *PASS != "" { auths = append(auths, ssh.Password(*PASS)) } config := ssh.ClientConfig{ User: *USER, Auth: auths, } addr := fmt.Sprintf("%s:%d", *HOST, *PORT) conn, err := ssh.Dial("tcp", addr, &config) if err != nil { log.Fatalf("unable to connect to [%s]: %v", addr, err) } defer conn.Close() c, err := sftp.NewClient(conn) if err != nil { log.Fatalf("unable to start sftp subsytem: %v", err) } defer c.Close() w, err := c.OpenFile("/dev/null", syscall.O_WRONLY) if err != nil { log.Fatal(err) } defer w.Close() f, err := os.Open("/dev/zero") if err != nil { log.Fatal(err) } defer f.Close() const size int64 = 1e9 log.Printf("writing %v bytes", size) t1 := time.Now() n, err := io.Copy(w, io.LimitReader(f, size)) if err != nil { log.Fatal(err) } if n != size { log.Fatalf("copy: expected %v bytes, got %d", size, n) } log.Printf("wrote %v bytes in %s", size, time.Since(t1)) }
func (c *comm) connectToAgent() { if c.client == nil { return } if c.config.DisableAgent { log.Printf("[INFO] SSH agent forwarding is disabled.") return } // open connection to the local agent socketLocation := os.Getenv("SSH_AUTH_SOCK") if socketLocation == "" { log.Printf("[INFO] no local agent socket, will not connect agent") return } agentConn, err := net.Dial("unix", socketLocation) if err != nil { log.Printf("[ERROR] could not connect to local agent socket: %s", socketLocation) return } // create agent and add in auth forwardingAgent := agent.NewClient(agentConn) if forwardingAgent == nil { log.Printf("[ERROR] Could not create agent client") agentConn.Close() return } // add callback for forwarding agent to SSH config // XXX - might want to handle reconnects appending multiple callbacks auth := ssh.PublicKeysCallback(forwardingAgent.Signers) c.config.SSHConfig.Auth = append(c.config.SSHConfig.Auth, auth) agent.ForwardToAgent(c.client, forwardingAgent) // Setup a session to request agent forwarding session, err := c.newSession() if err != nil { return } defer session.Close() err = agent.RequestAgentForwarding(session) if err != nil { log.Printf("[ERROR] RequestAgentForwarding: %#v", err) return } log.Printf("[INFO] agent forwarding enabled") return }
func withAgentSSHConfig(username string) (*ssh.ClientConfig, error) { agent, err := getAgent() if err != nil { return &ssh.ClientConfig{}, err } config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(agent.Signers), }, } return config, nil }
func withAgentSshConfig(username string) *ssh.ClientConfig { agent, err := getAgent() if err != nil { log.Println("Failed to connect to SSH_AUTH_SOCK:", err) os.Exit(1) } config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(agent.Signers), }, } return config }
func getAgentAuths() *agentAuths { conn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { log.Fatal(err) } ac := agent.NewClient(conn) aa := &agentAuths{ c: conn, a: ac, auths: []ssh.AuthMethod{ssh.PublicKeysCallback(ac.Signers)}, } return aa }
func sshAuths(addr *url.URL) (methods []ssh.AuthMethod) { c, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err == nil { auth := ssh.PublicKeysCallback(agent.NewClient(c).Signers) methods = append(methods, auth) } auth := ssh.PasswordCallback(func() (string, error) { fmt.Printf("%s@%s password: "******"\n") return string(b), err }) methods = append(methods, auth) return }
func (c *comm) connectToAgent() { if c.client == nil { return } if c.config.DisableAgent { return } // open connection to the local agent socketLocation := os.Getenv("SSH_AUTH_SOCK") if socketLocation == "" { return } agentConn, err := net.Dial("unix", socketLocation) if err != nil { c.config.Logger.Error("could not connect to local agent socket", "socket_path", socketLocation) return } defer agentConn.Close() // create agent and add in auth forwardingAgent := agent.NewClient(agentConn) if forwardingAgent == nil { c.config.Logger.Error("could not create agent client") return } // add callback for forwarding agent to SSH config // XXX - might want to handle reconnects appending multiple callbacks auth := ssh.PublicKeysCallback(forwardingAgent.Signers) c.config.SSHConfig.Auth = append(c.config.SSHConfig.Auth, auth) agent.ForwardToAgent(c.client, forwardingAgent) // Setup a session to request agent forwarding session, err := c.NewSession() if err != nil { return } defer session.Close() err = agent.RequestAgentForwarding(session) if err != nil { c.config.Logger.Error("error requesting agent forwarding", "error", err) return } return }
func main() { var auths []ssh.AuthMethod if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers)) } if *PASS != "" { auths = append(auths, ssh.Password(*PASS)) } config := ssh.ClientConfig{ User: *USER, Auth: auths, } addr := fmt.Sprintf("%s:%d", *HOST, *PORT) conn, err := ssh.Dial("tcp", addr, &config) if err != nil { log.Fatalf("unable to connect to [%s]: %v", addr, err) } defer conn.Close() c, err := sftp.NewClient(conn, sftp.MaxPacket(*SIZE)) if err != nil { log.Fatalf("unable to start sftp subsytem: %v", err) } defer c.Close() r, err := c.Open("/dev/zero") if err != nil { log.Fatal(err) } defer r.Close() const size = 1e9 log.Printf("reading %v bytes", size) t1 := time.Now() n, err := io.ReadFull(r, make([]byte, size)) if err != nil { log.Fatal(err) } if n != size { log.Fatalf("copy: expected %v bytes, got %d", size, n) } log.Printf("read %v bytes in %s", size, time.Since(t1)) }
// SSHConfig returns a function that can be used for the SSH communicator // config for connecting to the instance created over SSH using the private key // or password. func SSHConfig(useAgent bool, username, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) { return func(state multistep.StateBag) (*ssh.ClientConfig, error) { if useAgent { authSock := os.Getenv("SSH_AUTH_SOCK") if authSock == "" { return nil, fmt.Errorf("SSH_AUTH_SOCK is not set") } sshAgent, err := net.Dial("unix", authSock) if err != nil { return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err) } return &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers), }, }, nil } privateKey, hasKey := state.GetOk("privateKey") if hasKey { signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string))) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } return &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeys(signer), }, }, nil } else { return &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), ssh.KeyboardInteractive( packerssh.PasswordKeyboardInteractive(password)), }}, nil } } }
func createSSHAgentAuth(username string) (*ssh.ClientConfig, error) { sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { fmt.Println("Unable to configure authorization") fmt.Println("Error : ", err.Error()) return nil, err } clientConfig := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers), }, } return clientConfig, nil }
func (c *Client) Connect() (e error) { if c.Port == 0 { c.Port = 22 } var auths []ssh.AuthMethod if c.password != "" { auths = append(auths, ssh.Password(c.password)) } else if c.Agent, e = net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); e == nil { auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(c.Agent).Signers)) } config := &ssh.ClientConfig{ User: c.User, Auth: auths, } c.Conn, e = ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, c.Port), config) return e }
func sshAuths(addr *url.URL) (methods []ssh.AuthMethod) { if sock := os.Getenv("SSH_AUTH_SOCK"); sock != "" { c, err := net.Dial("unix", sock) if err != nil { log.Println("Warning: failed to contact the local SSH agent") } else { auth := ssh.PublicKeysCallback(agent.NewClient(c).Signers) methods = append(methods, auth) } } auth := ssh.PasswordCallback(func() (string, error) { fmt.Printf("%s@%s password: "******"\n") return string(b), err }) methods = append(methods, auth) return }