22

以下のコードは、SSH を介して 1 台のマシンで grep を実行し、結果を出力します。

import sys, os, string
import paramiko

cmd = "grep -h 'king' /opt/data/horror_20100810*"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()

print stdout.readlines()

すべてを 5 つの変数に入れてすべて出力するよりも、(大きな遅延が発生しないように) 5 台のマシンを一度に grep するにはどうすればよいでしょうか。

4

3 に答える 3

41

呼び出しを別々のスレッド (またはプロセスですが、それはやり過ぎです) に配置する必要があります。これには、コードが関数内にある必要があります (これはとにかく良い考えです: モジュールの上部に実質的なコードを持たないでください)。レベル)。

例えば:

import sys, os, string, threading
import paramiko

cmd = "grep -h 'king' /opt/data/horror_20100810*"

outlock = threading.Lock()

def workon(host):

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username='xy', password='xy')
    stdin, stdout, stderr = ssh.exec_command(cmd)
    stdin.write('xy\n')
    stdin.flush()

    with outlock:
        print stdout.readlines()

def main():
    hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc
    threads = []
    for h in hosts:
        t = threading.Thread(target=workon, args=(h,))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

main()

ホストが 5 つ以上ある場合は、代わりに「スレッド プール」アーキテクチャとワーク ユニットのキューを使用することをお勧めします。ただし、たった 5 つの場合は、「専用スレッド」モデルに固執する方が簡単です (特に、標準ライブラリにはスレッド プールがないため、threadpoolのようなサード パーティ製のパッケージが必要になるか、または多くの微妙なカスタムが必要になります)。もちろん、独自のコード;-)。

于 2010-08-14T23:03:28.830 に答える
-1

すべてをforループで実行するだけで、次の反復に進む前に stdin を閉じることを忘れないでください。つまり、行の後に行stdin.flush()を追加しますstdin.close()

于 2016-09-02T19:53:43.057 に答える