Python implementation code for SSH bulk login and command execution

  • 2020-04-02 09:41:09
  • OfStack

There are more than 100 computers in the LAN, all of which are Linux operating system, all of which have the same configuration, the same system (including username and password), and the 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 certain software, copying certain files, bulk shutdown and so on. If one has to be manually operated, it is time-consuming and laborious, and if there are more than one operation, it is more troublesome.
Maybe you think about Internet co-transmission. What is Internet co-transmission? It is on a computer to install the computer, configuration, and then use some software, such as "lenovo network with the original copy of the system in the past, in the system is very useful, as long as installed in a computer, with all the computers installed after the operating system, very convenient. With the requirements of all the computer hardware is exactly the same, the system installed on the lenovo computer to the founder computer is bound to have problems. Transfer system is also very time-consuming, according to the size of the hard disk, if the 30G hard disk, more than 100 computers about 2 hours more than the installation of a platform faster! But if the system is finished, found that you forgot to install a software, or also need to make small changes, the same transmission can be again, but too slow, two half a day will be lost. At this point we can use SSH to control each computer to execute certain commands.
Let's recall the SSH remote login process: first, execute the command SSH username@192.168.1.x, for the first 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, such as system hint we enter a password, enter the password correctly after we will be able to log on to the remote computer, and then we will be able to execute the command. We noticed that there were two human-computer interactions, one in which we typed 'yes' and the other in which we typed the password. Just because there are two interactions we can't simply use some command to complete our task. We can consider turning human-computer interaction into automatic interaction, which python's pexpect module can help us achieve. The following code is a function that USES pexpect to implement automatic interactive login 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('yesn') 
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 automatic login FTP, Telnet, SSH, SCP, etc., or more practical. Based on the above code, I believe that the reader already knows how to implement it (python is that simple!). .
Using the above code to complete the task is still relatively time-consuming, because the program has to wait for automatic interaction to appear, in addition, ubuntu SSH connection is relatively slow, a series of verification, so as to reflect the security of SSH. We should improve efficiency and finish it in the shortest time. Later I discovered the paramiko module in python, which was easier to SSH in. 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 '%stOKn'%(ip) 
ssh.close() 
except : 
print '%stErrorn'%(ip) 
if __name__=='__main__': 
cmd = ['cal','echo hello!']# List of commands 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 is a bit tricky:
1. The use of multithreading, login requests at the same time, to connect the computer at the same time, such speed a lot, I tried it on, if it's not a multi-threaded, one next to perform directly, it is about 5 ~ 10 seconds to finish for a computer operation, to determine the specific time according to the command, if is a software to install or uninstall time longer. So how to also want a minute and twenty minutes, with multi-threading after much faster, all the command execution finished with less than two minutes!
2. It is better to log in with the root user, because when installing or uninstalling the software, if the ordinary user will prompt for the password, so there is another interaction, it is more difficult to deal with! It is best to add "-y" parameter to apt-get install XXX when installing the software, because sometimes when installing or deleting the software, it will prompt whether to continue to install or uninstall, which is another automatic interaction! With that parameter there's no human interaction.
3. Loop all IP, because the IP of the computer is automatically assigned by the router, to be sure, it is best to execute all, to ensure that there is no missing host
4. If there is interaction during remote command execution, stdin.write("Y") can be used to complete the interaction. "Y" is the input "Y".
5. Put all the commands in a list, and walk through the list to execute the commands in turn
6. For better control, it is better to open the root user on the computer in advance, install the SSH server and let it boot automatically.

By cnblogs ma6174

Related articles: