pythonlinuxpexpectpxssh

How to escape a Linux command which has all characters like single quote, double quote(',",`) in python?


I have the following Linux command which gives metrics like CPU%, RAM%, and Hard disk percentage.

echo "CPU `LC_ALL=C top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}'`% RAM `free -m | awk '/Mem:/ { printf("%3.1f%%", $3/$2*100) }'` HDD `df -h / | awk '/\// {print $(NF-1)}'`"

I want to store it in a variable as a string. But I'm not able to store due to the usage of `,",' in the Linux command. How can i make it work?

Note: I'm storing this as a string in a variable because I want to check metrics like CPU%, RAM%, and Hard disk percentage by doing ssh to a server and executing the above command with the help of pexpect/pxssh library in python.


Solution

  • Triple-quoted raw strings are perfect for this purpose

    cmd = r'''
    echo "CPU `LC_ALL=C top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}'`% RAM `free -m | awk '/Mem:/ { printf("%3.1f%%", $3/$2*100) }'` HDD `df -h / | awk '/\// {print $(NF-1)}'`"
    '''