Uday Swami
Uday Swami

Reputation: 395

Execute multiple commands with pexpect

I'm using pexpect to make a ssh connection to a server. Login shell of the server is not bash. I want to execute multiple commands with one connection. I tried sendline() but it doesn't treat it as a command it just enters the text. So maybe I need a way to send "Enter" signal through pexpect. The next use case for this is to execute commands from certain directories so I first have to go there and execute the command. is there any way to do this? or is there any better way to execute multiple commands on remote server through password authentication?

Upvotes: 1

Views: 7683

Answers (1)

dbogle
dbogle

Reputation: 46

One way to get around this issue is to first start a bash and then run your commands. One thing to remember is that it is good to call child.expect after each command sent. Below is an example of how to connect to a server then run ls. Trivial yes but hopefully is helpful. For commands like 'cd' you should just be able to expect and empty string since there is not typically output

import pexpect
import sys

child = pexpect.spawn("bash")
child.logfile = sys.stdout
child.sendline("ssh user@hostname")
child.expect("Some string to match")
child.sendline("ls")
child.expect("Some directory or file")
child.sendline("cd /path/to/file/or/directory")
child.expect("")
child.sendline("ls")
child.expect("A certain filename")

When you run your ssh command you can also do something like

ssh -t user@hostname 'cd /path/to/directory'

That will take you right to a directory when your ssh connection starts

Upvotes: 3

Related Questions