在go语言中实现执行shell命令代码示例
在本文中,我们将向你展示如何在Go语言中执行shell命令,对于一个成熟的现代开发语言来说,如果没有办法让开发者执行shell命令,那么这种编程语言就不完整。
我们将使用dig命令来检索一个网站的名称服务器并输出。
很多时候,在大多数基于*nix的操作系统中,dig命令应该是默认安装的。
如果没有dig命令,你可以用
sudo yum install bind-utils
来安装它,或者搜索同等的安装说明来安装BIND包。
对于Windows的BIND包,下载链接:
http://www.isc.org
示例代码:
exec.go
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("dig", "any", "google.com")
out, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Print(string(out))
}
执行 > go run exec.go 将产生如下输出:
# go run exec.go
;; Truncated, retrying in TCP mode.
; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.el6_5.1 <<>> any google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52756
;; flags: qr rd ra; QUERY: 1, ANSWER: 24, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com. IN ANY
;; ANSWER SECTION:
google.com. 213 IN A 74.125.226.67
google.com. 213 IN A 74.125.226.70
google.com. 213 IN A 74.125.226.68
google.com. 213 IN A 74.125.226.78
google.com. 213 IN A 74.125.226.69
google.com. 213 IN A 74.125.226.66
google.com. 213 IN A 74.125.226.65
google.com. 213 IN A 74.125.226.72
google.com. 213 IN A 74.125.226.71
google.com. 213 IN A 74.125.226.73
google.com. 213 IN A 74.125.226.64
google.com. 213 IN AAAA 2607:f8b0:4006:808::1007
google.com. 513 IN MX 50 alt4.aspmx.l.google.com.
google.com. 21513 IN SOA ns1.google.com. dns-admin.google.com. 2014021800 7200 1800 1209600 300
google.com. 3513 IN TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com. 513 IN MX 30 alt2.aspmx.l.google.com.
google.com. 21513 IN NS ns4.google.com.
google.com. 21513 IN NS ns2.google.com.
google.com. 21513 IN NS ns3.google.com.
google.com. 513 IN MX 10 aspmx.l.google.com.
google.com. 21513 IN TYPE257 \# 19 0005697373756573796D616E7465632E636F6D
google.com. 513 IN MX 20 alt1.aspmx.l.google.com.
google.com. 513 IN MX 40 alt3.aspmx.l.google.com.
google.com. 21513 IN NS ns1.google.com.
;; Query time: 21 msec
;; SERVER: 8.8.4.4#53(8.8.4.4)
;; WHEN: Tue May 13 04:43:46 2014
;; MSG SIZE rcvd: 577
你可以改变以下代码:
cmd := exec.Command("dig","any","google.com")
至
application_name = "dig"
arg_0 = "any"
arg_1 = "google.com"
cmd := exec.Command(application_name,arg_0,arg_1)
注意:参数必须以这种方式分开,而不是把所有东西都放在一个字符串中。
参考资料:操作系统包
http://golang.org/pkg/os/exec/
相关文章