The code below runs grep in one machine through SSH and prints the results:
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()
How can I grep five machines all at once (so that I don't have major delay), than put all that in five variables and print them all out.
Yes it is possible, it is the default behavior. You can rely on it if you are using an updated version of SSH and it is no longer set to Protocol 1.
To do that, go to Hosts -> Add Host(s) or Cluster(s) from the main menu. Enter the IP address of the remote host. Type Yes and press Enter to add the remote hosts ssh keys to your local system. Finally, enter the password.
The default is 10. Specifies the maximum number of concurrent unauthenticated connections to the SSH daemon... The default is 10.
SSH client & key policies class paramiko.client. SSHClient. A high-level representation of a session with an SSH server. This class wraps Transport , Channel , and SFTPClient to take care of most aspects of authenticating and opening channels.
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level).
For example:
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()
If you had many more than five hosts, I would recommend using instead a "thread pool" architecture and a queue of work units. But, for just five, it's simpler to stick to the "dedicated thread" model (especially since there is no thread pool in the standard library, so you'd need a third party package like threadpool... or a lot of subtle custom code of your own of course;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With