審計系統---堡壘機python下ssh的使用

堡壘機python下ssh的使用

【堡壘機更多參考】http://www.cnblogs.com/alex3714/articles/5286889.html html

【paramiko的Demo實例】https://github.com/paramiko/paramiko python

Win7下paramiko的Demo遠程登陸執行交互命令: ios

【下載Demo文件】     https://github.com/paramiko/paramikogit

【paramiko更多參考】paramiko模塊學習github

image

本機[win7]登陸遠程Linux服務器sql

image

          Win7本機IP:  192.168.2.102 shell

          遠程服務器IP: 192.168.2.105windows

image

image

關於Win7下執行原代碼報錯問題的解決: 服務器

錯誤現象:TypeError: write() argument must be str, not bytes app

image

問題解決:F:\Django\paramiko-demo\paramiko-master\demos\interactive.py

image

 

Linux下paramiko的Demo遠程登陸執行交互命令:

下載Demo文件

https://github.com/paramiko/paramikoimage

上傳文件到本機Linux服務器:

omc@omc-virtual-machine:~$  cd paramiko_demo/
omc@omc-virtual-machine:~/paramiko_demo$  ll

image

Linux登陸其餘的Linux服務器

  Linxu本機IP:  192.168.25.110

  遠程服務器IP: 192.168.25.133

omc@omc-virtual-machine:~/paramiko_demo$  python3 demo.py
Hostname: 192.168.25.133
*** Unable to open host keys file
*** WARNING: Unknown host key!
Username [omc]: root
Auth by (p)assword, (r)sa key, or (d)ss key? [p]  p
Password for root@192.168.25.133: 
*** Here we go!
Last login: Tue May  1 07:53:03 2018 from 192.168.25.110
[root@localhost ~]# 

image

omc@omc-virtual-machine:~/paramiko_demo$ ssh  root@192.168.25.133
The authenticity of host '192.168.25.133 (192.168.25.133)' can't be established.
RSA key fingerprint is SHA256:+v73ij2IHBzxee8o9n5rYkBJPwD96SaEBtxkuGBBCqg.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.25.133' (RSA) to the list of known hosts.
root@192.168.25.133's password: 
Last login: Tue May  1 07:44:47 2018 from 192.168.25.1
[root@localhost ~]# logout
Connection to 192.168.25.133 closed.
omc@omc-virtual-machine:~/paramiko_demo$ python3 demo.py         
Hostname: 192.168.25.133
*** Host key OK.
Username [omc]: root
Auth by (p)assword, (r)sa key, or (d)ss key? [p] p
Password for root@192.168.25.133: 
*** Here we go!

注意:區別於第一次登陸,第二次登陸能夠獲取的133服務器的信息,沒有了告警

image

paramiko的Demo分析以及改進

demo.py

image

interactive.py

image

paramiko的interactive改進:

import socket
import sys
import time
from paramiko.py3compat import u
# windows does not have termios...
try:
    import termios
    import tty

    has_termios = True
except ImportError:
    has_termios = False
def interactive_shell(chan):  # chan應該是個鏈接的實例
    if has_termios:  # 判斷win仍是Linux
        posix_shell(chan)  # posix是Linux下的協議標準
    else:
        windows_shell(chan)

def posix_shell(chan):  # chan 就是咱們創建的鏈接實例
    import select  # IO多路複用,獲取事件時會一個個的進行進行搜尋,直到找到那個事件
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        cmd = []
        f = open('cmd.log', 'a')
        while True:  # select循環監測
            r, w, e = select.select([chan, sys.stdin], [], [])  # 3個參數分別爲輸入,輸出,錯誤信息
            if chan in r:  # 若是遠程有返回命令的結果,進行結果輸出
                try:
                    x = u(chan.recv(1024))  # 每次接收1KB的長度
                    if len(x) == 0:  # 長度爲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)  # read()函數,輸入一個讀取一個發送一個[回車表明命令輸入完成能夠執行任務]
                if(x == '\r'):   # Linux下的回車是\r
                    # print("".join(cmd))
                    cmd_log_format = "%s-%s-%s\r" % (time.ctime(time.time()), 'root', "".join(cmd))
                    f.write(cmd_log_format)
                    cmd = []  # 狀況做爲下次使用
                else:
                    cmd.append(x)
                if len(x) == 0:
                    break
                chan.send(x)  # 若是讀到了輸入內容,則發送到遠程進行操做
    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.decode("utf-8"))
            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

注:記錄了文件,可是由點小bug,就是文件會記錄下左右移動的操做[此時會轉換爲二進制的內容]

image

相關文章
相關標籤/搜索