Advertisement
Pug_coder

lab2.1_3

Sep 24th, 2021
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.98 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "github.com/jlaffaye/ftp"
  6.     "io/ioutil"
  7.     "path/filepath"
  8.     "strings"
  9.     "time"
  10. )
  11.  
  12. func getTransferParticipants(connections []*ftp.ServerConn) (*ftp.ServerConn, *ftp.ServerConn, bool) {
  13.     var indexA, indexB int
  14.     fmt.Print("Введите индекс сервера-отправителя: ")
  15.     fmt.Scan(&indexA)
  16.     fmt.Print("Введите индекс сервера-получателя: ")
  17.     fmt.Scan(&indexB)
  18.  
  19.     if indexA < 0 || indexA >= len(connections) || indexB < 0 || indexB > len(connections) {
  20.         fmt.Println("Вы указали некорректный индекс")
  21.         return nil, nil, false
  22.     }
  23.  
  24.     return connections[indexA], connections[indexB], true
  25. }
  26.  
  27. func download(connection *ftp.ServerConn) *ftp.Response {
  28.     var filePath string
  29.     fmt.Print("Введите путь до файла на сервере: ")
  30.     fmt.Scan(&filePath)
  31.  
  32.     response, err := connection.Retr(filePath)
  33.  
  34.     if err != nil {
  35.         fmt.Println("Произошла ошибка во время открытия файла на сервере:", err)
  36.         return nil
  37.     }
  38.  
  39.     return response
  40. }
  41. func readFile(c *ftp.ServerConn) {
  42.     var data string
  43.     fmt.Println("fileName: ")
  44.     fmt.Scan(&data)
  45.     r, err := c.Retr(data)
  46.     if err != nil {
  47.         fmt.Println(err)
  48.     }
  49.     defer r.Close()
  50.  
  51.     buf, err := ioutil.ReadAll(r)
  52.     println(string(buf))
  53. }
  54. func upload(response *ftp.Response, connection *ftp.ServerConn) bool {
  55.     var fileName string
  56.     fmt.Print("Введите путь до файла для сохранения на сервере: ")
  57.     fmt.Scan(&fileName)
  58.  
  59.     err := connection.MakeDir(filepath.Dir(fileName))
  60.     if err != nil {
  61.         fmt.Println("Не удалось создать нужную директорию для созранения")
  62.         return false
  63.     }
  64.  
  65.     if err = connection.Stor(fileName, response); err != nil {
  66.         fmt.Println("Произошла ошибка во время загрузки:", err)
  67.         return false
  68.     }
  69.  
  70.     return true
  71. }
  72.  
  73. func loop(connections []*ftp.ServerConn) {
  74.     defer func() {
  75.         for _, connection := range connections {
  76.             connection.Quit()
  77.         }
  78.     }()
  79.  
  80.     for {
  81.         var command string
  82.         fmt.Print("Введите комманду: ")
  83.         fmt.Scan(&command)
  84.  
  85.         switch strings.ToLower(command) {
  86.         case "transfer":
  87.             connectionA, connectionB, ok := getTransferParticipants(connections)
  88.  
  89.             if !ok {
  90.                 continue
  91.             }
  92.  
  93.             response := download(connectionA)
  94.  
  95.             if response == nil {
  96.                 continue
  97.             }
  98.  
  99.             if !upload(response, connectionB) {
  100.                 response.Close()
  101.                 continue
  102.             }
  103.  
  104.             fmt.Println("Успешный трансфер")
  105.         case "exit":
  106.             for i, connection := range connections {
  107.                 if err := connection.Quit(); err != nil {
  108.                     fmt.Println("Во время отключения от сервера", i, "произошла ошибка:", err)
  109.                 } else {
  110.                     fmt.Println("Успешное отключение от сервера", i)
  111.                 }
  112.             }
  113.             return
  114.         default:
  115.             fmt.Println("Неизвестная комманда")
  116.         }
  117.     }
  118. }
  119.  
  120. func getConnection() *ftp.ServerConn {
  121.     var url, login, password string
  122.  
  123.     fmt.Print("Введите адрес: ")
  124.     fmt.Scan(&url)
  125.     fmt.Print("Введите имя пользователя: ")
  126.     fmt.Scan(&login)
  127.     fmt.Print("Введите пароль: ")
  128.     fmt.Scan(&password)
  129.  
  130.     connection, err := ftp.Dial(url, ftp.DialWithTimeout(5 * time.Second))
  131.  
  132.     if err != nil {
  133.         fmt.Println("Ошибка подключения:", err)
  134.         return nil
  135.     }
  136.  
  137.     if err = connection.Login(login, password); err != nil {
  138.         fmt.Println("Ошибка авторизации:", err)
  139.         return nil
  140.     }
  141.  
  142.     return connection
  143. }
  144.  
  145. func main() {
  146.     var serversCount int
  147.     fmt.Print("Введите число серверов: ")
  148.     fmt.Scan(&serversCount)
  149.     var connections []*ftp.ServerConn
  150.     for i := 0; i < serversCount; i++ {
  151.         fmt.Printf("Сервер #%d\n", i)
  152.         connection := getConnection()
  153.         if connection == nil {
  154.             return
  155.         }
  156.         connections = append(connections, connection)
  157.     }
  158.  
  159.     loop(connections)
  160. }
  161.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement