You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用SSH执行命令时变量未被正确解析问题解决

问题根因

Python不会自动解析字符串字面量内的变量名并替换为对应值。你写command='cp command_test test/attempt/trial_something'时,command_test只是字符串里的普通文本,不会被识别为你之前定义的路径变量,最终传给SSH执行的命令自然找不到正确源文件,运行失败。你打印出的命令内容已经直接印证了这点:实际执行的命令里根本没有插入/test/trial这个路径。

修正方法

根据你使用的Python版本,选以下任意一种正确的字符串插入方式即可:

  • f-string写法(Python3.6及以上版本推荐,可读性最高)
    在字符串前加f标记,需要插入变量的位置用{变量名}包裹:
command_test='/test/trial'
command = f'cp {command_test} test/attempt/trial_something'
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)

此时打印command会得到正确的命令:cp /test/trial test/attempt/trial_something,和你最初能正常运行的命令完全一致。

  • 字符串直接拼接(兼容所有Python版本)
    用+连接字符串片段和变量,注意命令各部分之间的空格不要漏:
command_test='/test/trial'
command = 'cp ' + command_test + ' test/attempt/trial_something'
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
  • format方法拼接(兼容所有Python版本)
    用字符串的format方法占位插入变量:
command_test='/test/trial'
command = 'cp {} test/attempt/trial_something'.format(command_test)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
额外提示

如果后续用到的文件路径包含空格、特殊shell字符,建议给路径包裹双引号,避免shell解析参数出错,例如f-string写法可以调整为:

command = f'cp "{command_test}" test/attempt/trial_something'

内容的提问来源于stack exchange,提问作者martinmistere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 10:15:30