// ListKeys connects to the local SSH Agent and lists all the public keys // loaded into it. It returns user friendly error message when it has trouble. func ListKeys() ([]*agent.Key, error) { sshAuthSock := os.Getenv("SSH_AUTH_SOCK") if sshAuthSock == "" { return nil, fmt.Errorf( "The SSH_AUTH_SOCK environment variable is not set, which normally\n" + "means that no SSH Agent is running.") } conn, err := net.Dial("unix", sshAuthSock) if err != nil { return nil, fmt.Errorf( "Error connecting to agent: %s\n\n"+ "The agent address is detected using the SSH_AUTH_SOCK environment\n"+ "variable. Please verify this variable is correct and the SSH agent\n"+ "is properly set up.", err) } defer conn.Close() agent := agent.NewClient(conn) loadedKeys, err := agent.List() if err != nil { return nil, fmt.Errorf("Error listing keys: %s", err) } return loadedKeys, err }
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 (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 }
// initAuthMethod initiates SSH authentication method. func initAuthMethod() { var signers []ssh.Signer // If there's a running SSH Agent, try to use its Private keys. sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err == nil { agent := agent.NewClient(sock) signers, _ = agent.Signers() } // Try to read user's SSH private keys form the standard paths. files := []string{ os.Getenv("HOME") + "/.ssh/id_rsa", os.Getenv("HOME") + "/.ssh/id_dsa", } for _, file := range files { data, err := ioutil.ReadFile(file) if err != nil { continue } signer, err := ssh.ParsePrivateKey(data) if err != nil { continue } signers = append(signers, signer) } authMethod = ssh.PublicKeys(signers...) }
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 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 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 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 }
// New returns a new agent.Agent and the (custom) connection it uses // to communicate with a running pagent.exe instance (see README.md) func New() (agent.Agent, net.Conn, error) { if !Available() { return nil, nil, errors.New("SSH agent requested but Pageant not running") } return agent.NewClient(&conn{}), nil, nil }
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 NewSshExecWithAuth(user string) *SshExec { sshexec := &SshExec{} authSocket := os.Getenv("SSH_AUTH_SOCK") if authSocket == "" { log.Fatal("SSH_AUTH_SOCK required, check that your ssh agent is running") return nil } agentUnixSock, err := net.Dial("unix", authSocket) if err != nil { log.Fatal(err) return nil } agent := agent.NewClient(agentUnixSock) signers, err := agent.Signers() if err != nil { log.Fatal(err) return nil } sshexec.clientConfig = &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...)}, } return sshexec }
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 (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 main() { if !(len(os.Args) > 1) { log.Fatal("action required.") } action := os.Args[1] os.Args = append(os.Args[:1], os.Args[2:]...) flag.Parse() authSocket := os.Getenv("SSH_AUTH_SOCK") if authSocket == "" { log.Fatal("SSH_AUTH_SOCK required, check that your ssh agent is running") } agentUnixSock, err := net.Dial("unix", authSocket) if err != nil { log.Fatal(err) } agent := agent.NewClient(agentUnixSock) signers, err := agent.Signers() if err != nil { log.Fatal(err) } clientConfig = &ssh.ClientConfig{ User: sshUser, Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...)}, } hostsList := strings.Split(hosts, ",") if !(len(hostsList) > 0) { log.Fatal("one or more hosts required, use the -host flag") } stderrChan = make(chan string, 0) stdoutChan = make(chan string, 0) go consoleWriter() switch action { case "deploy": if etcdBinary != "" { deployFromEtcdBinary(etcdBinary, hostsList) os.Exit(0) } if gitCommit != "" { deployFromGitCommit(gitCommit, hostsList) os.Exit(0) } if gitTag != "" { deployFromGitTag(gitTag, hostsList) os.Exit(0) } case "version": etcdVersion(hostsList) } }
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 }
// Dial creates a client connection to the given SSH server. // // `addr` should be provided in the following format: // // user@host:port // // if `forwardAgent` is true then forwarding of the authentication agent connection will be enabled. func Dial(addr string, socket string, forwardAgent bool) (*SSHConn, error) { agentConn, err := net.Dial("unix", socket) if err != nil { return nil, err } var agentOk bool defer func() { if !agentOk { agentConn.Close() } }() sshAgent := agent.NewClient(agentConn) signers, err := sshAgent.Signers() if err != nil { return nil, err } host, port, user, err := ParseAddr(addr) if err != nil { return nil, err } config := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...)}, Timeout: ConnTimeout, } client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config) if err != nil { return nil, err } var clientOk bool defer func() { if !clientOk { client.Close() } }() if forwardAgent { if err := agent.ForwardToAgent(client, sshAgent); err != nil { return nil, fmt.Errorf("SetupForwardKeyring: %v", err) } } agentOk = true clientOk = true c := SSHConn{ client: client, agentConn: agentConn, forwardAgent: forwardAgent, } return &c, nil }
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 }
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 }
// 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)) }
// Opens a pipe with the ssh agent and uses the pipe // as the implementer of the public key callback function. func newSSHAgentConn() (*sshAgentConn, error) { pipe, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { return nil, err } return &sshAgentConn{ pipe: pipe, auth: &PublicKeysCallback{ User: "******", Callback: agent.NewClient(pipe).Signers, }, }, nil }
// SSHAgentClient returns an Agent that talks to the local ssh-agent func SSHAgentClient() (gosshagent.Agent, error) { sock := os.Getenv("SSH_AUTH_SOCK") if sock == "" { return nil, errors.New("SSH_AUTH_SOCK environment variable is not set. Verify ssh-agent is running. See https://github.com/coreos/fleet/blob/master/Documentation/using-the-client.md for help.") } agent, err := net.Dial("unix", sock) if err != nil { return nil, err } return gosshagent.NewClient(agent), nil }
func newAgent() (agent.Agent, error) { sock := os.Getenv("SSH_AUTH_SOCK") if sock == "" { return nil, errors.New("Unable to connect to the ssh agent. Please, check that SSH_AUTH_SOCK is set and the ssh agent is running") } conn, err := net.Dial("unix", sock) if err != nil { return nil, err } return agent.NewClient(conn), nil }
// New returns a new agent.Agent that uses a unix socket func New() (agent.Agent, net.Conn, error) { if !Available() { return nil, nil, errors.New("SSH agent requested but SSH_AUTH_SOCK not-specified") } sshAuthSock := os.Getenv("SSH_AUTH_SOCK") conn, err := net.Dial("unix", sshAuthSock) if err != nil { return nil, nil, fmt.Errorf("Error connecting to SSH_AUTH_SOCK: %v", err) } return agent.NewClient(conn), conn, nil }