python中的paramiko模組

來源:互聯網
上載者:User

標籤:method   http   oca   word   擷取檔案   xxxxx   rmi   密碼   pyc   

python的paramiko模組

此文章轉載於https://www.cnblogs.com/breezey/p/6663546.html,如有侵權,請聯絡。

     paramiko是用python語言寫的一個模組,遵循SSH2協議,支援以加密和認證的方式,進行遠程伺服器的串連。paramiko支援Linux, Solaris, BSD, MacOS X, Windows等平台通過SSH從一個平台串連到另外一個平台。利用該模組,可以方便的進行ssh串連和sftp協議進行sftp檔案傳輸。 paramiko常用的類與方法:  1、SSHClient類SHClient類是SSH服務會話的進階表示,封裝了傳輸、通道以及SFTPClient的校正、建立方法,通常用於執行命令。 1)connect方法connect(self,hostname,port=22,username=None,password=None,pkey=None,key_filename=None,timeout=None,allow_agent=True,look_for_keys=True,compress=False)參數說明:hostname:串連目標的主機地址port:串連目錄的連接埠,預設為22username:使用者名稱password:密碼pkey:私密金鑰方式使用者驗證key_filename:私密金鑰檔案名稱timeout:連線逾時時間allow_agent:是否允許使用ssh代理look_for_keys:是否允許搜尋私密金鑰檔案compress:開啟時是否壓縮 2)exec_command方法exec_command(self,command,bufsize=-1)參數說明:command:執行的的指令bufsize:檔案緩衝區大小,-1不限制 3)load_system_host_keys方法load_system_host_keys(self,filename=None)參數說明:filename:指定遠程主機的公開金鑰檔案,預設為.ssh目錄下的known_hosts檔案 4)set_missing_host_key_policy方法ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())參數說明:AutoAddPolicy:自動添加主機名稱及密鑰到本地並儲存,不依賴load_system_host_keys()配置,即如果known_hosts裡沒有遠程主機的公開金鑰時,預設串連會提示yes/no,自動yesRejectPolicy:自動拒絕未知主機名稱和密鑰,依賴load_system_host_keys()WarnningPlicy:功能與AutoAddPolicy相同,但是未知主機會提示yes/no  2、SFTPClient類根據SSH傳輸協議的sftp會話,實現遠程檔案上傳、下載等操作。 1)from_transport方法 classmethod from_transport(cls,t)參數說明:t:一個已通過驗證的傳輸對象 樣本:
>>> import paramiko>>> a = paramiko.Transport((“127.0.0.1″,2222))>>> a.connect(username=”root”, password=’123456′)>>> sftp = paramiko.SFTPClient.from_transport(a)
 2)put方法 put(self,localpath,remotepath,callback=None,confirm=True)參數說明:localpath:上傳源檔案的本地路徑remotepath:目標路徑callback:擷取接收與總傳輸位元組數confirm:上傳完畢後是否調用stat()方法,以便確認檔案大小 樣本:
>>> localpath=’ftp-test.log’>>> remotepath=’/data/ftp-test.log’>>> sftp.put(localpath,remotepath)

 

 3)get方法 get(self, remotepath, localpath, callback=None)參數說明:remotepath:需要下載的遠程檔案localpath:本機存放區路徑callback:同put方法 4)其他方法 mkdir:用於建立目錄remove:刪除目錄rename:重新命名stat:擷取檔案資訊listdir:擷取目錄列表  程式碼範例Paramiko ssh用戶端:
#!/usr/bin/pythonimport paramikoimport os,sysssh_host = sys.argv[1] ssh_port = 22user = ‘root‘password = ‘xxxxxx‘cmd = sys.argv[2]paramiko.util.log_to_file(‘/tmp/test‘)    #使用paramiko記錄日誌s = paramiko.SSHClient()    #綁定一個執行個體s.load_system_host_keys()    #載入known_hosts檔案s.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #遠端連線如果提示yes/no時,預設為yess.connect(ssh_host,ssh_port,user,password,timeout=5)    #串連遠程主機stdin,stdout,stderr = s.exec_command(cmd)    #執行指令,並將命令本身及命令的執行結果賦值到標準辦入、標準輸出或者標準錯誤cmd_result = stdout.read(),stderr.read()    #取得執行的輸出for line in cmd_result:  print lines.close()
 使用ssh密鑰串連:
pkey_file = ‘/home/breeze/.ssh/id_rsa‘key = paramiko.RSAKey.from_private_key_file(pkey_file)s.connect(host,port,username,pkey=key,timeout=5)stdin,stdout,stderr = s.exec_command(cmd)
 Paramiko SFTP傳送檔案:
#!/usr/bin/pythonimport os,sysimport paramikohost = sys.argv[1]rfilename = sys.argv[2]lfilename = os.path.basename(rfilename)user = ‘root‘password = ‘xxxx‘paramiko.util.log_to_file(‘/tmp/test‘) t = paramiko.Transport((host,22))t.connect(username=user,password=password)sftp = paramiko.SFTPClient.from_transport(t)sftp.get(rfilename,lfilename)#sftp.put(‘paramiko1.py‘,‘/tmp/paramiko1.py‘)t.close()

 

 使用interactive模組實現SSH互動:interactive.py模組內容如下:
#!/usr/bin/pythonimport socketimport sys   # windows does not have termios...try:import termiosimport 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)while True:            r, w, e = select.select([chan, sys.stdin], [], [])if chan in r:try:                    x = chan.recv(1024)if len(x) == 0:print ‘\r\n*** EOF\r\n‘,breaksys.stdout.write(x)                    sys.stdout.flush()except socket.timeout:pass            if sys.stdin in r:                x = sys.stdin.read(1)if len(x) == 0:breakchan.send(x)finally:        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)    # thanks to Mike Looijmans for this codedef 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()breaksys.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:breakchan.send(d)except EOFError:# user hit ^Z or F6pass
 inter_ssh.py互動指令碼如下:
#!/usr/bin/python#_*_coding:utf8_*_import paramikoimport interactive#記錄日誌paramiko.util.log_to_file(‘/tmp/test‘)#建立ssh串連ssh=paramiko.SSHClient()ssh.load_system_host_keys()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(‘192.168.128.82‘,port=22,username=‘root‘,password=‘cheyian‘)#建立互動式shell串連channel=ssh.invoke_shell()#建立互動式管道interactive.interactive_shell(channel)#關閉串連channel.close()ssh.close()

python中的paramiko模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.