Multi-threaded login to multiple Linux servers using Python's Paramiko module and threading

Source: Internet
Author: User
Tags python script

Sometimes we need to execute the same command on more than one Linux server, or the same thing, and if each of us is doing this in a separate sign-up, we can consider using an automated script. I'm using Python in a multi-threaded way, which is faster, and if using the shell can only be done with one run, the other is inefficient.

Write a Python script for this kind of need to do this work, basically achieve the effect I need


Implementation code:

#!/usr/bin/python#*-*coding:utf8*-* "" "This script is intended for bulk logons to the Linux operating system, and performs some simple commands that require all servers to have the same user name password, or as a key, can use the same method to log on the execution of the command by default only enter the first row, if you want to output more than one line needs to modify the Ssh_login function default script is logged in with the user name password, you can change the key login option Special Description:-C: followed by the command to execute, such as W,uptime,hostname , date, and so on, if there are spaces in the command, you need to use double quotation marks, such as "Cat /etc/hosts"-a: behind with the host, there are three ways 192.168.1.31 refers to a single host, 192.168.1.31,192.168.132, specify more than one host, Change the comma to "-" Specify the interval if there are many hosts, but the user name password is not the same, the login method is not the same, you can consider writing this information to a file, through the file traversal to complete the requirements of complex environment "" "import paramikofrom  optparse import optionparserimport sysimport netaddrimport threading# Use the option Help information to use the Chinese reload (SYS) sys.setdefaultencoding ("Utf-8") #定义选项usage  = sys.argv[0] +  "  [option] "Parser = optionparser (usage) parser.add_option ('-C ',  '--commond ',                   dest= ' Commond ',                   action= ' Store ',         &Nbsp;         default=false,                   help= ' You want to execute the command, such as: Uptime ') parser.add_ Option ('-a ',  '--host ',                   dest= ' Host ',                   action= ' Store ',                   default=False,                   help= ' requires the host to execute the command, with the host IP address, multiple IPs separated by commas, can also be used "-" Connect a host range ") Options, args = parser.parse_args () Def ssh_login (Ip, commond):      "Log in and execute the command, you can change to log on using the key"     ssh = paramiko. Sshclient ()     ssh.set_missing_hoSt_key_policy (Paramiko. Autoaddpolicy ())     ssh.connect (hostname=ip, port=22, username= ' root ',  password= ' p-0p-0p-0 ')     stdin, stdout, stderr = ssh.exec_command ( Commond)     print ('%s\t%s '  % (Ip, stdout.readline (). Rstrip ()))      ssh.close () if __name__ ==  ' __main__ ':    if not  Options.commond:        print ("Specify commands to execute")          exit (1)     if not options.host:         print ("Please specify Host")         exit (1)      if  ', '  in options.host:        ip =  options.host.split (', ')         for i in ip:     &nBsp;       t = threading. Thread (target=ssh_login, args= (i, options.commond))     #使用线程方式执行, Faster              t.start ()     elif  '-'  in  options.host:        startip = options.host.split ('-') [0]        endip = options.host.split ('-') [1]         ip = list (netaddr. IPRange (STARTIP, ENDIP))          #netaddr. IPRange () calculates all ip        for i in ip:  in the IP address range            t = threading. Thread (target=ssh_login, args= (str (i),  options.commond)              t.start () &NBsp;   else:        ip = options.host         ssh_login (Ip, options.commond)


The way of execution and results are as follows:

650) this.width=650; "Src=" https://s2.51cto.com/wyfs02/M02/9B/0B/wKioL1ldoqSzXwtAAAE0gkOdePs686.png-wh_500x0-wm_ 3-wmp_4-s_2328368830.png "title=" Ju5$ljq41s%tkv[m9]t (b5r.png "alt=" wkiol1ldoqszxwtaaae0gkodeps686.png-wh_50 "/ >


.

This article is from the "Blue _ Storm" blog, make sure to keep this source http://270142877.blog.51cto.com/12869137/1944923

Multi-threaded login to multiple Linux servers using Python's Paramiko module and threading

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.