xiaowei-system/skills/devops/devops-umbrella/references/gaokao-site/python-ssh-bash-escaping-20...

2.2 KiB
Raw Blame History

Python 脚本 via SSH 的 bash 转义问题处理

2026-06-20 本session 反复踩坑

问题

sshpass ssh "python3 -c '...'" 执行复杂 Python 脚本时,多级引号和 f-string 中的 {} 会被 bash 解释,导致语法错误。

典型报错

bash: syntax error near unexpected token `('

标准解决方案

方案 A写本地文件 → scp → 远程执行(推荐)

# 1. 本地写 Python 文件
cat > /tmp/fix_cache.py << 'PYEOF'
# Python 代码,不怕引号问题
with open('/www/wwwroot/gaokao/file.py', 'r') as f:
    content = f.read()
content = content.replace(old, new)
with open('/www/wwwroot/gaokao/file.py', 'w') as f:
    f.write(content)
print('Done')
PYEOF

# 2. scp 到远程
sshpass -p 'xue.2538' scp /tmp/fix_cache.py root@192.144.179.11:/tmp/fix_cache.py

# 3. 远程执行
sshpass -p 'xue.2538' ssh root@192.144.179.11 'python3 /tmp/fix_cache.py'

方案 Bexecute_codeHermes 内置)

from hermes_tools import terminal, write_file

# 直接在本地写文件
write_file('/tmp/fix.py', content='...')

# 通过 terminal 的 scp
terminal(f'scp /tmp/fix.py root@192.144.179.11:/tmp/fix.py')

# 远程执行
terminal(f'ssh root@192.144.179.11 "python3 /tmp/fix.py"')

方案 Cbase64 编码(不推荐,写长脚本时易错)

import base64
encoded = base64.b64encode(content.encode()).decode()
terminal(f'echo "{encoded}" | base64 -d > /www/wwwroot/gaokao/file.html')

哪些情况触发转义问题

场景 触发 解决方案
f-string 含 {var} 触发 方案 A
三引号字符串 触发 方案 A
sed -i 含特殊字符 触发 方案 A 或 write_file + scp
简单 curl / grep 不触发 直接 SSH
简单的 sed不含特殊字符 不触发 sed -i 's/old/new/'
纯文字替换(无转义) 不触发 python3 -c '...'

铁律

  • 一旦 Python 脚本超过 5 行 → 用方案 A
  • 一旦字符串含 {} → 用方案 A
  • 一旦有多层引号嵌套 → 用方案 A
  • write_file + terminal scp + terminal 远程执行 是最省心的组合