LAN has more than 100 computers, all Linux operating systems, all the same computer configuration, the system is identical (including user name and password), IP address is automatically assigned. Now there is a task to execute certain commands on these computers, saying something like install some software, copy some files, batch shutdown and so on. If one has to be operated manually, it is time-consuming and laborious, and it is even more troublesome to perform multiple operations.
Perhaps you will think of the network with the transmission, the network of the same transmission is what? is to install the computer on a computer, configuration, and then use some software, such as "Lenovo Network with the transmission" to the system as a copy of the past, in the installation of the system is very useful, as long as in a computer installed, the same after all the computer installed a good operating system, very convenient. The same transmission requires all computer hardware exactly the same, in Lenovo's computer system uploaded to founder computer will certainly have problems. Transmission 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, anyway, than a platform installation faster! But if the system has been passed, found that forget to install a software, or need to make some minor changes, and then pass the same time can, but too slow, pass two half a day is gone. At this point we can use SSH to control each computer to execute certain commands.
First let us recall the SSH remote login process: First execute the command SSH [email protected], the first time you log in the system will prompt us whether to continue to connect, we have to enter "Yes", and then after a period of time the system prompts us to enter the password, After you enter the password correctly, we can log on to the remote computer, and then we can execute the command. We noticed that there were two human-machine interactions, one for the input ' yes ', and another for the password. It is because there are two interactions that we cannot simply use certain commands to accomplish our task. We can consider turning human-computer interaction into automatic interaction, and Python's Pexpect module can help us achieve automatic interaction. The following code is a function that implements automatic interactive login and execution of commands with Pexpect:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Pexpect
def ssh_cmd (IP, passwd, cmd):
ret =-1
SSH = pexpect.spawn (' ssh ' [email protected]%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
With the Pexpect module we can do a lot of things, because he provides automatic interactive function, so we can achieve FTP,TELNET,SSH,SCP, such as automatic login, or more practical. Based on the code above, I believe the reader already knows how to implement it (Python is so simple!). )。
Use the above code to complete the task or to compare time, because the program to wait for automatic interaction, and Ubuntu with SSH connection is relatively slow, to perform a series of verification, so as to reflect the security of SSH. We need to improve efficiency and finish in the shortest possible time. Later I found the Paramiko module in Python, which is easier to use for SSH login. 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") #简单交互, enter ' Y '
out = Stdout.readlines ()
#屏幕输出
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! '] #你要执行的命令列表
Username = "" #用户名
passwd = "" #密码
Threads = [] #多线程
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 still a bit of a trick:
1. The use of multi-threading, at the same time to send a login request, at the same time to connect the computer, so much faster, I tried, if not multi-threading, directly one by one next to execute, about 5-10 seconds to a computer operation, the specific time according to the order to decide, If the software installation or uninstallation time is longer. This way down how to take ten or twenty minutes, with multi-threaded after a lot faster, all the command finished in less than 2 minutes!
2. It is best to log in with the root user, because when installing or uninstalling the software when the user will be prompted to enter the password, so that another interaction, processing is more troublesome! Installing the software apt-get install XXX preferably with the "-y" parameter, because sometimes when the software installation or removal prompts to continue to install or uninstall, this is another automatic interaction! With that parameter there is no human-computer interaction.
3. Loop all IP when looping, because the computer's IP is automatically assigned by the router, for insurance purposes, it is best to implement all, ensure that no missing host
4. If there is interaction at the remote execution of the command, you can use Stdin.write ("Y") to complete the interaction, and "Y" is the input "Y".
5. Put all the commands in a list and traverse the list to execute the commands in the list in turn
6. For better control, it is best to open the root user in advance on the computer, install the SSH server and let it run automatically.
Blogger ma6174 has copyright in this blog post (except reproduced) and is not permitted for commercial use without permission. Reprint please specify the source http://www.cnblogs.com/ma6174/
SSH Bulk Login and execute command (Python implementation)