SSH batch logon and command execution (Python implementation)

Source: Internet
Author: User
Tags ssh server

My life is short. I use python!

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 sectionCodeIs a function that uses pexpect to realize 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. Verify 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
Except Pexpect. EOF:
Print " EOF "
Ssh. Close ()
Ret =-1
Except Pexpect. Timeout:
Print " Timeout "
Ssh. Close ()
Ret =-2


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, becauseProgramWait for the automatic interaction to appear. In addition, UBUNTU uses SSH to connect slowly and performs a series of verification to reflect SSH security. 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 ()
Except :
Print ' % S \ terror \ n ' % (IP)

If _ Name __ = ' _ Main __ ' :
Cmd = [ ' Cal ' , ' Echo hello! ' ] # List of commands you want to execute
Username ="" # 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 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.

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: 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.