package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"strconv"
"time"
"gopkg.in/ini.v1"
)
func floattostr(input_num float64)
string
{
// to convert a float number to a string
return
strconv.FormatFloat(input_num,
'g'
, -1, 64)
}
func getTime()
string
{
// 得到unix时间戳
t := time.Now()
timestamp := t.Unix()
// 时间戳转时间格式字符串
tm := time.Unix(timestamp, 0)
s_tm := tm.Format(
"2006-01-02 15:04:05"
)
return
s_tm
}
func writeip(s
string
) {
//创建一个新文件,写入内容
filePath :=
"./ip.log"
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if
err != nil {
fmt.Printf(
"打开文件错误= %v \n"
, err)
return
}
//及时关闭
defer file.Close()
//写入内容
ip := getTime() +
" "
+ s +
"\n"
// \n\r表示换行 txt文件要看到换行效果要用 \r\n
//写入时,使用带缓存的 *Writer
writer := bufio.NewWriter(file)
writer.WriteString(ip)
//因为 writer 是带缓存的,因此在调用 WriterString 方法时,内容是先写入缓存的
//所以要调用 flush方法,将缓存的数据真正写入到文件中。
writer.Flush()
}
func getIpInfo()
string
{
var vmidIpAddr
string
var ipArr [6]
string
var innerIp =
""
var outIp =
""
addrs, err := net.InterfaceAddrs()
if
err != nil {
fmt.Println(err)
os.Exit(1)
}
j := 0
for
_, address := range addrs {
// 检查ip地址判断是否回环地址
if
ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if
ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
ipArr[j] = ipnet.IP.String()
fmt.Println(j)
j++
}
}
}
innerIp = ipArr[0]
outIp = ipArr[1]
fmt.Println(innerIp)
fmt.Println(outIp)
vmidIpAddr =
"inner_ip="
+ innerIp +
"&outer_ip="
+ outIp
writeip(vmidIpAddr)
vmidIpAddr =
"inner_ip=192.168.10.146&outer_ip=192.168.10.146"
return
vmidIpAddr
}
func main() {
var CacherIp =
""
var vmid =
""
var smb_user =
""
var smb_password =
""
var ipInfo =
""
cfg, err := ini.Load(
"cloudgame_mount.ini"
)
if
err != nil {
fmt.Printf(
"Fail to read file: %v"
, err)
os.Exit(1)
}
// 典型读取操作,默认分区可以使用空字符串表示
CacherIp = cfg.Section(
""
).Key(
"CacherIp"
).String()
// vmid = cfg.Section("").Key("vmid").String()
smb_user = cfg.Section(
""
).Key(
"smb_user"
).String()
smb_password = cfg.Section(
""
).Key(
"smb_password"
).String()
//获取本地IP
ipInfo = getIpInfo()
//获取vmid
//resp, err := http.Get("http://192.168.10.182:8082/cloud_games_shelves_api/v1/getvmid?inner_ip=192.168.10.146&outer_ip=192.168.10.146")
resp, err := http.Get(
"http://192.168.10.182:8082/cloud_games_shelves_api/v1/getvmid?"
+ ipInfo)
if
err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var vminfo map[
string
]
interface
{}
err1 := json.Unmarshal([]
byte
(
string
(body)), &vminfo)
if
err1 != nil {
fmt.Println(err1)
}
vmid = floattostr(vminfo[
"vmid"
].(float64))
//挂载磁盘
mountstr :=
"net use w: \\\\"
+ CacherIp +
"\\area_vm_data_"
+ vmid +
" "
+ smb_password +
" "
+
"/user:"
+ smb_user
fmt.Println(mountstr)
c := exec.Command(
"cmd"
,
"/C"
, mountstr)
if
err := c.Start(); err != nil {
fmt.Println(
"Error: "
, err)
}
}