golang使用sftp连接服务器远程上传、下载文件
安装github.com/pkg/sftp
我们之前介绍了,golang如何通过ssh连接服务器执行命令,下面我们来如何上传文件,上传文件同样需要之前的ssh,但是除此之外还需要一个模块,直接使用go get github.com/pkg/sftp 安装即可
使用
package main
import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"log"
"net"
"os"
"time"
)
//连接的配置
type ClientConfig struct {
Host string //ip
Port int64 // 端口
Username string //用户名
Password string //密码
sshClient *ssh.Client //ssh client
sftpClient *sftp.Client //sftp client
LastResult string //最近一次运行的结果
}
func (cliConf *ClientConfig) createClient(host string, port int64, username, password string) {
var (
sshClient *ssh.Client
sftpClient *sftp.Client
err error
)
cliConf.Host = host
cliConf.Port = port
cliConf.Username = username
cliConf.Password = password
cliConf.Port = port
config := ssh.ClientConfig{
User: cliConf.Username,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 10 * time.Second,
}
addr := fmt.Sprintf("%s:%d", cliConf.Host, cliConf.Port)
if sshClient, err = ssh.Dial("tcp", addr, &config); err != nil {
log.Fatalln("error occurred:", err)
}
cliConf.sshClient = sshClient
//此时获取了sshClient,下面使用sshClient构建sftpClient
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
log.Fatalln("error occurred:", err)
}
cliConf.sftpClient = sftpClient
}
func (cliConf *ClientConfig) RunShell(shell string) string {
var (
session *ssh.Session
err error
)
//获取session,这个session是用来远程执行操作的
if session, err = cliConf.sshClient.NewSession(); err != nil {
log.Fatalln("error occurred:", err)
}
//执行shell
if output, err := session.CombinedOutput(shell); err != nil {
fmt.Println(shell)
log.Fatalln("error occurred:", err)
} else {
cliConf.LastResult = string(output)
}
return cliConf.LastResult
}
func (cliConf *ClientConfig) Upload(srcPath, dstPath string){
srcFile, _ := os.Open(srcPath) //本地
dstFile, _ := cliConf.sftpClient.Create(dstPath) //远程
defer func() {
_ = srcFile.Close()
_ = dstFile.Close()
}()
buf := make([]byte, 1024)
for {
n, err := srcFile.Read(buf)
if err != nil {
if err != io.EOF {
log.Fatalln("error occurred:",err)
} else {
break
}
}
_, _ = dstFile.Write(buf[: n])
}
fmt.Println(cliConf.RunShell(fmt.Sprintf("ls %s", dstPath)))
}
func (cliConf *ClientConfig) Download(srcPath, dstPath string){
srcFile, _ := cliConf.sftpClient.Open(srcPath) //远程
dstFile, _ := os.Create(dstPath) //本地
defer func() {
_ = srcFile.Close()
_ = dstFile.Close()
}()
if _, err := srcFile.WriteTo(dstFile); err != nil {
log.Fatalln("error occurred", err)
}
fmt.Println("文件下载完毕")
}
func main() {
cliConf := new(ClientConfig)
cliConf.createClient("xx.xx.xx.xx", 22, "root", "xxxxxx")
//本地文件上传到服务器
cliConf.Upload(`D:\go\haha.go`, `/root/haha.go`) // /root/haha.go
//从服务器中下载文件
cliConf.Download(`/root/1.py`, `D:\go\1.py`) //文件下载完毕
}
golang使用sftp连接服务器远程上传、下载文件的更多相关文章
- ubuntu SSH 连接、远程上传下载文件
安装 SSH(Secure Shell) 服务以提供远程管理服务 sudo apt-get install ssh SSH 远程登入 Ubuntu 机 ssh username@192.168.0.1 ...
- 【ARM-LInux开发】利用scp 远程上传下载文件/文件夹
利用scp 远程上传下载文件/文件夹 scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o s ...
- python中使用paramiko模块并实现远程连接服务器执行上传下载
paramiko模块 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系 ...
- 利用scp 远程上传下载文件/文件夹和ssh远程执行命令
利用scp传输文件 1.从服务器下载文件scp username@servername:/path/filename /tmp/local_destination例如scp codinglog@192 ...
- linux利用scp远程上传下载文件/文件夹
scp是secure copy的简写,用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的.可能会稍微影响一下速度. 当你服务 ...
- Mac iTerm2使用rz、sz从远程上传下载文件
使用 brew install lrzsz .如果安装遇到错误的话,使用以下方法: 在mac终端下运行: brew install lrzsz (安装教程:http://brew.sh/index_z ...
- 利用scp 远程上传下载文件/文件夹
scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port ...
- 使用scp命令,远程上传下载文件/文件夹
1.从服务器下载文件 scp username@servername:/path/filename /local/path例如: scp ubuntu@117.50.20.56:/ygf/data/d ...
- paramiko远程连接linux服务器进行上传下载文件
花了不少时间来研究paramiko中sftpclient的文件传输,一顿操作猛如虎,最后就一直卡在了路径报错问题,疯狂查阅资料借鉴大佬们的心得,还是搞不好,睡了个午觉醒来,仔细一看原来是指定路径的文件 ...
随机推荐
- iOS-ASI异步下载图片
异步下载图片 异步下载图片ASIHTTPRequest *requestX = [ASIHTTPRequest requestWithURL:url]; self.re ...
- angular入门 - 环境安装及项目创建
1.安装node.js 下载,安装,在终端测试安装是否成功:node -v(查看nodejs版本) npm -v(查看npm版本) 下载地址:https://nodejs.org/en/downloa ...
- vue警告: component lists rendered with v-for should have explicit keys
warning信息:component lists rendered with v-for should have explicit keys. See https://vuejs.org/guide ...
- Node中导入模块require和import??
转自:https://blog.csdn.net/wxl1555/article/details/80852326 S6标准发布后,module成为标准,标准的使用是以export指令导出接口,以im ...
- C#基础知识学习 linq 和拉姆表达式一
两个方法对比 第二种方法 对比学习 拉姆表达 linq 用法
- springboot集成elk 一: springboot + Elasticsearch
1.ELK介绍 1> Elasticsearch是实时全文搜索和分析引擎, 提供搜集.分析.存储数据三大功能: 是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统. ...
- MySQL忘记密码解决
1.设置管理员root密码为123 开启MySQL服务后 PS C:\WINDOWS\system32> mysqladmin -uroot -p password "123" ...
- Python print函数详解
1 """ 2 print(...) 3 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=Fals ...
- gdb调试命令总结
常用命令: l 列出源代码 每次默认列10行 list 行号 列出从第几行开始的源代码 list函数名 列出某个函数的源代码 r 运行程序 next(或n) 执行下一行语句 ...
- 1,electron搭建
electron可以用js来创建丰富的桌面应用 一个electron应用的目录结构 your-app/ ├── package.json ├── main.js └── index.html 1,安装 ...