利用paramiko模塊實現堡壘機+審計功能

  paramiko模塊是一個遠程鏈接服務器,全真模擬ssh2協議的python模塊,藉助paramiko源碼包中的demos目錄下:demo.py和interactive.py兩個模塊實現簡單的堡壘機+審計功能。編寫的run_demo.py腳本,能夠根據登錄堡壘機的用戶信息在數據庫查詢該用戶全部能夠登錄的服務器列表,用戶能夠根據索引選擇登錄。爲防止用戶退出腳本後不中斷shell會話,致使不安全的因素,故在用戶退出run_demo.py腳本時,會結束已經鏈接的shell會話,直接退出堡壘機。python

1、修改paramiko源碼模塊的demo.py文件。ios

1.文件路徑(具體狀況具體~~,你懂得)git

[root@CT7 demos]# pwd
/usr/share/doc/python-paramiko-1.15.1/demosredis

[root@CT7 demos]# cat demo.pyshell

2.代碼以下:數據庫

# Copyright (C) 2003-2007  Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.


import base64
from binascii import hexlify
import getpass
import os
import select
import socket
import sys
import time
import traceback
from paramiko.py3compat import input

import paramiko
try:
    import interactive
except ImportError:
    from . import interactive


def agent_auth(transport, username):
    """
    Attempt to authenticate to the given transport using any of the private
    keys available from an SSH agent.
    """

    agent = paramiko.Agent()
    agent_keys = agent.get_keys()
    if len(agent_keys) == 0:
        return

    for key in agent_keys:
        print('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))
        try:
            transport.auth_publickey(username, key)
            print('... success!')
            return
        except paramiko.SSHException:
            print('... nope.')

#--modified this part,add note.#
def manual_auth(username, hostname,pw):
    '''default_auth = 'p'
    auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
    if len(auth) == 0:
        auth = default_auth

    if auth == 'r':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
        path = input('RSA key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.RSAKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('RSA key password: ')
            key = paramiko.RSAKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    elif auth == 'd':
        default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
        path = input('DSS key [%s]: ' % default_path)
        if len(path) == 0:
            path = default_path
        try:
            key = paramiko.DSSKey.from_private_key_file(path)
        except paramiko.PasswordRequiredException:
            password = getpass.getpass('DSS key password: ')
            key = paramiko.DSSKey.from_private_key_file(path, password)
        t.auth_publickey(username, key)
    else:
        pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
        t.auth_password(username, pw)'''
    t.auth_password(username,pw)


# setup logging
paramiko.util.log_to_file('demo.log')

username = ''
if len(sys.argv) > 1:
    hostname = sys.argv[1]
    if hostname.find('@') >= 0:
        username, hostname = hostname.split('@')
else:
    hostname = input('Hostname: ')
if len(hostname) == 0:
    print('*** Hostname required.')
    sys.exit(1)
port = 22
if hostname.find(':') >= 0:
    hostname, portstr = hostname.split(':')
    port = int(portstr)

# now connect
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((hostname, port))
except Exception as e:
    print('*** Connect failed: ' + str(e))
    traceback.print_exc()
    sys.exit(1)

try:
    t = paramiko.Transport(sock)
    try:
        t.start_client()
    except paramiko.SSHException:
        print('*** SSH negotiation failed.')
        sys.exit(1)

    try:
        keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    except IOError:
        try:
            keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
        except IOError:
            print('*** Unable to open host keys file')
            keys = {}

    # check server's host key -- this is important.
    key = t.get_remote_server_key()
    if hostname not in keys:
        print('*** WARNING: Unknown host key!')
    elif key.get_name() not in keys[hostname]:
        print('*** WARNING: Unknown host key!')
    elif keys[hostname][key.get_name()] != key:
        print('*** WARNING: Host key has changed!!!')
        sys.exit(1)
    else:
        print('*** Host key OK.')

    # get username
    #--modified add note.
    '''if username == '':
        default_username = getpass.getuser()
        username = input('Username [%s]: ' % default_username)
        if len(username) == 0:
            username = default_username'''
    #--modified  by myself add 3 lines.
    username = sys.argv[2]
    password = sys.argv[3]
    ops_user = sys.argv[4]

    agent_auth(t, username)
    if not t.is_authenticated():
        manual_auth(username, hostname,password)
    if not t.is_authenticated():
        print('*** Authentication failed. :(')
        t.close()
        sys.exit(1)

    chan = t.open_session()
    chan.get_pty()
    chan.invoke_shell()
    print('*** Here we go!\n')
    #--modified below line.
    interactive.interactive_shell(chan,hostname,username,ops_user)
    chan.close()
    t.close()

except Exception as e:
    print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e))
    traceback.print_exc()
    try:
        t.close()
    except:
        pass
    sys.exit(1)
View Code

 

2、修改paramiko源碼模塊的interactive.py文件。windows

1.文件路徑(具體狀況具體~~,你懂得)安全

[root@CT7 demos]# pwd
/usr/share/doc/python-paramiko-1.15.1/demosbash

[root@CT7 demos]# cat interactive.py服務器

2.代碼以下:

# Copyright (C) 2003-2007  Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.

import time
import socket
import sys
from paramiko.py3compat import u

# windows does not have termios...
try:
    import termios
    import tty
    has_termios = True
except ImportError:
    has_termios = False

#--modified this part,add hostname,username,ops_user.
def interactive_shell(chan,hostname,username,ops_user):
    if has_termios:
        posix_shell(chan,hostname,username,ops_user)
    else:
        windows_shell(chan)

