views:

176

answers:

2

Hello,

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 [email protected]')

    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

A: 

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.

Thomas Wouters
@Thomas Wouters -- Do you know any other way to ssh into another machine and enter tyhe password without using pexpect? Thanks
chrissygormley
I'm not sure why you think you need another way. Any which way you do it, you're going to end up in the same situation. But sure: paramiko can let you do this as well. You still end up with separate processes; that's how such things work.
Thomas Wouters
A: 

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

amadain