2017-04-11 122 views
0
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() 

我想将“行”内容传递给回显。但我得到 [u'\ n']作为输出。如何将本地变量传递给远程回显命令?

我也试过echo \ $行,echo“$ line”。但没有得到你好作为输出。

回答

1

远程shell无法访问您的程序变量,该命令必须在其启动之前组成。

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

注意的安全问题(感谢@Tripleee),在Python 3中使用shlex.quote来提高代码的健壮性:

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

感谢。工作! – vishnu

+1

对于包含双引号或美元符号或反引号的'line'值,它仍然不健壮,它们分别引入了shell的可变插值和命令替换。单引号可以防止后者绕过前者,但是后者的值不能包含单引号。为了完全健壮,你需要使用[如'shlex.quote()'](/ questions/35817/how-to-escape-os-system-calls-in-python)。 – tripleee

+0

非常好的一点@tripleee,谢谢;) – klashxx

相关问题