Python implements ssh batch logon and executes commands

Source: Internet
Author: User
Tags ssh server

There are more than one hundred computers in the LAN, all of which are linux operating systems. All computers have the same configuration and the system has the same username and password. IP addresses are automatically allocated. Now there is a task to execute some commands on these computers, such as installing some software, copying some files, and shutting down in batches. If you have to perform one operation manually, it is time-consuming and laborious. If you want to perform multiple operations, it will be more troublesome.

Maybe you will think of network simultaneous transmission. What is network simultaneous transmission? It is to install and configure the computer on a computer, and then use some software, such as "Lenovo Network Co-transmission", to copy the system as it is, which is useful when installing the system, you only need to install the OS on a computer. Simultaneous transmission requires that all computer hardware be identical, and the system installed on Lenovo's computer will certainly fail to be uploaded to founder's computer. The transfer system is also very time-consuming. According to the hard disk size, if the 30 GB hard disk, more than 100 computers will have to be transferred for more than two hours, which is faster than a single platform installation! However, if the system is complete and you forget to install a software package, or you still need to make some minor modifications. You can upload the package again, but it is too slow. It will take less than two or a half-day uploads. At this time, we can use ssh to control each computer to execute some commands.

Let us recall the ssh remote login process: first run the command ssh username@192.168.1.x, the First Login will prompt us whether to continue the connection, we want to enter "yes ", after a while, the system prompts us to enter the password. after entering the password correctly, we can log on to the remote computer and then execute the command. We noticed that there were two man-machine interactions, one being "yes" and the other being "password. Because there are two interactions, we cannot simply use some commands to complete our tasks. We can consider turning human-computer interaction into automatic interaction. The python pexpect module can help us achieve automatic interaction. The following code uses pexpect to implement automatic interactive logon and execute commands:

 
 
  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3.  
  4. import pexpect  
  5.  
  6. def ssh_cmd(ip, passwd, cmd):  
  7.     ret = -1 
  8.     ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))  
  9.     try:  
  10.         i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)  
  11.         if i == 0 :  
  12.             ssh.sendline(passwd)  
  13.         elif i == 1:  
  14.             ssh.sendline('yes\n')  
  15.             ssh.expect('password: ')  
  16.             ssh.sendline(passwd)  
  17.         ssh.sendline(cmd)  
  18.         r = ssh.read()  
  19.         print r  
  20.         ret = 0 
  21.     except pexpect.EOF:  
  22.         print "EOF" 
  23.         ssh.close()  
  24.         ret = -1 
  25.     except pexpect.TIMEOUT:  
  26.         print "TIMEOUT" 
  27.         ssh.close()  
  28.         ret = -2   
  29.     return ret 

Using the pexpect module, we can do a lot of things. Because of its automatic interaction function, we can achieve ftp, telnet, ssh, scp and other automatic logon functions, which is more practical. Based on the above code, I believe that the reader already knows how to implement python is that simple !).

Using the above Code to complete the task is still time-consuming, because the program has to wait for automatic interaction to appear, in addition, ubuntu ssh connection is slow and requires a series of verification, in this way, the security of ssh is reflected. We need to improve efficiency and complete it in the shortest time. Later, I found the paramiko module in python, which makes ssh Login easier. See the following code:

 
 
  1. #-*-Coding: UTF-8 -*-
  2. #! /Usr/bin/python
  3. Import paramiko
  4. Import threading
  5. Def ssh2 (ip, username, passwd, cmd ):
  6. Try:
  7. Ssh = paramiko. SSHClient ()
  8. Ssh. set_missing_host_key_policy (paramiko. AutoAddPolicy ())
  9. Ssh. connect (ip, 22, username, passwd, timeout = 5)
  10. For m in cmd:
  11. Stdin, stdout, stderr = ssh.exe c_command (m)
  12. # Stdin. write ("Y") # simple interaction, input 'y'
  13. Out = stdout. readlines ()
  14. # Screen output
  15. For o in out:
  16. Print o,
  17. Print '% s \ tOK \ n' % (ip)
  18. Ssh. close ()
  19. Except t:
  20. Print '% s \ tError \ n' % (ip)
  21. If _ name __= = '_ main __':
  22. Cmd = ['cal ', 'echo hello! '] # List of commands to be executed
  23. Username = "" # User Name
  24. Passwd = "" # Password
  25. Threads = [] # Multithreading
  26. Print "Begin ......"
  27. For I in range (1,254 ):
  28. Ip = '1970. 192. 1. '+ str (I)
  29. A = threading. Thread (target = ssh2, args = (ip, username, passwd, cmd ))
  30. A. start ()

The above program has some tips:

1. using multithreading and sending login requests at the same time to connect to the computer, this is much faster. I tried it. If multithreading is not required, it will be executed one by one, about 5 ~ It takes 10 seconds to complete the operation on a computer. The specific time depends on the command. If the software is installed or uninstalled for a longer time. In this case, it would take 10 or 20 minutes. It would be much faster to use multiple threads. It would take less than 2 minutes to execute all the commands!

2. It is best to log on with the root user, because when installing or uninstalling the software, if you use a common user, you will be prompted to enter the password, so that an additional interaction will make the process more troublesome! When installing the software, you 'd better add the "-y" parameter to apt-get install xxx, because sometimes you are prompted to continue to install or uninstall the software when installing or deleting the software. This is an automatic interaction! After that parameter is added, there will be no human-machine interaction.

3. loop through all ip addresses, because the computer's ip address is automatically allocated by the router. For the sake of insurance, it is best to execute all the ip addresses to ensure that no missing host is found.

4. If there is interaction during remote command execution, you can use stdin. write ("Y") to complete the interaction. "Y" means entering "Y ".

5. Put all the commands in a list. You can traverse the list and execute the commands in the list in sequence.

6. For better control, it is best to enable the root user on the computer in advance, install the ssh server, and enable it to run automatically upon startup.

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.