nested escape chars in a shell command

Juho Schultz juho.schultz at
Wed Oct 19 09:47:45 CEST 2005

Eli Criffield wrote:
> I'm try run an ssh command in pexpect and I'm having trouble getting
> everything escaped to do what i want.
> Here's a striped down script showing what i want to do.
> --
> #!/usr/bin/env python
> import pexpect
> import sys
> if len(sys.argv) < 3:
>         print " host command"
>         sys.exit(1)
> host = sys.argv[1]
> command = sys.argv[2]
> child = pexpect.spawn('''sh -x -c "stty -echo ; ssh -t -o
> 'StrictHostKeyChecking no' %s '%s' |awk '{print \"%s:\"$0}' "
> '''%(host,command,host), timeout=30)
> child.setlog(sys.stdout)
> child.expect(pexpect.EOF)
> --
> The problem in the pexpect.spawn line, It doesn't like the \"%s:\" part
> of the awk command. This is necessary so i can see what server the
> command is running on, In the full script the command will be running
> on about 100 servers at a time.
> It parses out into:
> + stty -echo
> + ssh -t -o 'StrictHostKeyChecking no' testserver date
> + awk '{print testserver:$0}'
> It totally strips out the "
> The stty -echo is required because part of what the program does is it
> tries to remember any passwords that are asked for, So you can run a
> command like "su -c id" and it will remember roots password for the
> next
> server and try that. -echo keeps the root password from being echoed to
> the screen.
> The second problem with the command is while "su -c id" works (taking
> out the awk part) running any command with more then one word after the
> -c in su fails, It strips out the '
> like so:
> ./sshexpect testserver "su -c 'ls -l /root'"
> + stty -echo
> + ssh -t -o 'StrictHostKeyChecking no' testserver 'su -c ls' -l /root
> su: user /root does not exist
> I have tried every combination of escaping i can think of can i can't
> get either problem solved.
> Any ideas?
> Eli

You can pass the argument list of your command to
pexpect.spawn(comm, args=['arg1','arg2'])
If the argument list is empty, pexpect tries to get the arguments
from the comm you passed to it. I guess this gives you problems.

Try using the args parameter. 
Simplest would be args=[' '] just to avoid the processing.

More information about the Python-list mailing list