In this section, we are going to learn about the sendcmd() function. We can use the sendcmd() function to send a simple string command to the server to get the String response. The client can send FTP commands such as STAT, PWD, RETR, and STOR. The ftplib module has multiple methods that can wrap these commands. The commands can be sent using the sendcmd() or voidcmd() methods. As an example, we are going to send a STAT command to check the status of a server.
Create a send_command.py script and write the following content in it:
from ftplib import FTP
ftp = FTP('your-ftp-domain-or-ip')
ftp.login('your-username','your-password')
ftp.cwd('/home/student/')
s_cmd_stat = ftp.sendcmd('STAT')
print(s_cmd_stat)
print()
s_cmd_pwd = ftp.sendcmd('PWD')
print(s_cmd_pwd)
print()
ftp.close()
Run the script as follows:
student@ubuntu:~/work$ python3 send_command.py
You will get the following output:
211-FTP server status:
Connected to ::ffff:192.168.2.109
Logged in as student
TYPE: ASCII
No session bandwidth limit
Session timeout in seconds is 300
Control connection is plain text
Data connections will be plain text
At session startup, client count was 1
vsFTPd 3.0.3 - secure, fast, stable
211 End of status
257 "/home/student" is the current directory
In the preceding code, we first mentioned the IP address, username, and password of the other machine. Next, we used the sendcmd() method for the STAT command to the other machine. Then, we used sendcmd() for the PWD command.