码迷,mamicode.com
首页 > 其他好文 > 详细

golang通过ssh实现远程文件传输

时间:2019-06-20 09:36:54      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:end   远程服务   tco   crypto   image   pcl   通过   timeout   官方   

使用ssh远程操作文件, 主要是创建ssh, 直接上代码


import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"net"
"strconv"
"time"
)

func SftpConnect(user, password, host string, port int) (sftpClient *sftp.Client, err error) { //参数: 远程服务器用户名, 密码, ip, 端口
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
},
}

addr := host + ":" + strconv.Itoa(port)
sshClient, err := ssh.Dial("tcp", addr, clientConfig) //连接ssh
if err != nil {
fmt.Println("连接ssh失败", err)
return
}

if sftpClient, err = sftp.NewClient(sshClient); err != nil { //创建客户端
fmt.Println("创建客户端失败", err)
return
}

return
}

使用也很简单

技术图片

sftpClient.Open() 返回的是*sftp.File, 操作和官方库差不多

golang通过ssh实现远程文件传输

标签:end   远程服务   tco   crypto   image   pcl   通过   timeout   官方   

原文地址:https://www.cnblogs.com/-xuzhankun/p/11056576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!