Go遠程服務器上傳文件 | go


import (
	"fmt"
	"log"
	"os"
	"path"
	"time"

	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
)

func pwdAuthConnect(sshHost, sshUser, sshPassword string, sshPort int) (*ssh.Client, error) {
	config := ssh.ClientConfig{
		Timeout:         5 * time.Second,
		User:            sshUser,
		Auth:            []ssh.AuthMethod{ssh.Password((sshPassword))},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	addr := fmt.Sprintf("%s:%d", sshHost, sshPort)
	Client, err := ssh.Dial("tcp", addr, &config)
	if err != nil {
		log.Fatal("連接服務器失敗", err)
		return nil, err
	}
	return Client, err
}

// CreateSftp 創建sftp會話
func CreateSftp(sshHost, sshUser, sshPassword string, sshPort int) (*sftp.Client, error) {
	// 連接Linux服務器
	conn, err := pwdAuthConnect(sshHost, sshUser, sshPassword, sshPort)
	if err != nil {
		fmt.Println("連接Linux服務器失敗", err)
		panic(err)
	}
	//defer conn.Close()

	// 創建sftp會話
	client, err := sftp.NewClient(conn)
	if err != nil {
		return nil, err
	}
	//defer client.Close()
	return client, nil
}

func main() {
	client, err := CreateSftp("192.168.225.146", "root", "123456", 22)
	if err != nil {
		return
	}
	defer client.Close()

	// 1.瀏覽服務目錄**
	w := client.Walk("/root")
	for w.Step() {
		if w.Err() != nil {
			continue
		}
		fmt.Println(w.Path())
	}
	// 2.服務器創建文件**
	f, err := client.Create("/tmp/kela.txt")
	if err != nil {
		panic(err)
	}
	_, err = f.Write([]byte("Hello World!\n"))
	if err != nil {
		panic(err)
	}
	f.Close()
	// 3.查看服務器文件**
	fi, err := client.Lstat("/tmp/kela.txt")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", fi)
	// 4.上傳文件**
	localFilePath := "C:/MCDiamond/Files/Study/miaokela/go.sum"
	remoteFilePath := "/root/"
	// 	1) 打開本地文件
	srcFile, err := os.Open(localFilePath)
	if err != nil {
		panic(err)
	}
	defer srcFile.Close()
	// 	絕對路徑中獲取文件名
	remoteFileName := path.Base(localFilePath)
	fmt.Println(remoteFileName)
	// 	2) 打開服務器文件
	dstFile, err := client.Create(path.Join(remoteFilePath, remoteFileName))
	if err != nil {
		panic(err)
	}
	defer dstFile.Close()
	// 	3) 將本地文件內容寫入服務器文件
	buf := make([]byte, 1024)
	for {
		n, _ := srcFile.Read(buf) // 將文件2進制內容寫入buf字節切片中
		if n == 0 {
			break
		}
		dstFile.Write(buf)
	}
	fmt.Println("文件上傳完畢")
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM