使用 Paramiko 一次创建多个 SSH 连接

发布于 2024-09-15 01:54:14 字数 466 浏览 13 评论 0原文

下面的代码通过 SSH 在一台机器上运行 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()

如何同时 grep 五台机器(这样我就不会出现重大延迟),然后将所有内容放入五个变量中并将它们全部打印出来。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

宫墨修音 2024-09-22 01:54:14

您需要将调用放入单独的线程(或进程,但这会太过分),这反过来又要求代码位于函数中(无论如何,这是一个好主意:模块顶部没有大量代码等级)。

例如:

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()

如果您有超过五个主机,我建议使用“线程池”架构和工作单元队列。但是,对于只有五个,坚持“专用线程”模型会更简单(特别是因为标准库中没有线程池,所以您需要像 threadpool...或者您自己的许多微妙的自定义代码;-)。

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;-).

孤星 2024-09-22 01:54:14

就我而言,我必须在具有一个 ip 和端口的服务器上执行命令,完成后需要对其他 ip 和不同端口执行 sftp。条件是由于端口转发,在对另一个 ip 执行 sftp 时一个连接应该处于活动状态。

两个连接都可以单独工作,但是在组合两个连接时,第二个 sftp 连接无法工作。

In my case i have to execute commands on server with one ip and port and after complete need to do sftp to other ip and different port.Condition is one connection should be live while doing sftp to another ip due to port forwarding.

Both connection are working separably but while combining both second sftp connection is not working.

梦开始←不甜 2024-09-22 01:54:14
#! /usr/bin/env python3
import sys, os, string, threading
try:
    import paramiko
    #import paramiko package
except:
    im = input("Paramiko module is missing. Do you want to install[Y/N]:")
    im = im.upper()
    if im == "Y":
        try:
            try:
                os.system("pip install paramiko")
            except:
                os.system("pip3 install paramiko")
        except:
            print("Please install paramiko package manually")
    else:
        print("Rerun and type 'y' to install")

#Running paramiko module with interactive password sending function
#this function helps to send password when sudo command is executed
def sudossh():
    host = "type host ip"
    port = 22
    username = "type username"
    password = "type password"
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port, username, password)
        ssh.get_transport()
        #In this example we will run HTTP module on server in port 80
        command = "sudo su -c 'sudo python -m SimpleHTTPServer 80'"
        print(f"Running: {command}\n")
        stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
        stdin.write("password\n")
        print("sent password\n")
        print("HTTP service is running now\n")
        stdin.flush()
        if stderr.channel.recv_exit_status() != 0:
            print(f"Error: {stderr.readlines()}")
        else:
            print(f"Output: \n{stdout.readlines()}")
        ssh.close()
    except Exception as err:
        print(str(err));
        print("Thanks for using my application");

#Running another paramiko module with interactive password sending function
def grepverification():
    host = "type host ip"
    port = 22
    username = "type username"
    password = "type password"
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port, username, password)
        ssh.get_transport()
        #Open new session and check port 80 status on server
        command = "sudo su -c 'netstat | grep 80'"
        print(f"Running: {command}\n")
        stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
        stdin.write("password\n")
        print("sent password\n")
        print("Connection is established. Check below output\n")
        stdin.flush()
        if stderr.channel.recv_exit_status() != 0:
            print(f"Error: {stderr.readlines()}")
        else:
            print(f"Output: \n{stdout.readlines()}")
        ssh.close()
    except Exception as err:
        print(str(err));
        print("Thanks for using my application");


def main():
    #Multithreading helps to run both at a same time. Useful for verification.
    # creating thread
    th1 = threading.Thread(target=sudossh)
    th2 = threading.Thread(target=grepverification)
    # starting thread 1
    th1.start()
    # starting thread 2
    th2.start()
    # wait until thread 1 is completely executed
    th1.join()
    # wait until thread 2 is completely executed
    th2.join()
    # both threads completely executed
    print("Completed!")
#you can use for loop to reduce lines but for understanding & smooth multithreading process will keep it as separate functions
#Comments are welcome. Thanks. Follow me on https://www.linkedin.com/in/dinesh-kumar-palanivelu-858441128/
#you need to change line - 23-26,36,51-54,64

if __name__=='__main__':
       main() 
        
#! /usr/bin/env python3
import sys, os, string, threading
try:
    import paramiko
    #import paramiko package
except:
    im = input("Paramiko module is missing. Do you want to install[Y/N]:")
    im = im.upper()
    if im == "Y":
        try:
            try:
                os.system("pip install paramiko")
            except:
                os.system("pip3 install paramiko")
        except:
            print("Please install paramiko package manually")
    else:
        print("Rerun and type 'y' to install")

#Running paramiko module with interactive password sending function
#this function helps to send password when sudo command is executed
def sudossh():
    host = "type host ip"
    port = 22
    username = "type username"
    password = "type password"
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port, username, password)
        ssh.get_transport()
        #In this example we will run HTTP module on server in port 80
        command = "sudo su -c 'sudo python -m SimpleHTTPServer 80'"
        print(f"Running: {command}\n")
        stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
        stdin.write("password\n")
        print("sent password\n")
        print("HTTP service is running now\n")
        stdin.flush()
        if stderr.channel.recv_exit_status() != 0:
            print(f"Error: {stderr.readlines()}")
        else:
            print(f"Output: \n{stdout.readlines()}")
        ssh.close()
    except Exception as err:
        print(str(err));
        print("Thanks for using my application");

#Running another paramiko module with interactive password sending function
def grepverification():
    host = "type host ip"
    port = 22
    username = "type username"
    password = "type password"
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, port, username, password)
        ssh.get_transport()
        #Open new session and check port 80 status on server
        command = "sudo su -c 'netstat | grep 80'"
        print(f"Running: {command}\n")
        stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
        stdin.write("password\n")
        print("sent password\n")
        print("Connection is established. Check below output\n")
        stdin.flush()
        if stderr.channel.recv_exit_status() != 0:
            print(f"Error: {stderr.readlines()}")
        else:
            print(f"Output: \n{stdout.readlines()}")
        ssh.close()
    except Exception as err:
        print(str(err));
        print("Thanks for using my application");


def main():
    #Multithreading helps to run both at a same time. Useful for verification.
    # creating thread
    th1 = threading.Thread(target=sudossh)
    th2 = threading.Thread(target=grepverification)
    # starting thread 1
    th1.start()
    # starting thread 2
    th2.start()
    # wait until thread 1 is completely executed
    th1.join()
    # wait until thread 2 is completely executed
    th2.join()
    # both threads completely executed
    print("Completed!")
#you can use for loop to reduce lines but for understanding & smooth multithreading process will keep it as separate functions
#Comments are welcome. Thanks. Follow me on https://www.linkedin.com/in/dinesh-kumar-palanivelu-858441128/
#you need to change line - 23-26,36,51-54,64

if __name__=='__main__':
       main() 
        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文