日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

go实现ssh远程机器并传输文件

發布時間:2023/12/29 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 go实现ssh远程机器并传输文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?項目目錄結構:

?sshtool.go:

package ssh_toolimport ("flag""fmt""github.com/pkg/sftp""golang.org/x/crypto/ssh""io""log""net""os""path""time" )// SshClient ssh客戶端對象 /* type SshClient struct {username stringpassword stringhost stringClient * ssh.Client }func (sshClient * SshClient) NewSshClient() *ssh.Client{flag.StringVar(&sshClient.username,"username","root","通過ssh2登錄linux的用戶名")flag.StringVar(&sshClient.password,"password","root","通過ssh2登錄linux的密碼")flag.StringVar(&sshClient.host,"host","192.168.56.25","通過ssh2登錄linux的ip地址")flag.Parse()log.Println(sshClient.password)auth := make([]ssh.AuthMethod, 0)auth = append(auth, ssh.Password(sshClient.password))clientConfig := &ssh.ClientConfig{User: sshClient.username,Auth: auth,Timeout: 30 * time.Second,HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {return nil},}addr := sshClient.host + ":22"client, err := ssh.Dial("tcp", addr, clientConfig) //連接sshif err != nil {log.Fatal("連接ssh失敗", err)}sshClient.Client = clientreturn client }func (sshClient * SshClient) RunCmd(cmd string) string {session, err := sshClient.Client.NewSession()if err != nil{panic(err)}defer session.Close()runResult,err := session.CombinedOutput(cmd)if err != nil{panic(err)}return string(runResult) }func (sshClient * SshClient) UploadFile(localPath string, remoteDir string, remoteFileName string){ftpClient, err := sftp.NewClient(sshClient.Client)if err != nil {fmt.Println("創建ftp客戶端失敗", err)panic(err)}defer ftpClient.Close()fmt.Println(localPath, remoteFileName)srcFile, err := os.Open(localPath)if err != nil {fmt.Println("打開文件失敗", err)panic(err)}defer srcFile.Close()dstFile, e := ftpClient.Create(path.Join(remoteDir, remoteFileName))if e != nil {fmt.Println("創建文件失敗", e)panic(e)}defer dstFile.Close()buffer := make([]byte, 1024000)for {n, err := srcFile.Read(buffer)dstFile.Write(buffer[:n])//注意,由于文件大小不定,不可直接使用buffer,否則會在文件末尾重復寫入,以填充1024的整數倍if err != nil {if err == io.EOF {fmt.Println("已讀取到文件末尾")break} else {fmt.Println("讀取文件出錯", err)panic(err)}}} }func (sshClient * SshClient) DownloadFile(remotePath string, localDir string , localFilename string) {ftpClient, err := sftp.NewClient(sshClient.Client)if err != nil {fmt.Println("創建ftp客戶端失敗", err)panic(err)}defer ftpClient.Close()srcFile, err := ftpClient.Open(remotePath)if err != nil {fmt.Println("文件讀取失敗", err)panic(err)}defer srcFile.Close()dstFile, e := os.Create(path.Join(localDir, localFilename))if e != nil {fmt.Println("文件創建失敗", e)panic(e)}defer dstFile.Close()if _, err1 := srcFile.WriteTo(dstFile); err1 != nil {fmt.Println("文件寫入失敗", err1)panic(err1)}fmt.Println("文件下載成功") }

const_values.go:?

package constkvconst (MSG_CODE_KEY = "code"MSG_CONTENT_KEY = "msg" )

SSHRemote.go:?

