From f73006cb93ed14cc14015befc6b47cb4c9b8d542 Mon Sep 17 00:00:00 2001 From: cangui Date: Fri, 13 Dec 2024 19:33:06 +0100 Subject: [PATCH] remove simply -> go github repo --- go.mod | 3 +- go.sum | 2 + main.go | 2 +- simply-ssh/main.go | 269 --------------------------------------------- 4 files changed, 5 insertions(+), 271 deletions(-) delete mode 100644 simply-ssh/main.go diff --git a/go.mod b/go.mod index 7ef41b2..7f08470 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module canguidev.fr/pvnet -go 1.23.2 +go 1.23.4 require github.com/TwiN/go-choice v1.2.0 @@ -19,6 +19,7 @@ require ( ) require ( + github.com/cangui2/simplyssh v0.1.0 github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect github.com/fatih/color v1.18.0 github.com/gdamore/encoding v1.0.1 // indirect diff --git a/go.sum b/go.sum index ccbf709..a64e3b4 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,8 @@ github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/TwiN/go-choice v1.2.0 h1:hMEJ09UPLwuowHhfXpooBNsIiV7siPfanjU76buni/Y= github.com/TwiN/go-choice v1.2.0/go.mod h1:LlMvhuqgWfGSdqUN3z3sDlDpSNNjjBpve+CBIC+2Nlg= +github.com/cangui2/simplyssh v0.1.0 h1:AMNao+vSIDcc0dt/W5VoskDx0sKByo5aev7nwPm7zKM= +github.com/cangui2/simplyssh v0.1.0/go.mod h1:Cs4yhDqGfIk5JyDiNbm4kg2PGieJ9ncejQ6JIzld1uE= github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/main.go b/main.go index 24d6386..11ad4b8 100644 --- a/main.go +++ b/main.go @@ -8,7 +8,7 @@ import ( "strings" "time" "canguidev.fr/pvnet/function" - simplyssh "canguidev.fr/pvnet/simply-ssh" + "github.com/cangui2/simplyssh" "github.com/TwiN/go-choice" "github.com/joho/godotenv" "github.com/pkg/sftp" diff --git a/simply-ssh/main.go b/simply-ssh/main.go deleted file mode 100644 index 243d7a4..0000000 --- a/simply-ssh/main.go +++ /dev/null @@ -1,269 +0,0 @@ -package simplyssh - -import ( - "bytes" - "fmt" - "io" - "log" - "os" - "path/filepath" - "strings" - "time" - - "github.com/pkg/sftp" - "golang.org/x/crypto/ssh" -) - -type hostConnection struct { - Id uint - Host string - HostName string - Port string - User string -} -func GetHost(path string) []hostConnection { - fileData, err := os.ReadFile(path) - if err != nil { - fmt.Println("Error reading file:", err) - return nil - } - - allHosts := []hostConnection{} - - word := []byte{} - breakLine := "\n" - //chargement initiale de lobject - var currentHost hostConnection - var i int=0 - for _, data := range fileData { - if !bytes.Equal([]byte{data}, []byte(breakLine)) { - word = append(word, data) - } else { - line := strings.TrimSpace(string(word)) - if strings.HasPrefix(line, "Host ") { - // Si un nouveau Host est trouvé, ajouter l'ancien à la liste - if currentHost.Host != "" { - allHosts = append(allHosts, currentHost) - } - // Initialiser un nouveau hostConnection - currentHost = hostConnection{} - currentHost.Id=uint(i) - parts := strings.Fields(line) - if len(parts) > 1 { - currentHost.Host = parts[1] - } - } else if strings.HasPrefix(line, "HostName ") { - parts := strings.Fields(line) - if len(parts) > 1 { - currentHost.HostName = parts[1] - } - } else if strings.HasPrefix(line, "Port ") { - parts := strings.Fields(line) - if len(parts) > 1 { - currentHost.Port = parts[1] - } - } else if strings.HasPrefix(line, "User ") { - parts := strings.Fields(line) - if len(parts) > 1 { - currentHost.User = parts[1] - i++ - } - } - word = word[:0] - } - - } - - // Ajouter le dernier host traité - if currentHost.Host != "" { - allHosts = append(allHosts, currentHost) - } - - return allHosts -} - -func Connect(pathKey, hostName, port, user string) *ssh.Client { - fmt.Println(pathKey) - - sshConfig := sshConfig(user, pathKey) - connection, err := ssh.Dial("tcp", hostName+":"+port, sshConfig) - if err != nil { - log.Fatal("Failed to dial: %s", err) - return nil - } - fmt.Println("Connection ok ") - - return connection -} - -func sshConfig(usernamme, path string) *ssh.ClientConfig { - sshConfig := &ssh.ClientConfig{ - User: usernamme, - Auth: []ssh.AuthMethod{ - PublicKeyFile(path), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), // Insecure, use for testing only - - - - } - return sshConfig - -} -func PublicKeyFile(file string) ssh.AuthMethod { - fmt.Println(file) - - buffer, err := os.ReadFile(file) - if err != nil { - fmt.Errorf("Failed to buffer: %s", err) - - return nil - } - - key, err := ssh.ParsePrivateKey(buffer) - if err != nil { - fmt.Errorf("Failed to key: %s", err) - - return nil - } - return ssh.PublicKeys(key) -} -type ProgressReader struct { - reader io.Reader - totalSize int64 - bytesRead int64 - lastUpdate time.Time -} - -func NewProgressReader(r io.Reader, totalSize int64) *ProgressReader { - return &ProgressReader{ - reader: r, - totalSize: totalSize, - } -} - -func (pr *ProgressReader) Read(p []byte) (int, error) { - n, err := pr.reader.Read(p) - pr.bytesRead += int64(n) - - // Mettre à jour la progression toutes les 500 ms par exemple - now := time.Now() - if now.Sub(pr.lastUpdate) > 500*time.Millisecond || err == io.EOF { - pr.lastUpdate = now - if pr.totalSize > 0 { - percent := float64(pr.bytesRead) / float64(pr.totalSize) * 100 - fmt.Printf("\r%.2f%% téléchargé...", percent) - } else { - // Si on ne connaît pas la taille, on ne peut afficher que les octets - fmt.Printf("\r%v bytes téléchargés...", pr.bytesRead) - } - } - - return n, err -} - -func DownloadDirectory(sftpClient *sftp.Client, remoteDir, localDir string) error { - entries, err := sftpClient.ReadDir(remoteDir) - if err != nil { - return err - } - - // Crée le répertoire local s’il n’existe pas - os.MkdirAll(localDir, 0755) - - for _, entry := range entries { - remotePath := remoteDir + "/" + entry.Name() - localPath := localDir + "/" + entry.Name() - - if entry.IsDir() { - // Téléchargement récursif - err = DownloadDirectory(sftpClient, remotePath, localPath) - if err != nil { - return err - } - } else { - // Téléchargement de fichier - remoteFile, err := sftpClient.Open(remotePath) - if err != nil { - return err - } - defer remoteFile.Close() - - localFile, err := os.Create(localPath) - if err != nil { - return err - } - defer localFile.Close() - - // Récupère la taille du fichier distant - info, err := remoteFile.Stat() - if err != nil { - return err - } - - totalSize := info.Size() - - // Crée un ProgressReader qui va afficher la progression - progressReader := NewProgressReader(remoteFile, totalSize) - - _, err = io.Copy(localFile, progressReader) - if err != nil { - return err - } - fmt.Println("\nTéléchargement terminé:", localPath) - } - } - return nil -} -func DownloadFile(sftpClient *sftp.Client, remoteFilePath, localFilePath string) error { - // Ouvrir le fichier distant - remoteFile, err := sftpClient.Open(remoteFilePath) - if err != nil { - return err - } - defer remoteFile.Close() - - // Créer le répertoire local si nécessaire - localDir := filepath.Dir(localFilePath) - if err := os.MkdirAll(localDir, 0755); err != nil { - return err - } - - // Créer le fichier local ou ecrase le dossier - localFile, err := os.Create(localFilePath) - if err != nil { - return err - } - defer localFile.Close() - - // Récupère la taille du fichier distant - info, err := remoteFile.Stat() - if err != nil { - return err - } - totalSize := info.Size() - - // Crée un ProgressReader qui va afficher la progression - progressReader := NewProgressReader(remoteFile, totalSize) - - // Copie du fichier avec affichage de la progression - _, err = io.Copy(localFile, progressReader) - if err != nil { - return err - } - - fmt.Println("\nTéléchargement terminé:", localFilePath) - return nil -} -func ExecuteCommand(command string,session *ssh.Session){ - // initialisation du buffer pour recupere les infos reçu de l' hôte - var b bytes.Buffer - session.Stdout = &b - if err := session.Run(command); err != nil { - fmt.Println(b) - log.Fatal("Failed cmd: ", err) - - } - fmt.Println(b) - -} \ No newline at end of file