zoukankan      html  css  js  c++  java
  • 堡垒机(paramiko)

    实现思路


    堡垒机执行流程

    1. 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码)

    2. 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表

    3. 用户选择服务器,并自动登陆

    4. 执行操作并同时将用户操作记录

    注:配置.brashrc实现ssh登陆后自动执行脚本,如:/usr/bin/python /root/menu.py

        但为了防止用户ctrl+c退出脚本依然留在系统,可以在下面加入一行exit。

        脚本中捕获except EOFError和 Kerboard Interrupt:不要continue,直接写退出sys.exit(0)。

    实现过程

    以下代码其实是paramiko源码包里demo.py的精简

    步骤一,实现用户登陆
    1
    2
    3
    4
    5
    6
    7
    8
    import getpass
      
    user = raw_input('username:')
    pwd = getpass.getpass('password')
    if user == 'root' and pwd == '123':
        print '登陆成功'
    else:
        print '登陆失败'
    步骤二,根据用户获取相关服务器列表
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    dic = {
        'alex': [
            '172.16.103.189',
            'c10.puppet.com',
            'c11.puppet.com',
        ],
        'eric': [
            'c100.puppet.com',
        ]
    }
      
    host_list = dic['alex']
      
    print 'please select:'
    for index, item in enumerate(host_list, 1):
        print index, item
      
    inp = raw_input('your select (No):')
    inp = int(inp)
    hostname = host_list[inp-1]
    port = 22
    步骤三,根据用户名、私钥登陆服务器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import paramiko
    import os
     
    tran=paramiko.Transport(('192.168.136.8',22))
    tran.start_client()
    #用户名密码方式
    tran.auth_password('root','123456')
    #私钥认证方式
    # default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
    # key = paramiko.RSAKey.from_private_key_file(default_path)
    # tran.auth_publickey('root', key)
    #打开一个通道
    channel=tran.open_session()
    #获取一个终端
    channel.get_pty()
    #激活器
    channel.invoke_shell()
     
    ####终端操作,用下面的《终端操作》三种操作模式替换此段代码####
    # 利用sys.stdin,肆意妄为执行操作
    # 用户在终端输入内容,并将内容发送至远程服务器
    # 远程服务器执行命令,并将结果返回
    # 用户终端显示内容
    ###################################################
     
    channel.close()
    tran.close()

    终端操作

    以下代码其实是paramiko源码包里interactive.py的内容,前两种模式是在linux下执行,模式三适用于windows。

    操作模式一:(linux)

    用select监听channel句柄变化进行通讯,一行一行发送,即只有用户按了回车键,才发送。

    关于通信结束,客户端返回一个空值(输入‘exit’就是空值),就是关闭连接的信号。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import select
    import sys
    import socket
    while True:
        #监视用户输入和服务器返回的数据
        #sys.stdin处理用户输入
        #channel是之前创建的通道,用于接收服务器返回信息和发送信息,相当于socket句柄
        readable,writeable,error=select.select([channel,sys.stdin,],[],[],1)
        #只要 channel,stdin,两个句柄其中之一变化就......
        if channel in readable:
            try:
                x=channel.recv(1024)
                if len(x)==0:
                    print ' *** EOF ',
                    break
                sys.stdout.write(x)
                sys.stdout.flush()
            except socket.timeout:
                pass
        if sys.stdin in readable:
            inp=sys.stdin.readline()
            channel.sendall(inp)
    操作模式二:(linux)

    原始终端模式tty,一个字符发送一次,能有tab补齐等的效果,断开连接之前再切换回标准终端模式,不然堡垒机的tty会有问题。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import select
    import sys
    import socket
    import termios  #只在linux下支持
    import tty
     
    # 获取原tty属性
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        # 为tty设置新属性
        # 默认当前tty设备属性:
        #   输入一行回车,执行
        #   CTRL+C 进程退出,遇到特殊字符,特殊处理。
     
        # 这是为原始模式,不认识所有特殊符号
        # 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器
        tty.setraw(sys.stdin.fileno())  #设置为原始终端模式
        channel.settimeout(0.0)
     
        while True:
            # 监视 用户输入 和 远程服务器返回数据(socket)
            # 阻塞,直到句柄可读
            r, w, e = select.select([channel, sys.stdin], [], [], 1)
            if channel in r:
                try:
                    x = channel.recv(1024)
                    if len(x) == 0:
                        print ' *** EOF ',
                        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
                channel.send(x)
     
    finally:
        # 重新设置终端属性
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
    操作模式三:(windows)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    def windows_shell(chan):
        import threading
     
        sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF. ")
     
        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    sys.stdout.write(' *** EOF *** ')
                    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
    记录日志:

    也记录了tab(' '),显示的不完整,解决思路:根据返回的结果进行处理,比较麻烦。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    try:
        f=open('log','a')
        while True:
            if channel in r:
                try:
                    if len(x)==0:
                        f.close()
            if sys.stdin in r:
                ......
                f.write(x)
    finally:
        pass

















  • 相关阅读:
    python https请求报错:SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
    python打包为exe文件
    文件自定义扫描工具
    pandas 的常用方法
    cisco应用
    Cisco 模拟配置
    python 识别图片上的数字
    OpenSSL
    OpenSSL
    OpenSSL
  • 原文地址:https://www.cnblogs.com/daliangtou/p/5129262.html
Copyright © 2011-2022 走看看