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的文件传输,一顿操作猛如虎,最后就一直卡在了路径报错问题,疯狂查阅资料借鉴大佬们的心得,还是搞不好,睡了个午觉醒来,仔细一看原来是指定路径的文件 ...
随机推荐
- linux计划任务以某个用户身份执行
# Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # ...
- iOS技术面试03:Foundation
是否可以把比较耗时的操作放在NSNotificationCenter中 如果在异步线程发的通知,那么可以执行比较耗时的操作: 如果在主线程发的通知,那么就不可以执行比较耗时的操作 3.Foundati ...
- EXCEL中,在其中列 前面or后面加一个“元”字的技巧
EXCEL小技巧,我们平常需要用到一些,记录下,供有需要的人参考! 案例: EXCEL其中的一列,每个后面加一个“元”字,如果要1个1个去加,相当麻烦,其实很简单,只需要一个公式即可! 解决方法: ( ...
- 【web 安全测试思路】图形验证码对服务器的影响
前言 图片验证码是为了防止恶意破解密码.刷票.论坛灌水等才出现的,但是你有没有想过,你的图形验证码竟然可能导致服务器的崩溃? 利用过程 这里以phpcms为例,首先需要找一个图形验证码. 将图片拖动到 ...
- redis windows 扩展Redis igbinary 下载地址
http://windows.php.net/downloads/pecl/releases/redis/3.1.2/ http://windows.php.net/downloads/pecl/re ...
- vue {{}}的用法
参考链接:https://blog.csdn.net/cofecode/article/details/78666233
- Information retrieval (IR class2)
1. 解析文档一般要分析哪些方面? - 首先分析文档的格式,是docx,html,xml,pdf... - 其次分析文档的语言,是英语,汉语,日语,德语... - 使用的什么字符集,ASCII编码, ...
- [转帖]Linux Shell常用技巧(五)
Linux Shell常用技巧(五) https://zhuanlan.zhihu.com/p/73451771 1. 变量:在awk中变量无须定义即可使用,变量在赋值时即已经完成了定义.变量的类型可 ...
- 什么是HybridDB for MySQL (原PetaData)
云数据库HybridDB for MySQL (原名PetaData)是同时支持海量数据在线事务(OLTP)和在线分析(OLAP)的HTAP(Hybrid Transaction/Analytical ...
- C++实现16进制字符串转换成int整形值
开发中经常需要把16进制字符串转换成整形,写了个个代码供大家参考下: #include <stdio.h> #include <string.h> //字符转换成整形 int ...