使用python通过SSH执行命令

时间:2013-07-11 10:49:53

标签: python ssh

我正在尝试使用python通过SSH执行所有多个命令。

每次,我都会遇到“意外(”错误。

请为此提供正确的语法。谢谢。

os.popen('''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>" }'\'')'" ''').read()

截至目前,我正在使用:

 data1=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' 'echo "<td>" $(uname -ri) "</td>";' ''').read().rstrip()
 data2=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' free | grep "Mem:" | awk '{print "<td>" $2/1024 " MB("int($4*100/$2)"%)</td>"}' ''').read().rstrip()
 data3=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' free | grep "Swap:" | awk '{ print "<td>" int($3*100/$2) "%" }' ''').read().rstrip()
 data4=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' cat /proc/cpuinfo | grep "processor" | wc -l ''').read().rstrip()
 data5=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' cat /proc/cpuinfo | grep "MHz" | sort -u | awk '{ print $4 }' ''').read().rstrip()
 data6=os.popen('''ssh -o BatchMode=yes -o StrictHostKeyChecking=no '''+host+''' cat /proc/cpuinfo | grep "cache size" | sort -u | awk '{ print "(" $4 " " $5 ")</td>" }' ''').read().rstrip()

1 个答案:

答案 0 :(得分:0)

我认为如果你使用合适的库来做到这一点是最好的。 就个人而言,我和paramiko一起工作过,这很简单。

选择: http://wiki.python.org/moin/SecureShell