1

I'm using pexpect to connect with ssh to a distance host. when the user or password are incorrect, I get an error but when the dest host is not reachable (for example when I entered an invalid ip or if the host is down) I don't get any indication. any idea why and what I should change in the command in order to get an indication in such case.

The source and dest machines are linux

this is the command I'm running

.../bin/python3 -c 'from pexpect import pxssh;import getpass;s = pxssh.pxssh();s.login("1.1.1.1", "user", "pass", auto_prompt_reset=False);s.sendline("touch /tmp/example.txt");s.prompt();'
Tal Levi
  • 363
  • 1
  • 6
  • 22

1 Answers1

0

You are not getting indication because the pxssh library dont provide feedback in your case. You would be better using the socket library to try to connect to the destination host before using pxssh

Here is how you could do it:

import socket
from pexpect import pxssh

def ssh_command(host, user, password, command):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2)
        s.connect((host, 22))
        s.close()
    except socket.error:
        print(f"Error: {host} is not reachable")
        return

    s = pxssh.pxssh()
    s.login(host, user, password, auto_prompt_reset=False)

    s.sendline(command)
    s.prompt()
    result = s.before.decode()

    s.logout()

    return result
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32