go log.Fatalln(err)

log.Fatalln(err)既有退出return的意义



package main

import (
"fmt"
"github.com/pkg/sftp"
utilsssh "golang.org/x/crypto/ssh"
"gopkg.in/yaml.v3"
"io/ioutil"
"log"
"os"
"path"
"sshutil/pkg/exec"
"sshutil/pkg/ssh"
"time"
)

const Confile = "config.yaml"

type remoteFiles struct {
Name string
Size string
ModTime string
}

type Cnf struct {
SftpConfig SftpConfig `json:"sftp_config" yaml:"sftp_config"`
SshConfig SshConfig `json:"ssh_config" yaml:"ssh_config"`
}

var cnf Cnf

func connect(user, password, host string, port int) (*sftp.Client, error) {
var (
auth []utilsssh.AuthMethod
addr string
clientConfig *utilsssh.ClientConfig
sshClient *utilsssh.Client
sftpClient *sftp.Client
err error
)
// get auth method
auth = make([]utilsssh.AuthMethod, 0)
auth = append(auth, utilsssh.Password(password))
clientConfig = &utilsssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 30 * time.Second,
HostKeyCallback: utilsssh.InsecureIgnoreHostKey(), //ssh.FixedHostKey(hostKey),
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if sshClient, err = utilsssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
// create sftp client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return sftpClient, nil
}
func uploadFile(sftpClient *sftp.Client, localFilePath string, remotePath string) {
srcFile, err := os.Open(localFilePath)
if err != nil {
fmt.Println("os.Open error : ", localFilePath)
log.Fatal(err)
}
defer srcFile.Close()
var remoteFileName = path.Base(localFilePath)
dstFile, err := sftpClient.Create(path.Join(remotePath, remoteFileName))
if err != nil {
fmt.Println("sftpClient.Create error : ", path.Join(remotePath, remoteFileName))
log.Fatal(err)
}
defer dstFile.Close()
ff, err := ioutil.ReadAll(srcFile)
if err != nil {
fmt.Println("ReadAll error : ", localFilePath)
log.Fatal(err)
}
dstFile.Write(ff)
fmt.Println(localFilePath + " copy file to remote server finished!")
}
func uploadDirectory(sftpClient *sftp.Client, localPath string, remotePath string) {
localFiles, err := ioutil.ReadDir(localPath)
if err != nil {
log.Fatal("read dir list fail ", err)
}
for _, backupDir := range localFiles {
localFilePath := path.Join(localPath, backupDir.Name())
remoteFilePath := path.Join(remotePath, backupDir.Name())
if backupDir.IsDir() {
sftpClient.Mkdir(remoteFilePath)
uploadDirectory(sftpClient, localFilePath, remoteFilePath)
} else {
uploadFile(sftpClient, path.Join(localPath, backupDir.Name()), remotePath)
}
}
fmt.Println(localPath + " copy directory to remote server finished!")
}

type SftpConfig struct {
User string `json:"user" yaml:"user"`
Password string `json:"password" yaml:"password"`
Host string `json:"host" yaml:"host"`
Port int `json:"port" yaml:"port"`
LocalPath string `json:"localpath" yaml:"localpath"`
RemotePath string `json:"remotepath" yaml:"remotepath"`
}

type SshConfig struct {
User string `json:"user" yaml:"user"`
Password string `json:"password"yaml:"password"`
Host string `json:"host" yaml:"host"`
LocalPath string `json:"localpath" yaml:"localpath"`
RemotePath string `json:"remotepath" yaml:"remotepath"`
}

func Config() {
// 1. read yaml, instance config.Zap
yfile, err := os.Open(Confile)
if err != nil {
log.Fatalln("os read file errors", err)
os.Exit(1)
}
defer yfile.Close()

ydecode := yaml.NewDecoder(yfile)
if err := ydecode.Decode(&cnf); err != nil {
log.Fatalln("yaml file is err", err)
}
}

func listFiles(sc sftp.Client, remoteDir string) (theFiles []remoteFiles, err error) {

files, err := sc.ReadDir(remoteDir)
if err != nil {
return theFiles, fmt.Errorf("Unable to list remote dir: %v", err)
}

for _, f := range files {
var name, modTime, size string

name = f.Name()
modTime = f.ModTime().Format("2006-01-02 15:04:05")
size = fmt.Sprintf("%12d", f.Size())

if f.IsDir() {
name = name + "/"
modTime = ""
size = "PRE"
}

theFiles = append(theFiles, remoteFiles{
Name: name,
Size: size,
ModTime: modTime,
})
}

return theFiles, nil
}

func init() {
if len(os.Args) < 2 {
fmt.Println("plase input age > 2")
os.Exit(1)

}

}
func main() {
Config()
client, err := ssh.New(&ssh.Option{}, ssh.WithStdoutEnable(true), ssh.WithUsername(cnf.SshConfig.User), ssh.WithPassword(cnf.SshConfig.Password), ssh.WithHostKeyCallback(utilsssh.InsecureIgnoreHostKey()))
if err != nil {
log.Fatalln(err)
}
cmd, err := exec.New(client)
if err != nil {
log.Fatalln(err)
}

if err := client.Copy(cnf.SshConfig.Host, cnf.SshConfig.LocalPath, cnf.SshConfig.RemotePath); err != nil {
log.Fatalln("is a send file errors", err)

} else {
res, err4 := cmd.CmdToString("127.0.0.1", "mv /data/test/* /data/bak/", "")

defer func() {
if r := recover(); r != nil {
log.Println(err4)
fmt.Println(r)

}
}()

fmt.Println("is a Ok Send file", res)

s, err := connect(cnf.SftpConfig.User, cnf.SftpConfig.Password, cnf.SftpConfig.Host, cnf.SftpConfig.Port)
if err != nil {
log.Fatalln(err)
panic(1)
}
SftpFiles, err1 := listFiles(*s, "./files")
if err1 != nil {
log.Fatalln(err)
}
for _, v := range SftpFiles {
filename := path.Join("/home/sftpuser/files/", v.Name)
f, err2 := os.Stat(filename)
if err2 != nil {

log.Fatalln(err)
}
if !f.IsDir() {
log.Fatalln("is nil data plase first time look up")

}

}
if f, err := os.Stat(os.Args[1]); err == nil {
if !f.IsDir() {
uploadFile(s, os.Args[1], cnf.SftpConfig.RemotePath)
} else if f.IsDir() {

uploadDirectory(s, os.Args[1], cnf.SftpConfig.RemotePath)
}

}

fmt.Println("传输完成")

}
}
posted @ 2023-12-11 21:13  技术颜良  阅读(44)  评论(0编辑  收藏  举报