nested escape chars in a shell command

Eli Criffield elicriffield at gmail.com
Tue Oct 18 16:09:19 EDT 2005


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 "ssh.py 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




More information about the Python-list mailing list