Ejemplo n.º 1
0
func Example(conn *ssh.Client) {
	// open an SFTP session over an existing ssh connection.
	sftp, err := sftp.NewClient(conn)
	if err != nil {
		log.Fatal(err)
	}
	defer sftp.Close()

	// walk a directory
	w := sftp.Walk("/home/user")
	for w.Step() {
		if w.Err() != nil {
			continue
		}
		log.Println(w.Path())
	}

	// leave your mark
	f, err := sftp.Create("hello.txt")
	if err != nil {
		log.Fatal(err)
	}
	if _, err := f.Write([]byte("Hello world!")); err != nil {
		log.Fatal(err)
	}

	// check it's there
	fi, err := sftp.Lstat("hello.txt")
	if err != nil {
		log.Fatal(err)
	}
	log.Println(fi)
}
Ejemplo n.º 2
0
func (s *SftpSession) Connect() error {

	addr := fmt.Sprintf("%s:%d", s.section.Server, s.section.Port)
	var err error

	if s.section.ProxyServer != "" {

		paddr := fmt.Sprintf("%s:%d", s.section.ProxyServer, s.section.ProxyPort)
		log.Printf("connect to proxy %s", paddr)
		conn, err := net.Dial("tcp", paddr)
		if err != nil {
			return err
		}

		// http connect
		connstr := []byte("CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n\r\n")
		if _, err := conn.Write(connstr); err != nil {
			return errors.New("failed to write connect to http proxy at " + paddr + ": " + err.Error())
		}
		status, err := bufio.NewReader(conn).ReadString('\n')
		if err != nil {
			log.Printf("response: \n%s\n", status)
			return errors.New("failed to read response from http proxy at " + paddr + ": " + err.Error())
		}
		if !strings.Contains(status, " 200 ") {
			return errors.New("error response from http proxy at " + paddr + ": " + status)
		}

		// CONNECT www.google.com.au:443 HTTP/1.1
		// Host: www.google.com.au:443
		//
		// HTTP/1.0 200 Connection Established
		// Proxy-agent: Apache

		sshconn, inch, inrq, err := ssh.NewClientConn(conn, paddr, &s.sshConfig)
		if err != nil {
			return err
		}
		s.connection = ssh.NewClient(sshconn, inch, inrq)

	} else {
		log.Printf("connect to %s", addr)
		s.connection, err = ssh.Dial("tcp", addr, &s.sshConfig)
		if err != nil {
			return err
		}
	}

	// start sftp
	s.client, err = sftp.NewClient(s.connection)
	if err != nil {
		return fmt.Errorf("unable to start sftp subsytem: %v", err)
	}

	return nil

}