Skip to content
Advertisement

Python + pexpect – How to establish a ssh connection?

I’ve been trying to establish an ssh connection via Python + pexpect, but I can’t send the lines that I want.

I think it’s certainly a syntax problem, but I don’t know where it is occurring.

#! /usr/bin/python # -*- encoding: utf-8 -*-
import re
import pexpect
import sys



child = pexpect.spawn ("gnome-terminal -e 'bash -c "ssh -X user@localhost; exec bash"'")
child.expect ("user@localhost"''s password.*:"'")
child.sendline ('xxyyzz')

print "OK"

The problem is that the password ‘xxyyzz’ never appears on the terminal, so I think the child.sendline doesn’t work and is a syntax problem.

Advertisement

Answer

You’re passing the input to the gnome-terminal process here. That won’t work, because it’s ssh (technically, bash, but bash’s stdin is also ssh‘s) that need that input, not gnome-terminal.


Regardless, you’re probably going to have a hard time ever getting this to work reliably. You should probably consider using a Python SSH library.

Good choices include:

  • Paramiko – low level Python SSH library
  • Fabric – higher level library (that uses Paramiko under the hood)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement