一、连接服务器,采用sftp连接模式
package middlewares
import (
"fmt"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func Connect(user, password, host string, port int) (*sftp.Client, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
sshClient *ssh.Client
sftpClient *sftp.Client
err error
)
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig = &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 30 * time.Second,
}
addr = fmt.Sprintf("%s:%d", host, port)
if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return sftpClient, nil
}
二、下载文件
func SyncCiticLog(r *gin.Context) {
User := viper.GetString("ConnectUser")
Password := viper.GetString("ConnectPassword")
Port := viper.GetInt("ConnectPort")
citicIp := viper.GetString("ConnectOldIp")
const allDir = "D:\\backup\\citic"
dstDir := ""
srcDir := ""
downloglist := DownLogList{}
sftpClient, sftpErr := middlewares.Connect(User, Password, citicIp, Port)
defer sftpClient.Close()
if sftpErr != nil {
logs.Error(map[string]interface{}{"msg": sftpErr}, "未连接到服务器,请检查相关配置!")
}
if error := r.ShouldBindBodyWithJSON(&downloglist); error != nil {
logs.Error(map[string]interface{}{"msg": "绑定结构体失败"}, "请检查配置文件是否正确!")
} else {
switch downloglist.ServiceIp {
case "172.16.2.51":
srcDir = "/home/backup/zqyl-abc/new"
dstDir = "D:\\backup\\abc"
break
case "172.16.2.58":
srcDir = "/home/backup/citic/" + downloglist.ServiceIp
dstDir = filepath.Join(allDir, "中信03")
break
case "172.16.2.59":
srcDir = "/home/backup/citic/" + downloglist.ServiceIp
dstDir = filepath.Join(allDir, "中信04")
break
case "172.16.2.60":
srcDir = "/home/backup/citic/" + downloglist.ServiceIp
dstDir = filepath.Join(allDir, "中信01")
break
case "172.16.2.61":
srcDir = "/home/backup/citic/" + downloglist.ServiceIp
dstDir = filepath.Join(allDir, "中信02")
break
}
for _, citicLog := range downloglist.LogList {
fileSrcDir := srcDir + "/" + citicLog
openFile, err := sftpClient.Open(fileSrcDir)
if err != nil {
logs.Error(map[string]interface{}{"msg": "读取文件失败!"}, "请检查文件是否存在或者是否正常!")
}
error := os.MkdirAll(dstDir, 0755)
if error != nil {
logs.Error(map[string]interface{}{"msg": "创建文件失败!"}, "请检查目录是否存在!")
}
logFile, _ := os.Create(dstDir + "\\" + citicLog)
defer logFile.Close()
_, copyErr := io.Copy(logFile, openFile)
if copyErr != nil {
logs.Info(map[string]interface{}{"msg": "下载文件失败,请检查磁盘分区是否存在或者是否可写入状态!!"}, "")
}
}
r.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "下载成功!",
"path": dstDir,
})
}
}