Check FTP status using AppleScript

applescriptautomatorftp

I have an AppleScript Automator application that, when double-clicked, opens FTP and displays an alert confirming the same. It is working perfectly as expected. However, I am looking to make it a tad more intuitive so that it opens FTP ONLY if FTP isn't already open. If FTP is already open on my system, the app should close it.

So, basically I want to use the app as a toggle switch which opens or closes FTP depending on its prevailing status. The code I am currently using to open FTP and display the alert is as follows:

set ipaddr to IPv4 address of (get system info)
set sun to short user name of (get system info)
do shell script "sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist" with administrator privileges
tell application "Finder" to display alert "FTP Launched and ready for file-transfer" & character id 8233 & character id 8233 & "User Name: " & sun & character id 8233 & "IP address: " & ipaddr

Can anyone please point me in the right direction? Is there any system variable that can be used to retrieve the FTP status? On Terminal, I could use this:

ftp localhost

And the results would tell me if it's open or closed. But how can I let AppleScript know the same?

Additional info: Output of "ftp localhost" on Terminal

Here's the result of ftp localhost when FTP is closed:

enter image description here

And here's the result when FTP is open:

enter image description here

Here, I just hit return without any input and then it gives this:

enter image description here

Best Answer

This works as a shell test, if you replace with your target.

echo "QUIT" | telnet <host> ftp 2>&1 | grep  "Escape character is" > /dev/null

We're using hardly any complex tools, we just send a command to the server that makes it close our connection. If this works, the ftp-server is up and running. If we couldn't connect at all, this line returns 1, else it returns 0.

Digested to an AppleScript it's something like

set hostn to <host>
try
    do shell script "echo \"QUIT\" | telnet " & hostn & " ftp 2>&1 | grep  \"Escape character is\" > /dev/null"
    display dialog "Online."
on error
    display dialog "Not online."
end try