Python implements ssh bulk login and executes commands

  • 2020-05-12 02:52:30
  • OfStack

There are more than 100 computers in the LAN, all of which are linux operating system. All computers have the same configuration, the system is identical (including user name and password), and ip address is automatically assigned. Now there is a task on these computers to execute certain commands, said to do certain operations, such as installing some software, copying some files, bulk shutdown and so on. If one has to be manually operated, it is time-consuming and laborious, and it is more troublesome to have multiple operations.

Maybe you think about Internet co-transmission. What is Internet co-transmission? It is to install the computer on 1 computer, configuration, and then use some software, such as "lenovo network with the original copy of the system in the past, when installing the system is very useful, as long as the computer installed in 1 computer, with all the computer installed after the operating system, very convenient. The same as the requirements of all computer hardware is exactly the same, lenovo computer installed on the system to the founder computer will be a problem. Transfer system is also very time-consuming, according to the size of the hard disk, if 30G hard disk, more than 100 computers will take about 2 hours to transfer, in any case, faster than 1 1 platform installation! But if the system is finished, found that I forgot to install a software, or still need to make a small modification, the same once can be transmitted, but too slow, two half a day will be gone. At this point we can use ssh to control each computer to execute certain commands.

Let us recall one ssh remote login process: first execute commands ssh username@192.168.1.x, 1 time I log in the system will prompt whether we should continue to connect, we need to input "yes", then after a period of time prompted we enter a password, enter the password correctly after, we will be able to log on to the remote computer, and then we'll be able to execute the command. We noticed that there were two human-computer interactions, one with 'yes' and one with the password. It is because of the two interactions that we cannot simply use certain commands to complete our tasks. We can consider turning human-computer interaction into automatic interaction. python's pexpect module can help us achieve automatic interaction. The following code is a function that USES pexpect to automatically interactively log in and execute commands:


#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
import pexpect 
 
def ssh_cmd(ip, passwd, cmd): 
  ret = -1 
  ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd)) 
  try: 
    i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5) 
    if i == 0 : 
      ssh.sendline(passwd) 
    elif i == 1: 
      ssh.sendline('yes\n') 
      ssh.expect('password: ') 
      ssh.sendline(passwd) 
    ssh.sendline(cmd) 
    r = ssh.read() 
    print r 
    ret = 0 
  except pexpect.EOF: 
    print "EOF" 
    ssh.close() 
    ret = -1 
  except pexpect.TIMEOUT: 
    print "TIMEOUT" 
    ssh.close() 
    ret = -2  
  return ret 

We can do a lot of things with pexpect module, because it provides automatic interaction function, so we can achieve the automatic login of ftp, telnet, ssh, scp, etc., which is quite practical. Trust that the reader already knows how to do it, based on the code above (python is that simple!). .

It still takes time to complete the task with the above code, because the program has to wait for automatic interaction. In addition, the ubuntu connection with ssh is slow, and it needs to be verified by series 1, so as to demonstrate the security of ssh. We should improve efficiency and finish it in the shortest time. Then I found the paramiko module in python, which made it easier to log in to ssh. Look at the following code:


#-*- coding: utf-8 -*- 
#!/usr/bin/python  
import paramiko 
import threading 
def ssh2(ip,username,passwd,cmd): 
  try: 
    ssh = paramiko.SSHClient() 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    ssh.connect(ip,22,username,passwd,timeout=5) 
    for m in cmd: 
      stdin, stdout, stderr = ssh.exec_command(m) 
#      stdin.write("Y")  # Simple interaction, input   ' Y'  
      out = stdout.readlines() 
      # The screen output  
      for o in out: 
        print o, 
    print '%s\tOK\n'%(ip) 
    ssh.close() 
  except : 
    print '%s\tError\n'%(ip) 
if __name__=='__main__': 
  cmd = ['cal','echo hello!']# List of commands you want to execute  
  username = "" # The user name  
  passwd = ""  # password  
  threads = []  # multithreading  
  print "Begin......" 
  for i in range(1,254): 
    ip = '192.168.1.'+str(i) 
    a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))  
    a.start() 

The above program has some tricks:

Using multithreading, and send the login request, to connect the computer at the same time, such speed a lot, I tried 1, if it's not a multi-threaded, 1 1 next to perform directly, it is about 5 ~ 10 seconds to finish on 1 computer operation, to determine the specific time according to the command, if is a software to install or uninstall time longer 1. This down how also want 1210 minutes, with multithreading after much faster, all the command execution finished with less than 2 minutes! It is better to log in with root users, because when installing or uninstalling the software, normal users will be prompted to enter the password, so there is one more interaction, which will be more difficult to deal with! When installing the software, it is better to add the parameter "-y", because sometimes when installing or deleting the software, it will prompt whether to continue to install or uninstall. This is another automatic interaction! You add that parameter and there's no human-computer interaction. Loop through all the ip, because the ip of the computer is automatically assigned by the router. To be on the safe side, it is best to execute all of them to ensure that there are no missing hosts If there is interaction during remote command execution, the interaction can be completed by stdin.write ("Y"). "Y" means "Y". Put all the commands in one list, and walk through the list to execute the commands in turn For better control, it is best to open the root user on the computer in advance, install the ssh server and let it boot automatically.

I hope this article is helpful to you, Python implementation ssh batch login and execute the command content to give you the introduction here. We hope you continue to pay attention to our website! Stay tuned to learn about Python.


Related articles: