在os.system的python脚本中正确使用ssh和sed

问题描述

我正在尝试使用os.system在python脚本中运行ssh命令,以使用0和{{在远程服务器中完全匹配的字符串的末尾添加ssh 1}}。

我在远程服务器上有一个名为sed文件,该文件的列表如下所示。

nodelist

我想使用sed进行以下修改,我想搜索test-node-1 test-node-2 ... test-node-11 test-node-12 test-node-13 ... test-node-21 ,当找到完全匹配项时,我想在末尾添加0,该文件必须最终看起来像这样。

test-node-1

但是,当我运行第一个命令时,

test-node-1 0
test-node-2
...
test-node-11
test-node-12
test-node-13
...
test-node-21

结果变成这样,

hostname = 'test-node-1'
function = 'nodelist'

os.system(f"ssh -i ~/.ssh/my-ssh-key username@serverlocation \"sed -i '/{hostname}/s/$/ 0/' ~/{function}.txt\"")

我尝试在命令中添加\ b,

test-node-1 0
test-node-2
...
test-node-11 0
test-node-12 0
test-node-13 0
...
test-node-21

该命令根本不起作用。

我必须手动输入节点名称,而不是像这样使用变量

os.system(f"ssh -i ~/.ssh/my-ssh-key username@serverlocation \"sed -i '/\b{hostname}\b/s/$/ 0/' ~/{function}.txt\"")

使我的命令起作用。

我的命令出了什么问题,为什么我不能做我想做的事情?

解决方法

此代码存在严重的安全问题;修复它们需要从头开始对其进行重新设计。让我们在这里做

#!/usr/bin/env python3
import os.path
import shlex  # note,quote is only here in Python 3.x; in 2.x it was in the pipes module
import subprocess
import sys

# can set these from a loop if you choose,of course
username = "whoever"
serverlocation = "whereever"
hostname = 'test-node-1'
function = 'somename'

desired_cmd = ['sed','-i',f'/\\b{hostname}\\b/s/$/ 0/',f'{function}.txt']
desired_cmd_str = ' '.join(shlex.quote(word) for word in desired_cmd)
print(f"Remote command: {desired_cmd_str}",file=sys.stderr)

# could just pass the below direct to subprocess.run,but let's log what we're doing:
ssh_cmd = ['ssh',os.path.expanduser('~/.ssh/my-ssh-key'),f"{username}@{serverlocation}",desired_cmd_str]
ssh_cmd_str = ' '.join(shlex.quote(word) for word in ssh_cmd)
print(f"Local command: {ssh_cmd_str}",file=sys.stderr)  # log equivalent shell command
subprocess.run(ssh_cmd) # but locally,run without a shell

如果运行此命令(最后的subprocess.run除外,这将需要真实的SSH密钥,主机名等),则输出如下所示:

Remote command: sed -i '/\btest-node-1\b/s/$/ 0/' somename.txt
Local command: ssh -i /home/yourname/.ssh/my-ssh-key whoever@whereever 'sed -i '"'"'/\btest-node-1\b/s/$/ 0/'"'"' somename.txt'

那是正确/期望的输出;有趣的'"'"'惯用法是,如何在符合POSIX的外壳中将单引号单引号安全地插入单引号内。


有什么不同?很多:

  • 我们正在生成要作为数组运行 的命令,并让Python进行必要时将这些数组转换为字符串的工作。这样可以避免外壳注入攻击(一种非常常见的安全漏洞)。
  • 因为我们自己生成列表,所以我们可以更改引用每个列表的方式:适当时可以使用f字符串,适当时可以使用原始字符串,等等。
  • 我们没有将~传递给远程服务器:这是多余的,也是不必要的,因为~是启动SSH会话的默认位置;并且我们正在使用的安全预防措施(以防止外壳将值解析为代码)阻止其生效(因为未完成将~替换为有效值HOMEsed本身,但通过调用它的外壳;因为我们根本不调用任何本地外壳,因此还需要使用os.path.expanduser来使{{1 }}受到尊敬)。
  • 因为我们没有使用原始字符串,所以我们需要将~中的反斜杠加倍,以确保Python将其视为文字而不是语法。
  • 至关重要的是,我们绝不会在任何可以被本地或远程shell解析为代码的上下文中传递数据