python模塊之 paramiko

轉自:http://blog.csdn.net/songfreeman/article/details/50920767 ios


paramiko模塊提供了ssh及sft進行遠程登陸服務器執行命令和上傳下載文件的功能。這是一個第三方的軟件包,使用以前須要安裝。shell

1 基於用戶名和密碼的 sshclient 方式登陸服務器

# 創建一個sshclient對象ssh = paramiko.SSHClient()# 容許將信任的主機自動加入到host_allow 列表,此方法必須放在connect方法的前面ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 調用connect方法鏈接服務器ssh.connect(hostname='192.168.2.129', port=22, username='super', password='super')# 執行命令stdin, stdout, stderr = ssh.exec_command('df -hl')# 結果放到stdout中,若是有錯誤將放到stderr中print(stdout.read().decode())# 關閉鏈接ssh.close()123456789101112123456789101112

2 基於用戶名和密碼的 transport 方式登陸 
方法1是傳統的鏈接服務器、執行命令、關閉的一個操做,有時候須要登陸上服務器執行多個操做,好比執行命令、上傳/下載文件,方法1則沒法實現,能夠經過以下方式來操做session

# 實例化一個transport對象trans = paramiko.Transport(('192.168.2.129', 22))# 創建鏈接trans.connect(username='super', password='super')# 將sshclient的對象的transport指定爲以上的transssh = paramiko.SSHClient()
ssh._transport = trans# 執行命令,和傳統方法同樣stdin, stdout, stderr = ssh.exec_command('df -hl')
print(stdout.read().decode())# 關閉鏈接trans.close()12345678910111213141234567891011121314

3 基於公鑰密鑰的 SSHClient 方式登陸ssh

# 指定本地的RSA私鑰文件,若是創建密鑰對時設置的有密碼,password爲設定的密碼,如無不用指定password參數pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')# 創建鏈接ssh = paramiko.SSHClient()
ssh.connect(hostname='192.168.2.129',
            port=22,
            username='super',
            pkey=pkey)# 執行命令stdin, stdout, stderr = ssh.exec_command('df -hl')# 結果放到stdout中,若是有錯誤將放到stderr中print(stdout.read().decode())# 關閉鏈接ssh.close()12345678910111213141234567891011121314

4 基於密鑰的 Transport 方式登陸socket

# 指定本地的RSA私鑰文件,若是創建密鑰對時設置的有密碼,password爲設定的密碼,如無不用指定password參數pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')# 創建鏈接trans = paramiko.Transport(('192.168.2.129', 22))
trans.connect(username='super', pkey=pkey)# 將sshclient的對象的transport指定爲以上的transssh = paramiko.SSHClient()
ssh._transport = trans# 執行命令,和傳統方法同樣stdin, stdout, stderr = ssh.exec_command('df -hl')
print(stdout.read().decode())# 關閉鏈接trans.close()1234567891011121314151612345678910111213141516

##### 傳文件 SFTP ###########ide

# 實例化一個trans對象# 實例化一個transport對象trans = paramiko.Transport(('192.168.2.129', 22))# 創建鏈接trans.connect(username='super', password='super')# 實例化一個 sftp對象,指定鏈接的通道sftp = paramiko.SFTPClient.from_transport(trans)# 發送文件sftp.put(localpath='/tmp/11.txt', remotepath='/tmp/22.txt')# 下載文件# sftp.get(remotepath, localpath)trans.close()123456789101112123456789101112

5 實現輸入命令立馬返回結果的功能 
以上操做都是基本的鏈接,若是咱們想實現一個相似xshell工具的功能,登陸之後能夠輸入命令回車後就返回結果:工具

import paramikoimport osimport selectimport sys# 創建一個sockettrans = paramiko.Transport(('192.168.2.129', 22))# 啓動一個客戶端trans.start_client()# 若是使用rsa密鑰登陸的話'''
default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
prikey = paramiko.RSAKey.from_private_key_file(default_key_file)
trans.auth_publickey(username='super', key=prikey)
'''# 若是使用用戶名和密碼登陸trans.auth_password(username='super', password='super')# 打開一個通道channel = trans.open_session()# 獲取終端channel.get_pty()# 激活終端,這樣就能夠登陸到終端了,就和咱們用相似於xshell登陸系統同樣channel.invoke_shell()# 下面就能夠執行你全部的操做,用select實現# 對輸入終端sys.stdin和 通道進行監控,# 當用戶在終端輸入命令後,將命令交給channel通道,這個時候sys.stdin就發生變化,select就能夠感知# channel的發送命令、獲取結果過程其實就是一個socket的發送和接受信息的過程while True:
    readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])    # 若是是用戶輸入命令了,sys.stdin發生變化
    if sys.stdin in readlist:        # 獲取輸入的內容
        input_cmd = sys.stdin.read(1)        # 將命令發送給服務器
        channel.sendall(input_cmd)    # 服務器返回告終果,channel通道接受到結果,發生變化 select感知到
    if channel in readlist:        # 獲取結果
        result = channel.recv(1024)        # 斷開鏈接後退出
        if len(result) == 0:
            print("\r\n**** EOF **** \r\n")            break
        # 輸出到屏幕
        sys.stdout.write(result.decode())
        sys.stdout.flush()# 關閉通道channel.close()# 關閉連接trans.close()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152531234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253

6 支持tab自動補全spa

import paramikoimport osimport selectimport sysimport ttyimport termios'''
實現一個xshell登陸系統的效果,登陸到系統就不斷輸入命令同時返回結果
支持自動補全,直接調用服務器終端

'''# 創建一個sockettrans = paramiko.Transport(('192.168.2.129', 22))# 啓動一個客戶端trans.start_client()# 若是使用rsa密鑰登陸的話'''
default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
prikey = paramiko.RSAKey.from_private_key_file(default_key_file)
trans.auth_publickey(username='super', key=prikey)
'''# 若是使用用戶名和密碼登陸trans.auth_password(username='super', password='super')# 打開一個通道channel = trans.open_session()# 獲取終端channel.get_pty()# 激活終端,這樣就能夠登陸到終端了,就和咱們用相似於xshell登陸系統同樣channel.invoke_shell()# 獲取原操做終端屬性oldtty = termios.tcgetattr(sys.stdin)try:    # 將如今的操做終端屬性設置爲服務器上的原生終端屬性,能夠支持tab了
    tty.setraw(sys.stdin)
    channel.settimeout(0)    while True:
        readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])        # 若是是用戶輸入命令了,sys.stdin發生變化
        if sys.stdin in readlist:            # 獲取輸入的內容,輸入一個字符發送1個字符
            input_cmd = sys.stdin.read(1)            # 將命令發送給服務器
            channel.sendall(input_cmd)        # 服務器返回告終果,channel通道接受到結果,發生變化 select感知到
        if channel in readlist:            # 獲取結果
            result = channel.recv(1024)            # 斷開鏈接後退出
            if len(result) == 0:
                print("\r\n**** EOF **** \r\n")                break
            # 輸出到屏幕
            sys.stdout.write(result.decode())
            sys.stdout.flush()finally:    # 執行完後將如今的終端屬性恢復爲原操做終端屬性
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)# 關閉通道channel.close()# 關閉連接trans.close()
相關文章
相關標籤/搜索