Multi-device Batch SSH command, is currently serial, later will join multithreading to achieve parallel, directly on the source code
# multiple devices execute SSH commands in bulk #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = ' Babyshen ' __ 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.exec_command (CMD) res,err = stdout.read (), Stderr.read () result = res if res else err print (' \033[31;1m%s %s\033[0m ' % (HOST,IP)) print (' \033[32;1m%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 ' # user name password = ' 123456789 ' # password cmd = ' ip route show match 1.1.1.1 | head -1 " # commands to execute ssh = SSh (Port,username,password) for i in client: host , Ip = i,client[i] try: ssh.ssh_con (host,ip,cmd) except windowserror: print (' \033[31;1m%s %s %s \ 033[0m\n ' % (HOST,IP, ' connection attempt failed ')) except Exception as e: print (e)
GitHub Address: https://github.com/babyshen/Python/blob/master/batsh_ssh.py
This article is from the "Baby God" blog, make sure to keep this source http://babyshen.blog.51cto.com/8405584/1910340
Python executes SSH commands in bulk via the Paramiko module