为什么Python调用带重定向的sshfs命令会出现重定向语法错误?
问题原因
- 你在xfce4-terminal中使用的是bash、zsh这类支持
<<<Here String特殊重定向语法的shell,而Python的os.system接口默认调用的是/bin/sh,绝大多数Linux发行版的/bin/sh默认关联为dash,dash并不支持<<<语法,因此会抛出重定向语法错误。 - 另外
os.system属于老旧的进程调用接口,对进程输入输出的控制能力很弱,本身也不推荐用于复杂的命令调用场景。
解决方法
方案1:显式指定用bash执行命令
将原命令包装为bash的执行参数,适配<<<语法要求:
import os os.system("bash -c \"sshfs -o password_stdin user@example.ddnss.de:/remote/path ~/example_local_path/ <<< 'password'\"")
方案2:使用官方推荐的subprocess模块传递输入(更安全)
subprocess是Python官方推荐的进程调用接口,不需要依赖shell的特殊重定向语法,可以直接把密码传递给进程的标准输入,既避免了shell兼容性问题,也降低了命令注入风险:
import os import subprocess cmd = [ "sshfs", "-o", "password_stdin", "user@example.ddnss.de:/remote/path", os.path.expanduser("~/example_local_path/") ] subprocess.run(cmd, input=b"password\n", check=True)
注意:不启用shell模式的情况下
~不会被自动解析为用户家目录,需要手动调用os.path.expanduser处理路径。
方案3:改用SSH密钥认证(长期使用最优)
避免在脚本中硬编码明文密码,安全性更高,也不需要额外处理密码输入逻辑:
- 本地执行
ssh-keygen生成SSH密钥对,默认保存到~/.ssh/id_rsa - 执行
ssh-copy-id user@example.ddnss.de将公钥上传到远端服务器 - 后续调用sshfs无需输入密码,Python代码可以简化为:
import os import subprocess subprocess.run([ "sshfs", "user@example.ddnss.de:/remote/path", os.path.expanduser("~/example_local_path/") ], check=True)
内容的提问来源于stack exchange,提问作者TheoremOnTheRocks
相关产品推荐
相关产品推荐

