Question

I am trying to use pexpect to ssh into a computer but I do not want to return back to the original computer. The code I have is:

#!/usr/bin/python2.6

import pexpect, os

def ssh():

    # Logs into computer through SSH
    ssh_newkey = 'Are you sure you want to continue connecting'
    # my ssh command line
    p=pexpect.spawn('ssh build@10.51.11.10')

    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
    p.sendline("password")
    i=p.expect('-bash-3.2')

    print os.getcwd()
ssh()

This allows me to ssh into the computer but when I run the os.getcwd() the pexpect has returned me to the original computer. You see I want to ssh into another computer and use their environment not drag my environment using pexpect. Can anyone suggest how to get this working or an alternative way.

Thanks

Was it helpful?

Solution

The process that launches ssh is never going to leave the computer it runs on. When you ssh into another computer, you start a new process there. That process is an entirely separate thing, a separate program to run. If you want to do anything on the remote machine, you have to either send the commands to execute over the connection, or copy over the program you want to run and execute it remotely.

OTHER TIPS

your instance to the other machine is p. p.sendline what you want on the other machine and p.expect the result. in the case outlined

p.sendline("pwd && hostname")
p.expect("-bash-3.2") # although its better to set the prompt yourself so that this can be ported to any machine
response = p.before
print "received response [[" + response + "]]"

Try that. Also try module pxssh to use ssh with python. This module uses pexpect and has all of the methods in it to do exactly what you want here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top