SSH Bulk Login and execute the command Python implementation code _python

Source: Internet
Author: User
Tags stdin ssh server lenovo
LAN has more than 100 computers, all are Linux operating systems, all computer configuration is the same, the system is exactly the same (including user name and password), the IP address is automatically allocated. One task now is to execute certain commands on these computers, saying that some operations, such as installing some software, copying some files, and shutting down the machine in batches. If a set of manual to operate, time-consuming and laborious, if you want to do a number of operations is even more trouble.
Perhaps you will think of the network with the same biography, the network is what? is to install the computer on a computer, configure well, and then use some software, such as "Lenovo Network with the same" to copy the system as is, in the installation system is very useful, as long as in a computer upload good, the same pass after all the computers are installed operating system, very convenient. The same transmission requires all computer hardware exactly the same, in Lenovo's computer-mounted system uploaded to the founder of the computer will certainly be problematic. Transmission system is also very time-consuming, according to the size of the hard disk, if the 30G hard drive, more than 100 computers to pass about 2 hours, anyway, than a platform to install faster! But if the system has been passed, found that forgot to install a software, or need to do some minor changes, and then pass once, but too slow, two times a half-day time is gone. At this point we can use SSH to control each computer to execute certain commands.
Let us recall the SSH remote login process: First to execute the command SSH username@192.168.1.x, the first time the system will prompt us to continue to connect, we want to enter "Yes", and then wait a period of time after the system prompts us to enter the password, After you have entered 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-computer interactions, one for ' yes ' and the other for the password. It is because there are two interactions that we cannot simply use certain commands to accomplish our task. We can think of 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 the automatic interactive logon and execution of commands using Pexpect:
Copy Code code as follows:

#!/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 he provides automatic interactive function, so we can achieve FTP,TELNET,SSH,SCP, such as automatic login, or more practical. The code above believes that the reader already knows how to do it (Python is that simple!). )。
Use the above code to complete the task is still relatively time-consuming, because the program to wait for automatic interaction, and Ubuntu with SSH connection is relatively slow, to conduct a series of verification, so as to reflect the security of SSH. We should improve the efficiency and finish in the shortest time. I later discovered the Paramiko module inside Python, which is simpler to use for SSH logins. Look at the following code:
Copy Code code as follows:

#-*-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 tricky:
1. The use of multiple threads, at the same time to send a login request, while to connect the computer, so much faster, I tried, if not more than a thread, directly one by one next to execute, about 5-10 seconds to a computer operation, the specific time to be based on the order to decide, If the software installation or uninstall time is longer. This way down how to also ten or twenty minutes, with more than a few threads faster, all the execution of the command completed in less than 2 minutes!
2. It is best to log in with the root user, because when installing or uninstalling the software, if the user will be prompted to enter the password, so that another interaction, deal with more trouble! When installing software apt-get install XXX preferably with "-y" parameters, because sometimes when installing or removing software prompts whether to continue to install or uninstall, this is another automatic interaction! With that parameter, there is no human-computer interaction.
3. Loop all IP, because the IP of the computer is automatically assigned to the router, insurance, preferably all the implementation, to ensure that there is no missing host
4. If there is interaction at the remote Execution command, you can use Stdin.write ("Y") to complete the interaction, "Y" is the input "Y".
5. Put all the commands in a list and iterate through the list to execute the commands in the list.
6. In order to better control, it is best to open the root user in advance on the computer, install the SSH server and let it run automatically.

Author: cnblogs ma6174
Related Article

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.