1

我正在尝试使用 os.popen() 通过 SSH 在 Python 中执行这 4 个命令。

问题出在 awk 命令上,尤其是它的引号。

这是我必须转换的内容:

ssh -o BatchMode=yes -o StrictHostKeyChecking=no $host 'echo "<td>" $(uname -ri) "</td>"; free | grep "Mem:" | awk '\''{ print "<td>" $2/1024 " MB (" int($4*100/$2) "%) </td>" }'\''; free | grep "Swap:" | awk '\''{ print "<td>" int($3*100/$2) "%" }'\''; echo "</td><td>" $(cat /proc/cpuinfo | grep "processor" | wc -l) "@" $(cat /proc/cpuinfo | grep "MHz" | sort -u | awk '\''{ print $4 }'\'') "Mhz" $(cat /proc/cpuinfo | grep "cache size" | sort -u | awk '\''{ print "(" $4 " " $5 ")</td>" }'\'')' 

这是我尝试过的,但在最后一个命令中出现了一些引号错误。问题似乎与 awk 引号有关。另外,我想将它们合并到一个 SSH 实例中。

os.popen("ssh 127.0.0.1 'echo \"<td>\" $(uname -ri) \"</td>\"'").read()

os.popen("ssh 127.0.0.1 free | grep \"Mem:\" | awk '{print \"<td>\" $2/1024 \" MB(\"int($4*100/$2)\"%)</td>\"}'").read()

os.popen("ssh 127.0.0.1 free | grep \"Swap:\" | awk '{ print \"<td>\" int($3*100/$2) \"%\" }'").read()

os.popen("ssh 127.0.0.1 'echo \"</td><td>\" $(cat /proc/cpuinfo | grep \"processor\" | wc -l) \"@\" $(cat /proc/cpuinfo | grep \"MHz\" | sort -u | awk '{ print $4 }') \"Mhz\" $(cat /proc/cpuinfo | grep \"cache size\" | sort -u | awk '{ print \"(\" $4 \" \" $5 \")</td>\" }')'").read()

请帮忙。一组工作命令将不胜感激。

谢谢

4

3 回答 3

0

除此之外,您应该使用subprocess而不是os.popen,在 shell 命令的上下文中,引用可以很容易地完成

def shellquote(*strs):
    r"""Input: strings, output: String enclosed with '' and every ' replaced with '\''. For use with the shell."""
    # just take everything except '; replace ' with '\''
    # ''' is seen by the shell as ''\'''\'''\'''. Ugly, but not harmful.
    return " ".join([
            "'"+st.replace("'","'\\''")+"'"
            for st in strs
    ])

您可以轻松地使用它来补偿 shell 在 SSH 连接另一端的操作。

import subprocess

def sshcall(*args):
    return subprocess.check_output(['ssh', '127.0.0.1'] + list(args))


sshcall('echo', sq("<td>") + '$(uname -ri)' + sq("</td>"))
# '<td>3.9.3-9.g0b5d8f5-desktop i386</td>\n'

sshcall('free | grep "Mem:" | awk ' + sq('{print "<td>" $2/1024 " MB(" int($4*100/$2) "%)</td>" }'))
# '<td>3017.93 MB(20%)</td>\n'

sshcall('free | grep "Swap:" | awk ' + sq('{ print "<td>" int($3*100/$2) "%" }'))
# '<td>3%\n'

最后一行我将作为您的示例。


您只需向远程系统询问数据并自己传输数据,就可以大大简化这一过程。在这种情况下,您不必担心 shell 引用,因为您在本地进行大部分转换。该连接仅用于查询原始信息:

un = sshcall('uname -ri')
fr = sshcall('free')
cpu = sshcall('cat /proc/cpuinfo')

甚至-仅使用一个连接-

un, fr, cpu = sshcall('uname -ri; echo XXXXX; free; echo XXXXX; cat /proc/cpuinfo').split("XXXXX")

您可以分析和输出数据

import re

do_re1 = lambda r, s: re.search(r, s).group(1).strip()
nums = lambda r, s: [int(x) for x in do_re1(r, s).split()]

print "<td>" + un.strip() + "</td>"

swapnums = nums("Swap:(.*)\n", fr)
memnums = nums("Mem:(.*)\n", fr)

print "<td> %f MB (%f %%) </td>" + % (memnums[0] / 1024.0, memnums[2] * 100.0 / memnums[0])
# swapnums: similiar

numcpus = len(re.findall("rocessor.*:(.*)\n", cpu))
freqs = [i.group(1).strip() for i in re.finditer("MHz.*:(.*)\n", cpu)]
cachesizes = [i.group(1).strip() for i in re.finditer("cache size.*:(.*)\n", cpu)]

# output them as you want
于 2013-06-25T08:24:34.093 回答
0

抱歉,我没有可以测试的目标,但是如果您用三引号而不是单引号构造字符串,您会发现它会容易得多 - 这将减少所需的转义并帮助您找到问题。为了可读性,我还会考虑再次使用 "".join([ ]) 构造字符串。

于 2013-06-25T06:32:16.570 回答
0

我的东西你用于 ssh python 模块(喜欢 paramiko,pexpect ...)我的建议是 pexpect 使用例如代码Python:How can remote from my local pc to remoteA to remoteb to remote c using Paramiko , Python - Pxssh - Getting an尝试登录远程服务器时出现密码被拒绝错误

于 2013-06-25T06:44:04.943 回答