简体   繁体   中英

How to pass local variable to remote echo command?

import paramiko, commands
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.load_system_host_keys()
ssh_client.connect('xx.xx.x', username='abc', 
key_filename='rsa')

line ="Hello"
stdin, stdout, stderr=ssh_client.exec_command('echo $line')
print stdout.readlines()

I want to pass the "line" content to echo. But i get [u'\\n'] as output.

I have also tried echo \\$line, echo "$line". But not getting hello as output.

The remote shell can't access to your program variables, the command must be composed before its launch.

stdin, stdout, stderr = ssh_client.exec_command('echo "{0}"'.format(line))

Be aware of safety issues ( Thanks @Tripleee ), in Python 3 use shlex.quote to increase the robustness of your code:

stdin, stdout, stderr = ssh_client.exec_command('echo {}'.format(quote(line)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM