I'll give you a basic example that expands a bit on what Illuminatus said about try one and then the other.
# in pseudocode no less!
ping $deviceIP or report it as not responding and exit
if ssh error then
if ssh error is 'connection refused'
telnet $deviceIP or report error and exit
do work with telnet connection
report error and exit
do work with ssh connection
If you already know which devices use telnet and which use ssh then things get even simpler. Just try the correct protocol!
Update: Oops. I forgot the most important part.
You will not get any good responses until you can give us some clear information regarding your problem and code that demonstrates said problem.