Question

I have a very long string ssh_cmd, I get it from

cmd = """kill -9 `ps -ef|grep "udp_receiver"|grep -v "grep"|awk '{print $2}'`"""
HostName="133.33.22.1"
ssh_cmd = """ssh -t inria_spoofing@{0} 'sudo nohup bash -c "{1} > /nohup.out 2>&1 &"'""".format(HostName, cmd)

the resulted ssh_cmd is:

ssh -t kitty@133.33.22.1 'sudo nohup bash -c "kill -9 `ps -ef|grep "udp_receiver"|grep -v "grep"|awk '{print $2}'` > /nohup.out 2>&1 &"'

however, I'm afraid when I run

child = pexpect.spawn(ssh_cmd)

there is problem, so how to organize the string? thanks!

Was it helpful?

Solution

To answer the question, here's the proper ssh_cmd: ssh -t kitty@133.33.22.1 "sudo nohup bash -c \"kill -9 \\\`ps -ef | grep 'udp_receiver' | grep -v 'grep' | awk '{print \\\$2}'\\\` > /nohup.out 2>&1 &\""

Basically, you need to escape double quotes, backticks and backslashes in a command each time you embed this command in another one. I did not use single quotes except at the lower level because you cannot use escaped single quotes inside single quotes.

You do need to escape the $ too when it is just a character inside a string quoted with double quotes, even if the string does also contain single quotes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top