【问题标题】:Python multiple commands in SSHSSH中的Python多个命令
【发布时间】:2013-06-21 20:15:23
【问题描述】:

我正在尝试使用 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()

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

谢谢

【问题讨论】:

    标签: python shell ssh awk


    【解决方案1】:

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

    【讨论】:

    • 我试过这个 os.popen(''' ssh 127.0.0.1 'echo "" $(uname -ri) "";free | grep "Mem:" | awk '{print "" $2/1024 " MB("int($4*100/$2)"%)"}' ' ''').read()
    【解决方案2】:

    我的东西你用于 ssh python 模块(喜欢 paramiko,pexpect...)我的建议是 pexpect 使用例如代码 Python: How can remote from my local pc to remoteA to remoteb to remote c using ParamikoPython - Pxssh - Getting an password refused error when trying to login to a remote server

    【讨论】:

      【解决方案3】:

      除了你应该使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2015-06-17
        • 1970-01-01
        • 2013-11-24
        • 2016-07-08
        • 1970-01-01
        相关资源
        最近更新 更多