package mainimport ("SSH/constkv""SSH/ssh_tool""bufio""encoding/json""io""log""net/http" )var (sshClient = new(ssh_tool.SshClient)buffer = make([]byte,10240) )func handlerCmd(writer http.ResponseWriter, request *http.Request) {var resultMap = make(map[string]interface{})//處理錯誤的panicdefer func() {err := recover()if err != nil{resultMap[constkv.MSG_CODE_KEY] = http.StatusOKresultMap[constkv.MSG_CONTENT_KEY] = err.(error).Error()bytes, _ := json.Marshal(&resultMap)writer.Write(bytes)}}()var bufferSlice = make([]byte,0)reader := request.BodybufferReader := bufio.NewReader(reader)for {length, err := bufferReader.Read(buffer)bufferSlice = append(bufferSlice,buffer[:length]...)if err == io.EOF{break}}log.Println(string(bufferSlice))var paramMap = make(map[string]interface{})_ = json.Unmarshal(bufferSlice, &paramMap)log.Println(paramMap["cmd"])cmd := paramMap["cmd"]log.Println(cmd.(string) + "--------------------")if sshClient.Client != nil{runCmd := sshClient.RunCmd(cmd.(string))resultMap[constkv.MSG_CODE_KEY] = http.StatusOKresultMap[constkv.MSG_CONTENT_KEY] = runCmd}bytes, _ := json.Marshal(&resultMap)_ , _ = writer.Write(bytes) }func handleUploadFile(writer http.ResponseWriter, request *http.Request) {var resultMap = make(map[string]interface{})//處理錯誤的panicdefer func() {err := recover()if err != nil{resultMap[constkv.MSG_CODE_KEY] = http.StatusOKresultMap[constkv.MSG_CONTENT_KEY] = err.(error).Error()bytes, _ := json.Marshal(&resultMap)writer.Write(bytes)}}()var bufferSlice = make([]byte,0)reader := request.BodybufferReader := bufio.NewReader(reader)for {length, err := bufferReader.Read(buffer)bufferSlice = append(bufferSlice,buffer[:length]...)if err == io.EOF{break}}log.Println(string(bufferSlice))var paramMap = make(map[string]interface{})_ = json.Unmarshal(bufferSlice, &paramMap)localPath := paramMap["localPath"]remoteDir := paramMap["remoteDir"]remoteFileName := paramMap["remoteFileName"]log.Println(localPath)log.Println(remoteDir)sshClient.UploadFile(localPath.(string),remoteDir.(string),remoteFileName.(string)) }func handleDownloadFile(writer http.ResponseWriter, request *http.Request) {var resultMap = make(map[string]interface{})//處理錯誤的panicdefer func() {err := recover()if err != nil{resultMap[constkv.MSG_CODE_KEY] = http.StatusOKresultMap[constkv.MSG_CONTENT_KEY] = err.(error).Error()bytes, _ := json.Marshal(&resultMap)writer.Write(bytes)}}()var bufferSlice = make([]byte,0)reader := request.BodybufferReader := bufio.NewReader(reader)for {length, err := bufferReader.Read(buffer)bufferSlice = append(bufferSlice,buffer[:length]...)if err == io.EOF{break}}log.Println(string(bufferSlice))var paramMap = make(map[string]interface{})_ = json.Unmarshal(bufferSlice, &paramMap)remotePath := paramMap["remotePath"]localDir := paramMap["localDir"]localFileName := paramMap["localFileName"]log.Println(remotePath)log.Println(localDir)log.Println(localFileName)sshClient.DownloadFile(remotePath.(string),localDir.(string),localFileName.(string)) }func main(){//初始化ssh客戶端sshClient.NewSshClient()//1.注冊一個給定模式的處理器函數到DefaultServeMuxhttp.HandleFunc("/", handlerCmd)http.HandleFunc("/uploadFile", handleUploadFile)http.HandleFunc("/downloadFile", handleDownloadFile)//2.設置監聽的TCP地址并啟動服務//參數1:TCP地址(IP+Port)//參數2:當設置為nil時表示使用DefaultServeMuxerr := http.ListenAndServe(":8080", nil)log.Fatal(err) }

總結

以上是生活随笔為你收集整理的go实现ssh远程机器并传输文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。