fgimian / paramiko-expect

A Python expect-like extension for the Paramiko SSH library which also supports tailing logs.
MIT License
204 stars 78 forks source link

how to catch the return string and record,not just dispaly #52

Open heartbeat2015 opened 5 years ago

heartbeat2015 commented 5 years ago

from future import print_function import traceback

import paramiko from paramiko_expect import SSHClientInteraction

def main():

Set login credentials and the server prompt

HOSTNAME = '1.2.3.4'
USERNAME = 'root'
PASSWORD = '123456'
PROMPT = '.*'

# Use SSH client to login
try:
    # Create a new SSH client object
    client = paramiko.SSHClient()

    # Set SSH key parameters to auto accept unknown hosts
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # Connect to the host
    client.connect(hostname=HOSTNAME, username=USERNAME, password=PASSWORD)

    # Create a client interaction class which will interact with the host
    with SSHClientInteraction(client, timeout=10, display=True) as interact:

        interact.send('ls -l /')
        interact.expect(PROMPT, timeout=5)

        cmd_output_ls = interact.current_output_clean
        print(cmd_output_ls)

        # Send the exit command and expect EOF (a closed session)
        interact.send('exit')
        interact.expect()

except Exception:
    traceback.print_exc()
finally:
    try:
        client.close()
    except Exception:
        pass

if name == 'main': main()


I doesn't get the result in cmd_output_ls, and at the end of programm,the result will display. which api to catch them,not just display result

heartbeat2015 commented 5 years ago

after exec this line interact.expect(), all result is in current_output

fruch commented 5 years ago

can you share more details on the remote machine you are connecting to ? my guess the PS1 the is messing your PROMPT regex, try be more specific in this regex to match the prompt