SSH key pair batch authentication Python script

Source: Internet
Author: User
Tags key string python script


For key pair distribution on the management machine in the cluster


Version: Python2.7

Modules: Paramiko, multiprocessing

Note: When you get remote server key fingerprint information about the script 70 line, different operating systems may differ, if you use this script, you must test it locally .


# -*- coding:utf-8 -*-import sysreload (SYS),  sys.setdefaultencoding (' utf-8 ') import  osimport timeimport paramikoimport multiprocessing#  This script is used for key pair distribution #  needs to be used with Nmap, Therefore needs in the Linux environment #  password, different server's different password may write in this one list password = [' 19820909 ']# IP address, many writes in a list, the specific list please circulate the IP by itself _list = [' 10.10.10.139 ', ' 10.10.10.140 ']#  port, cannot have multiple ports, need to unify port = 22#  local user's home directory and user name   Keep the user who executes the script by default load_username = os.environ["user"]load_userhome = os.environ["HOME"]#   The user name of the remote server, you can specify the user name. Default and  load_username  consistent long_username = load_username#long_username =  "Zouri" Try:     #  get local public key string     keys_str = open ("%s/.ssh/id_rsa.pub"  % load_userhome). Read (). Split ("\ n") [0]except:    print  ' attempt  command: \033[1;31mssh-keygen -t rsa -p  ""  -f ~/.ssh/id_rsa \033[0m  '     sys.exit (0) def network_test (IP):    #  using  nmap   Test the connectivity of the network     sss = os.popen ("Nmap -sp %s|grep host|grep  up|awk  ' {print $3} ' " % ip)     sun = sss.read ()      if  ' Up '  in sun:        return  True    else:        return falsedef ssh _test (Ip, password):    sun = false    s =  Paramiko. Sshclient ()     s.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())     try:        #  establish SSH link         s.connect (Ip, port, long_username, password)         a, b,&nBsp;c = s.exec_command ("echo  $HOME")         long_range_ Home = b.read (). replace ("\ n",  "")         s.exec_command ("Mkdir %s/.ssh && chmod 700 %s/.ssh"  %  (Long_range_home, long _range_home))         s.exec_command ("echo %s >> % S/.ssh/authorized_keys " %  (keys_str, long_range_home)          s.exec_command ("Chmod 600 %s/.ssh/authorized_keys"  %  (long_range_home))          s.close ()         sun =  True        #  get   Key fingerprint information for a remote server   write to local          key_1 = os.popen ("ssh-keyscan -p %d %s"  %   (PORT,IP)). Read (). Split ("\ n") [0]        know_file = open (load_userhome +   "/.ssh/known_hosts", "A +")         know_file.write (key_1 +   "\ n")         know_file.close ()     except   "Authentication":         pass    finally:         return sundef ssh_run (IP):  #  execution function     sun = 1    if not network_test (IP):         print  "\033[1;31m%s\033[0m is no,maybe the  Network " % ip    else:        for i _in in password:            if ssh_ Test (ip, i_in):  &Nbsp;              print  "%s is  ok,keys has been added " % ip                 sun = 0                 break        if  sun == 1:            print  "\ 033[1;31m%s\033[0m is no,maybe the password " % ipdef sun_run (x):     #  Open Multi-threaded run  x represents the maximum number of threads to open     sun_pool = multiprocessing. Pool (processes=x)     for i in ip_list:         sun_pool.apply_async (ssh_run,  (i,))     sun_pool.close ()      sun_pool.join () if  " __main__ " == __name__:    sun_time_01 = int (Time.time ())      sun_run (    sun_time_02 = int) (Time.time ())      print  "time-consuming%s seconds"  % str (sun_time_02 - sun_time_01)



This article from "Horse Walk Day" blog, declined reprint!

SSH key pair batch authentication Python script

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.