简体   繁体   English

如何将本地变量传递给远程echo命令?

[英]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. 但是我得到[u'\\ n']作为输出。

I have also tried echo \\$line, echo "$line". 我也试过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: 请注意安全问题( 感谢@Tripleee ),在Python 3中使用shlex.quote可以提高代码的健壮性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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