簡體   English   中英

SSH中的Python多個命令

[英]Python multiple commands in SSH

我正在嘗試使用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()

請幫忙。 一個工作的命令集將不勝感激。

謝謝

抱歉,我沒有可以測試的目標,但是如果用三重引號而不是單引號構造字符串,您會發現它容易得多-這將減少所需的轉義並幫助您發現問題。 我也考慮再次使用“” .join([])構造字符串以提高可讀性。

我想為ssh python模塊使用東西(喜歡paramiko,pexpect ...),我的建議是使用pexpect作為示例代碼Python:如何使用Paramiko 從Python到我的本地PC到remoteA到remoteb到remotec,Pxssh- 獲取嘗試登錄到遠程服務器時密碼被拒絕錯誤

除此之外,您應該使用subprocess os.popen而不是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
    ])

您可以輕松地使用它來補償SSH連接另一端的Shell動作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM