Python implements ssh batch logon and command execution, and pythonssh executes command

Source: Internet
Author: User
Tags ssh server

Python implements ssh batch logon and command execution, and pythonssh executes command

There are more than one hundred computers in the LAN, all of which are linux operating systems. The configurations of all computers are the same, the system is the same (including the user name and password), and 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 it (python is so 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 () excep T: print '% s \ tError \ n' % (ip) if _ name __= =' _ main _ ': cmd = ['cal ', 'echo hello! '] # List of commands you want to execute username = "" # username passwd = "" # password threads = [] # multithreading print "Begin ...... "for I in range (1,254): ip = '100. 168. 1. '+ str (I) a = threading. thread (target = ssh2, args = (ip, username, passwd, cmd). start ()

The above program has some tips:

  • 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!
  • 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. This requires another interaction, which makes it more difficult to handle! 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.
  • Loop all ip addresses, because the computer's ip address is automatically allocated by the router. For the sake of security, it is best to execute all the ip addresses to ensure that no missing host is found.
  • If there is interaction when executing commands remotely, you can use stdin. write ("Y") to complete the interaction. "Y" means entering "Y ".
  • Put all the commands in a list. You can traverse the list and execute the commands in the list in sequence.
  • For better control, it is best to enable the root user in advance on the computer, install the ssh server, and enable it to run automatically upon startup.

I hope this article will be helpful to you. You can use Python to implement ssh batch logon and execute commands here. We hope you will continue to follow our website! If you want to learn Python, continue to follow this site.

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.