Ruby 擷取WINXP機器的IP

來源:互聯網
上載者:User

 ruby中有一個名叫open3的類,可以用來執行系統命令,但是winxp下安裝ruby後,預設的open3是支援linux的,運行代碼會報找不到fork()方法的錯誤。

 所幸已經有win版本的open3 :win32-open3 ,安裝很簡單,執行gem install win32-open3即可:

 

D:/ruby/bin>gem install win32-open3
Successfully installed win32-open3-0.2.7-x86-mswin32-60
1 gem installed
Installing ri documentation for win32-open3-0.2.7-x86-mswin32-60...
Installing RDoc documentation for win32-open3-0.2.7-x86-mswin32-60...

 

open3會返回一個數組,包含了3個 IO handles :STDIN, STDOUT ,STDERR 。分別為“標準輸入”,“標準輸出”,“錯誤".   通過對STDOUT的處理,即可得到系統命令執行的結果

 

代碼如下:

#GetIP.rb

require 'rubygems'
require 'win32/open3'

#stdin, stdout, stderr = Open3.popen3('ipconfig')  
#stdout =  Open3.popen3('ipconfig')
io_in, io_out, io_err = Open3.popen3("ipconfig",mode='t',show=false)
#io_in << "ipconfig/n"
io_out.each do |l|
p l
end

 

運行該檔案,結果如下:

"Windows IP Configuration/r/n"
"/r/n"
"/r/n"
"Ethernet adapter /316/336/317/337/315/370/302/347/301/254/275/323:/r/n"
"/r/n"
"        Media State . . . . . . . . . . . : Media disconnected/r/n"
"/r/n"
"Ethernet adapter /261/276/265/330/301/254/275/323:/r/n"
"/r/n"
"        Connection-specific DNS Suffix  . : /r/n"
"        IP Address. . . . . . . . . . . . : 222.248.147.93/r/n"
"        Subnet Mask . . . . . . . . . . . : 255.255.224.0/r/n"
"        Default Gateway . . . . . . . . . : 222.248.128.1/r/n"

 

 

以上只是擷取ip的一種方法,我們也可以用一句代碼搞定:

system("ipconfig")

聯繫我們

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