0

I'm trying to create a new dir via SSH with a python script. When i try my commands by using the Python command line it just works. But when I try to do the same by a script it does not create the new 'test' folder (I even copy/paste the commands in the script into the Python cmd to verify they are right and there they work). So any ideas why it does not work by script?

The used code:

child = pexpect.spawn('ssh 192.168.56.101 -oStrictHostKeyChecking=no')
child.expect=('password:')
child.sendline('MyPwd')
child.sendline('mkdir /home/myUser/Desktop/test')
Nicholas
  • 1,189
  • 4
  • 20
  • 40

2 Answers2

1

Seems to work when I just add another line

for example

child.sendline('\n')

so the entire script is

child = pexpect.spawn('ssh 192.168.56.101 -oStrictHostKeyChecking=no')
child.expect=('password:')
child.sendline('MyPwd')
child.sendline('mkdir /home/myUser/Desktop/test')
child.sendline('\n')
Nicholas
  • 1,189
  • 4
  • 20
  • 40
  • other than you can use for pxssh module, this extends pexpect.spawn to specialize setting up SSH connections.child.sendline() it is takecare of new line. – Reegan Miranda Apr 22 '13 at 12:32
  • thanks for your response. I'm running a command right now which takes a while to process and the output is stored in an external file. The problem now is that when i throw new child.sendline() it immediately takes that one and interrupts the previous command. Is there a way to tell it to wait/sleep before using the next sendline() command or do I need the pxssh module for that? – Nicholas Apr 22 '13 at 14:10
  • ok you use for child.prompt(None) and send command child.sendline("ls") – Reegan Miranda Apr 23 '13 at 05:30
0

What I usually do to solve this issue is sync-ing with host machine. After I send something to the machine, I expect an answer, which usually translates in the machine's prompt. So, in your case, I would go for something like this:

child = pexpect.spawn('ssh 192.168.56.101 -oStrictHostKeyChecking=no')
child.expect('password:')
child.sendline('MyPwd')
child.expect('YourPromptHere')
child.sendline('mkdir /home/myUser/Desktop/test')
child.expect('YourPromptHere')

You can just replace YourPromptHere with the prompt of the machine, if you are running the script on a single target, or with a regular expression (eg. "(\$ )|(# )|(> )").

tl;dr : To summarize what I said, you need to wait until the previous action was finished until sending a new one.

Catalin Luta
  • 711
  • 4
  • 8