Search code examples
pythonexpect

Python executing expect command unmatching quotes issue: python -c 'os.system("expect -c ...")'


python -c 'import os; os.system("/usr/bin/expect -c \'spawn ssh root@localhost; expect \"password:\" { send \"root\r\"}; interact\'")'

I am getting unmatched quotes issue (> prompt) when I execute the above command in the CLI

But executing it in a python script rather running in the command line works. Also, the expect script syntax is correct.

How to balance/level the quotes in such scenarios? I would like to understand the trick. Any online validation check tool available as like regular expression parser checking online?


Solution

  • First, in shell (I'm using Bash), write a correct expect -c "...":

    [STEP 101] # expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof"
    spawn ssh foo@localhost date
    foo@localhost's password:
    Wed 13 Jan 2021 10:26:53 AM CST
    [STEP 102] #
    

    (Here I use double quotes only so it'll be easier to put in single quotes for following python -c '...'.)

    Then, write a python -c 'print(...)' which would output the previous expect -c:

    [STEP 103] # python -c 'print("""expect -c "spawn ssh foo@localhost date; expect \\"assword:\\" { send \\"foobar\\r\\"}; expect eof" """)'
    expect -c "spawn ssh foo@localhost date; expect \"assword:\" { send \"foobar\r\"}; expect eof"
    [STEP 104] #
    

    Then, replace the print with os.system:

    [STEP 105] # python -c 'import os; os.system("""expect -c "spawn ssh foo@localhost date; expect \\"assword:\\" { send \\"foobar\\r\\"}; expect eof" """)'
    spawn ssh foo@localhost date
    foo@localhost's password:
    Wed 13 Jan 2021 10:27:33 AM CST
    [STEP 106] #