How to connect to the FTP server using Python's standard ftplib library.
import socket
from ftplib import FTP
# --- Configuration variables ---
# Use your platform's specific credentials and server details here. If you are unsure about credentials contact customer care.
FTP_SERVER = 'ftp.kvikymart.com'
FTP_PORT = 21
FTP_USERNAME = 'your username'
FTP_PASSWORD = 'your password'
LOCAL_FILE_NAME = 'localfile.txt'
REMOTE_FILE_NAME = 'remotefile.txt'
# --- FTP Connection and Transfer ---
# 1. Initialize FTP object
ftp = FTP()
ftp.set_debuglevel(2)
# 2. Connect to the server
ftp.connect(FTP_SERVER, FTP_PORT)
# 3. Log in with credentials
ftp.login(user=FTP_USERNAME, passwd=FTP_PASSWORD)
ftp.af = socket.AF_INET6 # force EPSV
ftp.set_pasv(True) # enable passive mode
# 4. Navigate to the desired remote directory
ftp.cwd('/')
# 5. Open the local file and upload it in binary mode
with open(LOCAL_FILE_NAME, 'rb') as f:
ftp.storbinary(f'STOR {REMOTE_FILE_NAME}', f)
# 6. Close the connection
ftp.quit()
Successful response will look like this:
*get* '220 FTP server ready.\n'
*resp* '220 FTP server ready.'
*cmd* 'USER your username'
*put* 'USER your username\r\n'
*get* '331 Password required for your username\n'
*resp* '331 Password required for your username'
*cmd* 'PASS ********************'
*put* 'PASS ********************\r\n'
*get* '230 User your username logged in\n'
*resp* '230 User your username logged in'
*cmd* 'CWD /'
*put* 'CWD /\r\n'
*get* '250 CWD command successful\n'
*resp* '250 CWD command successful'
*cmd* 'TYPE I'
*put* 'TYPE I\r\n'
*get* '200 Type set to I\n'
*resp* '200 Type set to I'
*cmd* 'EPSV'
*put* 'EPSV\r\n'
*get* '229 Extended Passive Mode Entered (|||data_port|)\n'
*resp* '229 Extended Passive Mode Entered (|||data_port|)'
*cmd* 'STOR remotefile.txt'
*put* 'STOR remotefile.txt\r\n'
*get* '150 Opening BINARY mode data connection for remotefile.txt\n'
*resp* '150 Opening BINARY mode data connection for remotefile.txt'
*get* '226 Transfer complete\n'
*resp* '226 Transfer complete'
*cmd* 'QUIT'
*put* 'QUIT\r\n'
*get* '221 Goodbye.\n'
*resp* '221 Goodbye.'