Coverage for pyquickhelper/cli/ftp_cli.py: 47%
47 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Command line about transfering files.
4"""
5import os
6import glob
9def ftp_upload(files, dest, host, user, pwd, ftps=False, fLOG=print):
10 """
11 Pushes a file to a server using :epkg:`FTP` or :epkg:`SFTP`.
13 :param files: local files to move, comma separated or
14 defined with a pattern if character ``*`` is used
15 :param dest: destination folder
16 :param host: server name or ip address
17 :param user: user to log in
18 :param pwd: password for the user
19 :param ftps: use :epkg:`SFTP` or :epkg:`FTP`
20 :param fLOG: logging function
21 :return: status
23 .. cmdref::
24 :title: Upload one or several files to a FTP server
25 :cmd: -m pyquickhelper ftp_upload --help
27 Uploads a file, a list of files, files defined
28 by a pattern to a FTP server using FTP or SFTP
29 protocol.
31 The user and the password can be prefix by
32 `keyring,`. The module :epkg:`keyring` is then used
33 to retrieve the values. Example:
34 ``--user=keyring,user,site``.
35 """
36 from ..filehelper import TransferFTP
38 if isinstance(files, str):
39 files = [files]
40 new_files = []
41 for name in files:
42 if ',' in name:
43 new_files.extend(name.split(','))
44 else:
45 new_files.append(name)
46 files = new_files
47 new_files = []
48 for name in files:
49 if "*" in name:
50 new_files.extend(glob.glob(name))
51 else:
52 new_files.append(name)
53 files = new_files
55 if user.startswith("keyring,"):
56 spl = user[len("keyring,"):].split(',')
57 if len(spl) != 2:
58 raise ValueError(f"Unable to get user '{user}'.")
59 import keyring
60 user = keyring.get_password(spl[0], spl[1])
61 if user is None:
62 raise ValueError(f"No stored user for '{user}'.")
64 if pwd.startswith("keyring,"):
65 spl = pwd[len("keyring,"):].split(',')
66 if len(spl) != 2:
67 raise ValueError(f"Unable to get user '{pwd}'.")
68 import keyring
69 pwd = keyring.get_password(spl[0], spl[1])
70 if pwd is None:
71 raise ValueError(f"No stored user for '{pwd}'.")
73 ftps = 'SFTP' if ftps in ('1', 'True', 'true', 1, True) else 'FTP'
74 ftp = TransferFTP(host, user, pwd, ftps=ftps, fLOG=fLOG)
76 for file in files:
77 if not os.path.exists(file):
78 raise FileNotFoundError(f"Unable to find '{file}'.")
79 if fLOG:
80 fLOG(f"[ftp_upload] transfer '{file}'")
81 r = ftp.transfer(file, dest, file.split('/')[-1])
82 try:
83 ftp.close()
84 except Exception as e:
85 fLOG(f"[ftp_upload] closing failed due to {e}.")
86 return r