vishnu vishnu - 8 days ago 6
Python Question

passing python variable in echo command

I am new to python as well as shell. I am trying to send this command, (parse "Varying sentence") to a server.

('echo "(parse \\"trees are tall\\")" |nc localhost xxxxx')


I tried the following:

ssh_client = paramiko.SSHClient()
ssh_client.connect('server', username='wefw', password='fwf')

for line in json_text:
line = line.rstrip('\r\n')
json_content = json.loads(line)
body = ''
try:
body = json_content['id']['body']
body_encoded = body.encode('utf-8')
stdin, stdout, stderr=ssh_client.exec_command('echo "(parse \\"${body_encoded}\\"})" |nc localhost xxxxx')


The sentences vary. i cannot hard code the sentence in parse command. so i tried passing the variable "body_encoded" like this:

('echo "(parse \\"${body_encoded}\\")" |nc localhost xxxxx')


But something is wrong here. How can i pass variable, "body_encoded" that has a string value?

exec_command('echo "(parse \\"varying sentence\\")"')

Answer

You can use string interpolation:

ssh_client.exec_command('echo "(parse \\"%s\\")" |nc localhost xxxxx' % body)
Comments