一、安装集成ifconfig
linux输入命令
yum install -y net-tools.x86_64
这个en开头的就是你实际的主机地址 inet是ip地址 ether是mac地址
输入命令看是否能查询
ifconfig ens18 | grep ether | awk ‘{print $2}’
ifconfig ens18 | grep inet | awk ‘{print $2}’
代码如下(示例):
import (
"fmt"
"strings"
"golang.org/x/crypto/ssh"
)
type Cli struct {
user string
pwd string
addr string
client *ssh.Client
}
func NewCli(user, pwd, addr string) Cli {
return Cli{
user: user,
pwd: pwd,
addr: addr,
}
}
// Connect 连接远程服务器
func (c *Cli) Connect() error {
config := &ssh.ClientConfig{
User: c.user,
Auth: []ssh.AuthMethod{
ssh.Password(c.pwd),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", c.addr, config)
if nil != err {
return fmt.Errorf("connect server error: %w", err)
}
c.client = client
return nil
}
// Run 运行命令
func (c Cli) Run(shell string) (string, error) {
if c.client == nil {
if err := c.Connect(); err != nil {
return "", err
}
}
session, err := c.client.NewSession()
if err != nil {
return "", fmt.Errorf("create new session error: %w", err)
}
defer session.Close()
buf, err := session.CombinedOutput(shell)
return string(buf), err
}
// 调用测试
func main() {
var (
username = "root"
password = "主机密码"
addr = "主机地址"
)
// 初始化
client := NewCli(username, password, addr)
// ssh 并运行脚本
macsh := "ifconfig ens18 | grep " + "ether" + "| awk '{print $2}'"
ipsh := "ifconfig ens18 | grep " + "inet " + "| awk '{print $2}'"
macstr, err := client.Run(macsh)
ipstr, err := client.Run(ipsh)
if err != nil {
log.Printf("failed to run shell,err=[%v]\n", err)
return
}
if ipstr != "" {
iplist := strings.Split(ipstr, "\n")
if len(iplist) != 0 {
ip = iplist[0]
}
}
if macstr != "" {
mac = strings.Replace(macstr, "\n", "", -1)
}
fmt.Println("====mac====", mac)
fmt.Println("==ip=======", ip)
}