標籤:style blog http 使用 os 檔案 io art
試了一下perl下安裝ssh模組,整了半天linux/window上都裝不上,各相依模組的版本總是匹配不上,後改了一下思路,用ruby吧
Net::SSH和Net::SCP是兩個Ruby操作SSH的gem包。Net::SSH相當於cmd,專門用於執行命令;Net::SCP專門用於傳輸檔案。它們倆結合,可以做任何SSH client能做的事情。
安裝:
gem install net-sshgem install net-scp
以下所有代碼都引用這段代碼
require ‘net/ssh‘require ‘net/scp‘HOST = ‘192.168.1.1‘USER = ‘username‘PASS = ‘password‘
1、使用Net::SSH執行一個命令
Net::SSH.start( HOST, USER, :password => PASS ) do |ssh| result = ssh.exec!(‘ls‘) puts resultend
Net::SSH.start會與目標主機建立一個串連,並返回一個代表串連的session。如果後面接收一個block,會在block結束時自動關閉串連。否則要自己關閉串連。注意密碼作為一個hash參數傳遞,是因為SSH登入驗證方式比較多,需要的參數變化多樣。
2、使用NET-SFTP傳輸檔案。
如果不需要執行命令,僅僅是傳輸檔案,可以使用Net::SCP.start,類似Net::SSH.start
Net::SCP.start( HOST, USER, :password => PASS ) do |scp| scp.upload!( ‘c:/scp1.rb‘, ‘/home/oldsong/‘ ) scp.download!( ‘/home/oldsong/test.txt‘, ‘c:/‘ )end
3、如果即要傳輸檔案,又要執行命令,scp不必重建立立串連,借用ssh串連即可
Net::SSH.start( HOST, USER, :password => PASS ) do|ssh| logfiles = ssh.exec!( ‘ls *.log‘ ).split logfiles.each do |l| ssh.scp.download!( l, l ) endend
4、如果要傳輸大檔案,最好能顯示傳輸進度,不然好久沒反應,還會以為死機了呢。
Net::SSH.start( HOST, USER, :password => PASS ) do|ssh| ssh.scp.upload!( ‘large.zip‘, ‘.‘ ) do|ch, name, sent, total| print "\r#{name}: #{(sent.to_f * 100 / total.to_f).to_i}%" endend5、上傳一個目錄,包括子目錄中的所有檔案。加上“:recursive => true”參數。
Net::SSH.start( HOST, USER, :password => PASS ) do|ssh| ssh.scp.download!( ‘logs‘, ‘.‘, :recursive => true )end
6、如果下載後不想儲存成檔案,而是放到記憶體中直接處理,只要不給download!傳遞本地檔案名稱即可,會返回一個字串。
Net::SCP.start( HOST, USER, :password => PASS ) do|scp| puts scp.download!(‘log.txt‘).split(/\n/).grep(/^ERROR/)end
7、scp最進階應用程式,根據事件顯示所有傳輸資訊。
Net::SCP.start( HOST, USER, :password => PASS ) do|scp| sftp.upload!(f, remote_file) do |event, uploader, *args|case event # args[0] : file metadata when :openputs "start uploading.#{args[0].local} -> #{args[0].remote} #{args[0].size} bytes}" when :put then# args[0] : file metadata# args[1] : byte offset in remote file# args[2] : data being written (as string)puts "writing #{args[2].length} bytes to #{args[0].remote} starting at #{args[1]}" when :close then# args[0] : file metadataputs "finished with #{args[0].remote}" when :mkdir then# args[0] : remote path nameputs "creating directory #{args[0]}" when :finish thenputs "all done!"end end puts "upload success"end 標籤: Linux, net-scp, net-ssh, net::scp, net::ssh, Ruby