Python implementation code for batch logon and command execution via ssh

Source: Internet
Author: User
Tags ssh server

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: Copy codeThe Code is 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. login CT (['password: ', 'continue connecting (yes/no )? '], Timeout = 5)
If I = 0:
Ssh. sendline (passwd)
Elif I = 1:
Ssh. sendline ('yes \ n ')
Ssh. Verify CT ('password :')
Ssh. sendline (passwd)
Ssh. sendline (cmd)
R = ssh. read ()
Print r
Ret = 0
Failed t pexpect. EOF:
Print "EOF"
Ssh. close ()
Ret =-1
Failed t 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:Copy codeThe Code is 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.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.

Author: cnblogs ma6174

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.