Python利用paramiko實現ssh登陸服務器三次密碼驗證-1

Python利用paramiko實現ssh登陸服務器三次密碼驗證-1

2018年11月19日 14:27:25 閱讀數 684

一、paramiko模塊安裝

   Python實現ssh登陸需要使用paramiko模塊,完整安裝paramiko主要需要安裝3個模塊,分別是:ecdsa、paramiko、pycrypto。
安裝過程這裏就不詳細說了,可以參考
安裝paramiko模塊填坑過程記錄

解釋兩點:
1.本次只是使用ssh驗證用戶名、密碼方式登陸,所以只需安裝paramiko模塊,ecdsa、pycrypto可以不安裝。
2.windows全部安裝paramiko需要,Visual Studio 2015(或者更新的版本),空間要求4G+好大好麻煩,而本例中不需要安裝。

二、paramiko模塊使用

   Paramiko是用python語言寫的一個模塊,遠程連接到Linux服務器,查看上面的日誌狀態,批量配置遠程服務器,文件上傳,文件下載等。
定義調用參數:

host = "120.24.239.214"
port = 22
timeout = 30
user = "root"
password = "******"
  •  

登陸服務器並執行命令:

# -*- coding:utf-8 -*-
import paramiko

def sftp_exec_command(command):
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(host, 22, user, password)
        std_in, std_out, std_err = ssh_client.exec_command(command)
        for line in std_out:
            print line.strip("\n")
        ssh_client.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_exec_command("ls -l")
  •  

上傳文件:

# -*- coding:utf-8 -*-
import paramiko

def sftp_upload_file(server_path, local_path):
    try:
        t = paramiko.Transport((host, 22))
        t.connect(username=user, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.put(local_path, server_path)
        t.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_upload_file("/root/bug.txt", "D:/bug.txt")
  •  

下載文件:

# -*- coding:utf-8 -*-
import paramiko

def sftp_down_file(server_path, local_path):
    try:
        t = paramiko.Transport((host, 22))
        t.connect(username=user, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.get(server_path, local_path)
        t.close()
    except Exception, e:
        print e

if __name__ == '__main__':
    sftp_down_file("/root/test.txt", "D:/text.txt")
  •  

詳細paramiko模塊使用參考
python模塊之 paramiko
可實現基於密碼,證書等登陸方式。

三、登陸遠程服務器,執行巡檢

   輸入用戶名,密碼登陸遠程服務器,執行巡檢,輸入密碼三次錯誤則報錯執行下一主機登陸。

   執行巡檢腳本爲shell腳本,在server.txt中寫入巡檢內容。結果輸出至d:\xunjian目錄(需提前建立),文件爲 主機名_日期.log格式。

#-*- coding:utf-8 -*-
import paramiko
import datetime
import os
##讀取當前路徑
base_dir=os.getcwd()
##命令開始執行時間
starttime=datetime.datetime.now()
print(" -------------------------------------------------------------")
print("|                                                             |")
print("  startime:        ",starttime)
print("|                                                             |")
print(" -------------------------------------------------------------")

##定義三次登陸

def ssh2(ip, username, cmd):
    for n in range(3) :
        try:
            passwd = input('請輸入主機(%s)   %s用戶密碼:' % (ip, username))
            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.exec_command(m)
#               out = stdout.readlines()
#              return out
            stdin, stdout, stderr = ssh.exec_command(cmd)
            out = stdout.read()
            return out
            break
        except Exception as e:
            if n < 2:
                print('%s\tError\t%s' % (ip, e))
                print('輸入密碼錯誤請重新輸入!')
            else:
                out = bytes('\033[0;31m主機登陸失敗,繼續下一主機\033[0m', encoding='utf-8')
                return out

def linux_check(servertable, iptable):

##注意路徑前面的r,否則有些文件會當作轉義字符處理
##讀取命令腳本
    cmd_filepath=base_dir+r"\server.txt"
    cmd_file=open(cmd_filepath,"r")
    cmd=cmd_file.read()
##讀取IP地址列表
    ip_filepath=base_dir+r"\ip.txt"
    ip_file=open(ip_filepath,'r')
    while 1:
        ipinfo=ip_file.readline()
        if not ipinfo :
            break
        else :
    ##讀取IP,用戶名,密碼
            infos = ipinfo.split(',')
            hostname= infos[0]
            hostip = infos[1]
            username = infos[2].strip('\n')
            today = datetime.date.today().strftime('%Y%m%d')
            filename = hostname + '_' + today
            f = open('d:\\xunjian\\%s.log' % (filename), 'w')

            print(" -------------------------------------------------------------")
            print("|                                                             |")
            print("                      ",hostname,hostip)
            print("|                                                             |")
            print(" -------------------------------------------------------------")
            a = ssh2(hostip, username, cmd)
            print(a.decode())
            f.writelines(a.decode())
            endtime = datetime.datetime.now()
            f.writelines('check complete.................%s...............' % (endtime))
            f.close()



if __name__ == '__main__':
    a=linux_check()

##命令執行完成時間
endtime=datetime.datetime.now()
print(" -------------------------------------------------------------")
print("|                                                             |")
print("    endtime:      ",endtime)
print("|                                                             |")
print(" -------------------------------------------------------------")
print(" -------------------------------------------------------------")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章