Python uses the paramiko module to execute ssh commands in batches.

Source: Internet
Author: User
This article mainly explains how to use the paramiko module to execute ssh commands in batches in python. it has some reference value. interested friends can refer to multiple devices to execute ssh commands in batches. Currently, it is serial, multi-thread parallel implementation will be added later, and the source code will be directly added

Note that you cannot execute top or other dynamic commands.

#! /Usr/bin/env python #-*-coding: UTF-8-*-_ author _ = 'babyun' _ version _ = '1. 0.0 'import paramiko class SSh (object): def _ init _ (self, port, username, password): self. port = port self. username = username self. password = password def ssh_con (self, host, ip, cmd): ssh = paramiko. SSHClient () ssh. set_missing_host_key_policy (paramiko. autoAddPolicy () ssh. connect (ip, self. port, self. username, self. password) stdin, stdout, stderr = ssh.exe c_command (cmd) res, err = stdout. read (), stderr. read () result = res if res else err print ('\ 033 [31; 1 m % s \ 033 [0m' % (host, ip )) print ('\ 033 [32; 1 m % s \ 033 [0m' % result. decode () ssh. close () if _ name _ = '_ main _': client = {'host1': '1. 1.1.1 ', 'host2': '2. 2.2.2 ', 'host3': '3. 3.3.3 ', 'host4': '4. 4.4.4 ',} # host list, hostname: ip port = 22 # port number username = 'root' # username password = '000000' # password cmd = "ip route show match 1.1.1.1 | head-1" ssh = SSh (port, username, password) for I in client: host, ip = I, client [I] try: ssh. ssh_con (host, ip, cmd) handle T WindowsError: print ('\ 033 [31; 1 m % s \ 033 [0m \ n' % (host, ip, 'connection attempt failed') failed t Exception as e: print (e)

The above is a detailed description of how python uses the paramiko module to execute ssh commands in batches. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.