溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Python之paramiko模塊和threading實(shí)現(xiàn)多線程登錄多臺(tái)Linux服務(wù)器

發(fā)布時(shí)間:2020-06-17 06:05:07 來源:網(wǎng)絡(luò) 閱讀:8519 作者:藍(lán)色_風(fēng)暴 欄目:建站服務(wù)器

        有時(shí)候我們需要在多臺(tái)Linux服務(wù)器上面執(zhí)行同樣的命令,或者同樣的操作,如果我們每一臺(tái)單獨(dú)登錄上去做這樣太麻煩了,所以我們可以考慮使用自動(dòng)化腳本來實(shí)現(xiàn)。我這里使用Python多線程的方式,這樣速度更快,如果使用Shell只能一臺(tái)完了執(zhí)行另外一臺(tái)效率不高。

        針對這樣的需要寫了一個(gè)Python腳本來完成這樣的工作,大致實(shí)現(xiàn)了我需要的效果


實(shí)現(xiàn)代碼:

#!/usr/bin/python
#*-*coding:utf8*-*

"""
此腳本適用于批量登錄到Linux操作系統(tǒng),并執(zhí)行一些簡單命令
要求所有服務(wù)器的用戶名密碼一樣,或者密鑰一樣,都能使用同一種方法登錄
執(zhí)行的命令默認(rèn)只輸入第一行,如果要輸出多行需要修改ssh_login函數(shù)
默認(rèn)腳本是以用戶名密碼登錄,也可以改為用密鑰登錄
選項(xiàng)特殊說明:
-c:后面跟要執(zhí)行命令,命令如w,uptime,hostname,date等,如果命令中有空格,需要用雙引號(hào),如"cat /etc/hosts"
-a:后面跟主機(jī),有三種寫法192.168.1.31指單臺(tái)主機(jī),192.168.1.31,192.168.132,指定多臺(tái)主機(jī),把逗號(hào)換成“-”指定區(qū)間

如果有很多主機(jī),但用戶名密碼不一樣,登錄方法也不一樣,可以考慮把這些信息寫入到一個(gè)文件,
通過對文件遍歷來完成復(fù)雜環(huán)境的需求
"""

import paramiko
from optparse import OptionParser
import sys
import netaddr
import threading

#使用選項(xiàng)幫助信息可以使用中文
reload(sys)
sys.setdefaultencoding("utf-8")

#定義選項(xiàng)
usage = sys.argv[0] + " [選項(xiàng)]"
parser = OptionParser(usage)
parser.add_option('-c', '--commond',
                  dest='commond',
                  action='store',
                  default=False,
                  help='你要執(zhí)行的命令,如:uptime')
parser.add_option('-a', '--host',
                  dest='host',
                  action='store',
                  default=False,
                  help='需要執(zhí)行命令的主機(jī),跟主機(jī)IP地址,多個(gè)IP用逗號(hào)分隔,也可以用“-”連接一個(gè)主機(jī)范圍')
options, args = parser.parse_args()

def ssh_login(ip, commond):
    "登錄并執(zhí)行命令,可以更改為使用密鑰登錄"
    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("請指定要執(zhí)行的命令")
        exit(1)
    if not options.host:
        print("請指定主機(jī)")
        exit(1)

    if ',' in options.host:
        ip = options.host.split(',')
        for i in ip:
            t = threading.Thread(target=ssh_login, args=(i, options.commond))   #使用線程方式執(zhí)行,更快
            t.start()
    elif '-' in options.host:
        startip = options.host.split('-')[0]
        endip = options.host.split('-')[1]
        ip = list(netaddr.IPRange(startip, endip))        #netaddr.IPRange()用于計(jì)算IP地址區(qū)間內(nèi)的所有IP
        for i in ip:
            t = threading.Thread(target=ssh_login, args=(str(i), options.commond))
            t.start()
    else:
        ip = options.host
        ssh_login(ip, options.commond)


執(zhí)行方式及結(jié)果如下:

使用Python之paramiko模塊和threading實(shí)現(xiàn)多線程登錄多臺(tái)Linux服務(wù)器


.

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI