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:
- #!/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
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:
- #-*-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.exe c_command (m)
- # Stdin. write ("Y") # simple interaction, input 'y'
- Out = stdout. readlines ()
- # Screen output
- For o in out:
- Print o,
- Print '% s \ tOK \ n' % (ip)
- Ssh. close ()
- Except t:
- Print '% s \ tError \ n' % (ip)
- If _ name __= = '_ main __':
- Cmd = ['cal ', 'echo hello! '] # List of commands to be executed
- Username = "" # User Name
- Passwd = "" # Password
- Threads = [] # Multithreading
- Print "Begin ......"
- For I in range (1,254 ):
- Ip = '1970. 192. 1. '+ str (I)
- A = threading. Thread (target = ssh2, args = (ip, username, passwd, cmd ))
- 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.