pythonshellsshpexpect

Python - check for specific shell prompt on a remote server


Is there a way, using Python, to check for a specific command prompt on a remote Unix server. I need to be able to SSH to a series of remote Unix servers, check that I receive a "INPUT NAME:" prompt, and log off. I don't need to enter anything at the prompt, just make sure that one is received. I haven't a clue how to go about it, and every combination of search terms I've tried just gives me how to get input from a user(which I already know how to do). The pseudocode I have looks like this:

Iterate through server list
SSH log in to Unix server
Did you get an "INPUT NAME:" prompt after login?
     True: Mark Server good
     False: Mark Server bad
Close connection
Next server

To clarify, the "INPUT NAME:" prompt is part of a proprietary shell that users with a certain group get assigned upon login, as opposed to something like bash or ksh. What I will be doing is creating an ID with this group as a test ID for this purpose.


Solution

  • Here is a suggestion: Use pexpect.pxssh. To get started, create a Python virtualenv using venv or other tools. Then install pexpect:

    pip install pexpect
    

    Here is a sample code which connects to a single server. You can add a loop so it will work with multiple servers:

    import pexpect.pxssh
    
    # Start a ssh session
    server_name = "ubuntu"
    user_name = "root"
    ssh = pexpect.pxssh.pxssh(encoding="utf-8")
    ssh.login(server=server_name, username=user_name)
    
    # Check for the prompt
    # The .before attribute holds text before the next interaction
    print(f"{ssh.before=}")
    is_good = "INPUT NAME:" in ssh.before
    print(f"{is_good=}")
    ssh.logout()
    

    Here is a sample output:

    ssh.before=" unset PROMPT_COMMAND\r\n\x1b]0;root@localhost: ~\x07root@localhost:~# PS1='[PEXPECT]\\$ '\r\n"
    is_good=False
    

    Notes