python之實現基於paramiko和mysql資料庫的Bastion Host

來源:互聯網
上載者:User

標籤:

一、Bastion Host結構

  Bastion Host執行流程:

    1. 管理員為使用者在伺服器上建立帳號(將公開金鑰放置伺服器,或者使用使用者名稱密碼)
    2. 使用者登陸Bastion Host,輸入Bastion Host使用者名稱密碼,現實目前使用者管理的伺服器列表
    3. 使用者選擇伺服器,並自動登陸
    4. 執行操作並同時將使用者操作記錄

  註:配置.brashrc實現ssh登陸後自動執行指令碼,如:/usr/bin/python /home/wupeiqi/menu.py

二、實現過程

步驟一,實現使用者登陸

import getpass

user = raw_input(‘username:‘)
pwd = getpass.getpass(‘password‘)
if user == ‘alex‘ and pwd == ‘123‘:
print ‘登陸成功‘
else:
print ‘登陸失敗‘
步驟二,根據使用者擷取相關伺服器列表


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
步驟三,根據使用者名稱、私密金鑰登陸伺服器


tran = paramiko.Transport((hostname, port,))
tran.start_client()
default_path = os.path.join(os.environ[‘HOME‘], ‘.ssh‘, ‘id_rsa‘)
key = paramiko.RSAKey.from_private_key_file(default_path)
tran.auth_publickey(‘wupeiqi‘, key)

# 開啟一個通道
chan = tran.open_session()
# 擷取一個終端
chan.get_pty()
# 啟用器
chan.invoke_shell()

#########
# 利用sys.stdin,肆意妄為執行操作
# 使用者在終端輸入內容,並將內容發送至遠程伺服器
# 遠程伺服器執行命令,並將結果返回
# 使用者終端顯示內容
#########

chan.close()
tran.close()

 

三、終極版實現

import paramikoimport sysimport osimport socketimport getpassfrom paramiko.py3compat import u# windows does not have termios...try:    import termios    import tty    has_termios = Trueexcept ImportError:    has_termios = Falsedef interactive_shell(chan):    if has_termios:        posix_shell(chan)    else:        windows_shell(chan)def posix_shell(chan):    import select    oldtty = termios.tcgetattr(sys.stdin)    try:        tty.setraw(sys.stdin.fileno())        tty.setcbreak(sys.stdin.fileno())        chan.settimeout(0.0)        log = open(‘handle.log‘, ‘a+‘, encoding=‘utf-8‘)        flag = False        temp_list = []        while True:            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                    if flag:                        if x.startswith(‘\r\n‘):                            pass                        else:                            temp_list.append(x)                        flag = False                    sys.stdout.write(x)                    sys.stdout.flush()                except socket.timeout:                    pass            if sys.stdin in r:                x = sys.stdin.read(1)                import json                if len(x) == 0:                    break                if x == ‘\t‘:                    flag = True                else:                    temp_list.append(x)                if x == ‘\r‘:                    log.write(‘‘.join(temp_list))                    log.flush()                    temp_list.clear()                chan.send(x)    finally:        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)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        passdef run():    default_username = getpass.getuser()    username = input(‘Username [%s]: ‘ % default_username)    if len(username) == 0:        username = default_username    hostname = input(‘Hostname: ‘)    if len(hostname) == 0:        print(‘*** Hostname required.‘)        sys.exit(1)    tran = paramiko.Transport((hostname, 22,))    tran.start_client()    default_auth = "p"    auth = input(‘Auth by (p)assword or (r)sa 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)        tran.auth_publickey(username, key)    else:        pw = getpass.getpass(‘Password for %[email protected]%s: ‘ % (username, hostname))        tran.auth_password(username, pw)    # 開啟一個通道    chan = tran.open_session()    # 擷取一個終端    chan.get_pty()    # 啟用器    chan.invoke_shell()    interactive_shell(chan)    chan.close()    tran.close()if __name__ == ‘__main__‘:    run()

python之實現基於paramiko和mysql資料庫的Bastion Host

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.