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")