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!