You cannot not-execute a command and then react on the return value of the executed command (because this is what you really want to do: check if you can run sftp
successful, and if so do a "proper" run; but you'll never know whether it can run successfull without running it).
So the main question is, what it is what you actually want to test.
If you want to test whether you can do a full sftp
connection (with all the handshaking and what not), you could try running sftp
in batch-mode (which is handily non-interactive).
E.g. the following runs an sftp
session, only to terminate it immediately with a bye
command:
if echo bye | sftp -b - -oPort=23 user@server ; then
echo "sftp succeeded"
fi
This will only succeed if the entire sftp
session works (that is: you pass any key checks; you can authenticate, ...).
If the server asks you for a password, it will fail to authenticate (being non-interactive), and you won't enter the then
body.
If you only want to check whether something is listening on port 23
, you can use netcat
for this:
if netcat -z server 23; then
echo "port:32 is open"
fi
This will succeed whenever it can successfully bind to port 23 on the server. It doesn't care whether there's an sftp
daemon running, or (more likely) a telnet
daemon.
You could also do some minimal test whether the remote server looks like an SSH/SFTP server: ssh
servers usually greet you with a string indicating that they indeed speak ssh: something like "SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.4".
With this information you can then run:
if echo QUIT | netcat server 23 | grep SSH; then
echo "found an ssh server"
fi