#--modified this part,add **kargs
def posix_shell(chan,hostname,username,ops_user):
    date = time.strftime('%Y-%m-%d')
    f = file('/tmp/audit_%s_%s.log' % (ops_user,date),'a+')
    record = []
    import select
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        while True:
            #--modified define datetime.
            date = time.strftime("%Y-%m-%d %H:%M:%S")
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                record.append(x) #--modified 
                chan.send(x)
            if x == '\r':
                cmd = ''.join(record).split('\r')[-2]
                #log = "%s|%s|%s|%s\n" %(hostname,date,username,cmd)
                log = "%s |%s | %s | %s | %s\n" %(ops_user,hostname,username,date,cmd)
                f.write(log)
                f.flush()
        f.close()
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

    
# thanks to Mike Looijmans for this code
def windows_shell(chan):
    import threading

    sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
        
    def writeall(sock):
        while True:
            data = sock.recv(256)
            if not data:
                sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
                sys.stdout.flush()
                break
            sys.stdout.write(data)
            sys.stdout.flush()
        
    writer = threading.Thread(target=writeall, args=(chan,))
    writer.start()
        
    try:
        while True:
            d = sys.stdin.read(1)
            if not d:
                break
            chan.send(d)
    except EOFError:
        # user hit ^Z or F6
        pass
View Code

 

3、編寫登錄腳本,用戶登錄堡壘機以後,自動運行腳本。腳本會根據用戶信息到數據庫中查詢該用戶能夠登錄的全部機器,並展示給用戶,用戶只須要選擇要登錄機器的序號便可完成登錄。

1.安裝數據庫,省略。

2.建立audit數據庫,創建2個表,一個是用戶信息表,一個服務器信息表,使用外鍵關聯。(當用戶刪除後,對應的服務器信息也將刪除。)

create database audit;

a.用戶信息表,結構和數據。

CREATE TABLE `user_info` (
  `employee_name` varchar(255) NOT NULL,
  `department` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
View Code

b.服務器信息表,結構和數據。

CREATE TABLE `server_info` (
  `employee_name` varchar(255) NOT NULL,
  `ip_address` varchar(16) NOT NULL,
  `user_name` varchar(16) NOT NULL,
  `user_pass` varchar(32) NOT NULL,
  KEY `employee_name` (`employee_name`),
  CONSTRAINT `server_info_ibfk_1` FOREIGN KEY (`employee_name`) REFERENCES `user_info` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
View Code

3.編寫登錄腳本run_demo.py,用戶退出該腳本的時候也會退出該堡壘機(即腳本結束後,shell會話也會退出。)

代碼以下:

#!/usr/bin/env python
import os,sys,MySQLdb

employee_name = 'opslover'
s_id = os.getppid()
try:
    conn = MySQLdb.connect(host='localhost',user='root',passwd='123456',db='audit',port=3306)
    cur = conn.cursor()
    cur.execute("select * from server_info where employee_name = '%s' " % employee_name)
    result = cur.fetchall()
    #print list(result) 
    #--change tuple to list
    list_record = []
    for record in result:
        list_record.append(list(record))
        #print  list_record.index(list_record[1]),list_record[1]
    while True:
        os.system('clear')
        print """
                \033[35;1mWelcome to login jumpserver!\033[0m
                Choose the Server to connect:"""
        #print list_record
        #--obtain ip's index ,choice index to login remote server
        for line in list_record:
            print list_record.index(line),line[1]
        #print list_record
        choice = raw_input("\033[32;1mPlease chose one you will login remote server:\033[0m").strip()
        if choice == 'quit':
           print type(s_id)
           cmd = 'kill -9 %d' % s_id
           os.system(cmd)
        #if len(choice) == 0:continue
        #if not choice.isdigit():continue
        choice = int(choice)
        if choice >= len(list_record):
            print "\033[31:1mYou have no access to login remote server!!!"
            continue
        #print list_record
        login_ops_user = list_record[choice][0]
        login_server = list_record[choice][1]
        login_user = list_record[choice][2]
        login_pass = list_record[choice][3]
        #print login_ops_user,login_server,login_user,login_pass
        cmd = 'python /usr/share/doc/python-paramiko-1.15.1/demos/demo.py %s %s %s %s' %(login_server,login_user,login_pass,login_ops_user)
        os.system(cmd)
    #print choice
    cur.close()
    conn.close()
except MySQLdb.Error,e:
    print 'MySQL Error Info:',e
View Code

4.添加用戶環境變量,每次登錄堡壘機,自動執行該腳本。

[root@CT7 opslover]# grep python /home/opslover/.bashrc
python run_demo.py

4、模擬登錄演示。

1.使用opslover登錄堡壘機,顯示此用戶全部能夠登錄的機器。

2.選擇ip對應的索引便可完成登錄。(選擇0)

3.執行exit退出遠程服務器後,堡壘機會繼續詢問你要登錄哪臺機器。選擇1,繼續。

4.執行exit退出遠程服務器後,堡壘機會繼續詢問你要登錄哪臺機器。此時用戶能夠退出,再也不登錄遠程服務器,執行quit便可,shell進程也會被退出。

5、審計結果查看。

模擬登錄過程當中的全部操做都會被記錄在/tmp/audit開頭的文件,會以用戶和日期分割文件。

這樣就借用paramiko模塊簡單實現了堡壘機+審計的功能。有興趣的能夠根據本身的須要自行繼續擴展修改。

相關文章
相關標籤/搜索