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的文件传输,一顿操作猛如虎,最后就一直卡在了路径报错问题,疯狂查阅资料借鉴大佬们的心得,还是搞不好,睡了个午觉醒来,仔细一看原来是指定路径的文件 ...
随机推荐
- 使用redis做为MySQL的缓存-C语言编写UDF
介绍 在实际项目中,MySQL数据库服务器有时会位于另外一台主机,需要通过网络来访问数据库:即使应用程序与MySQL数据库在同一个主机中,访问MySQL也涉及到磁盘IO操作(MySQL也有一些数据预读 ...
- redis未设置idle超时时间导致连接过多
今天ELK收集日志的时候,发现收集失败,查找各方面原因,最后在redis日志里面发现报错:[2489] 02 Jun 10:43:42 # Error allocating resoures for ...
- 容器版单个jenkins实现CI/CD----带solo博客开源项目
实验架构: 192.168.0.96 gitlab 192.168.0.97 jenkins.docker-1.7 192.168.0.98 harbor.docker-1.7集群 jenkins安装 ...
- cut截取数据
参考文档 https://blog.csdn.net/caoshunxin01/article/details/79355566 [root@kube-node3 ~]# cat tab_space. ...
- jQuery BlockUI Plugin Demo 4(Element Blocking Examples)
Element Blocking Examples This page demonstrates how to block selected elements on the page rather t ...
- css mix-blend-mode 混合模式
CSS3混合模式种类 在CSS3混合模式中,目前仅有16种:normal,multiply,screen,overlay,darken,lighten,color-dodge,color-burn,h ...
- 记录一下我的git连接不上GitHub问题
1.日常操作,提交代码,报错误下: $ git clone git@github.com:hanchao5272/myreflect.git Cloning into 'myreflect'... s ...
- 怎么通过外网来访问自己在Tomcat服务器中配置的项目
目前还没有试验过 https://blog.csdn.net/qingyisuo/article/details/80086105
- 为什么 Python 中的 True 等于 1
开始的时候,需要用以下函数来做一个判断,根据返回的值来做一些后续判断处理: def is_success(param): if not param: return False return True ...
- TypeScript 迭代器(iterator)和生成器(generator)
⒈迭代器(iterator) 1.可迭代性 当一个对象实现了Symbol.iterator属性时,我们认为它是可迭代的. 一些内置的类型如 Array,Map,Set,String,Int32Arra ...