0

how to perform

echo xyz | ssh [host]

(send xyz to host) with python?

I have tried pexpect

pexpect.spawn('echo xyz | ssh [host]')

but it's performing

echo 'xyz | ssh [host]'

maybe other package will be better?

1
  • Check out paramiko if you want to do SSH with Python. Commented Dec 23, 2014 at 21:56

2 Answers 2

2

http://pexpect.sourceforge.net/pexpect.html#spawn

Gives an example of running a command with a pipe :

shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)

Previous incorrect attempt deleted to make sure no-one is confused by it.

Sign up to request clarification or add additional context in comments.

1 Comment

@user4815162342 - I have now edited my answer, and deleted my comments refering to it - care to do the same ?
0

You don't need pexpect to simulate a simple shell pipeline. The simplest way to emulate the pipeline is the os.system function:

os.system("echo xyz | ssh [host]")

A more Pythonic approach is to use the subprocess module:

p = subprocess.Popen(["ssh", "host"],
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("xyz\n")
output = p.communicate()[0]

2 Comments

pexpect is a lot more powerful though if you need to parse the output, and look for things like prompts, errors, etc, but to run a simple subprocess you are right, pexpect is overload.
@TonySuffolk66 Agreed. My answer is based on the assumption that the OP needs to port the simple shell pipeline echo xyz | ssh [host] to Python. The question doesn't make it clear if this is indeed the case, or if the OP needs pexpect for more involved stuff, such as typing in a passphrase and communicating in both directions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.