package main import ( "fmt" "github.com/pkg/sftp" "golang.org/x/crypto/ssh" "log" "net" "os" "path" "time" ) func connect(user, password, host string, port int) (*sftp.Client, error) { var ( auth []ssh.AuthMethod addr string clientConfig *ssh.ClientConfig sshClient *ssh.Client sftpClient *sftp.Client err error ) // get auth method auth = make([]ssh.AuthMethod, 0) auth = append(auth, ssh.Password(password)) clientConfig = &ssh.ClientConfig{ User: user, Auth: auth, Timeout: 30 * time.Second, HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }, } // connet to ssh addr = fmt.Sprintf("%s:%d", host, port) if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil { return nil, err } // create sftp client if sftpClient, err = sftp.NewClient(sshClient); err != nil { return nil, err } return sftpClient, nil } func main() { var ( err error sftpClient *sftp.Client ) sftpClient, err = connect("root", "123", "192.168.10.101", 22) if err != nil { log.Fatal(1, err) } defer sftpClient.Close() var remoteFilePath = "/home/_backup/mysql/db_glazing-" + time.Now().Format("02-Jan-2006") + ".tar.gz" var localDir = "/home/_backup" srcFile, err := sftpClient.Open(remoteFilePath) if err != nil { log.Fatal(err) } defer srcFile.Close() var localFileName = path.Base(remoteFilePath) dstFile, err := os.Create(path.Join(localDir, localFileName)) if err != nil { log.Fatal(err) } defer dstFile.Close() if _, err = srcFile.WriteTo(dstFile); err != nil { log.Fatal(err) } fmt.Println("copy file from remote server finished!") }
sftp_download
最新推荐文章于 2024-06-26 17:04:03 发布