Download data from ftp server with Python

Recently, I needed to download the latest version of software from a ftp server then install it into tested machine.

#configurations.yaml


---
coccoc_dev_version: 79.0.3945.98
jenkins:
admin_password: '123456'
admin_username: admin
domain: http://10.0.12.96:8080
class YamlUtils:

def __new__(cls):

if not hasattr(cls, 'instance'):
cls.instance = super(YamlUtils, cls).__new__(cls)

return cls.instance

def read_data_from_file(self, file):
with open(file) as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)

def write_data_to_file(self, loaded, file):
with open(file, 'wb') as stream:
try:
return yaml.safe_dump(loaded, stream, default_flow_style=False
, explicit_start=True, allow_unicode=True, encoding='utf-8')
except yaml.YAMLError as exc:
print(exc)
yaml_made_utils = YamlUtils()
configuration_info = None
configuration_path = '/resources/configurations.yaml'


def get_configurations_info():
if configuration_info is None:
return yaml_made_utils.read_data_from_file(os.getcwd() + configuration_path)
else:
return configuration_info


class CocCocConfigs:
COCCOC_DEV_VERSION = get_configurations_info()['coccoc_dev_version']

@staticmethod
def update_coccoc_dev_version(coccoc_version):
data = get_configurations_info()
data['coccoc_dev_version'] = coccoc_version
return yaml_made_utils.write_data_to_file(data, os.getcwd() + configuration_path)
def download_latest_coccoc_dev_installer():
coccoc_installer_name = "standalone_coccoc_en.exe"
from ftplib import FTP
with FTP('browser3v.dev.itim.vn') as ftp:
ftp.login('anonymous', '')
ftp.cwd('corom')
folders_list = ftp.nlst()
coccoc_download_folder_list = get_list_coccoc_installer_dirs(folders_list)
latest_coccoc_download_dir = coccoc_download_folder_list[-1]
from configs.yaml_configs import CocCocConfigs
if CocCocConfigs.COCCOC_DEV_VERSION not in latest_coccoc_download_dir:
ftp.cwd(f"{latest_coccoc_download_dir}/installers")
try:
ftp.retrbinary("RETR " + coccoc_installer_name,
open(f"C:\\coccoc-dev\\{coccoc_installer_name}", 'wb').write)
except:
print(f"Error download coccoc binary for {coccoc_installer_name}")
return latest_coccoc_download_dir
else:
return "Already latest"
with FTP('browser3v.dev.itim.vn') as ftp:
ftp.login('anonymous', '')
def main():
coccoc_version = download_latest_coccoc_dev_installer()
if coccoc_version not in "Already latest":
CocCocConfigs.update_coccoc_dev_version(coccoc_version)
else:
pass


if __name__ == "__main__":
main()

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store