Skip to content

Commit

Permalink
fix(v1.0): support IP段
Browse files Browse the repository at this point in the history
  • Loading branch information
cuisongliu committed Mar 24, 2021
1 parent 0a6c8c2 commit c8c61a6
Showing 2 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@ package cmd
import (
"fmt"
"github.com/cuisongliu/sshcmd/pkg/sshutil"
"github.com/cuisongliu/sshcmd/pkg/utils"
"github.com/wonderivan/logger"
"golang.org/x/crypto/ssh"
"os"
@@ -79,6 +80,7 @@ func validate(tSSH *sshutil.SSH) {
}
var session *ssh.Session
var errors []error
host = utils.ParseIPs(host)
for _, h := range host {
session, err := tSSH.Connect(h)
if err != nil {
74 changes: 74 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package utils

import (
"fmt"
"github.com/wonderivan/logger"
"math/big"
"net"
"os"
"strings"
)

// ParseIPs 解析ip 192.168.0.2-192.168.0.6
func ParseIPs(ips []string) []string {
return DecodeIPs(ips)
}

func DecodeIPs(ips []string) []string {
var res []string
var port string
for _, ip := range ips {
port = "22"
if ipport := strings.Split(ip, ":"); len(ipport) == 2 {
ip = ipport[0]
port = ipport[1]
}
if iprange := strings.Split(ip, "-"); len(iprange) == 2 {
for Cmp(stringToIP(iprange[0]), stringToIP(iprange[1])) <= 0 {
res = append(res, fmt.Sprintf("%s:%s", iprange[0], port))
iprange[0] = NextIP(stringToIP(iprange[0])).String()
}
} else {
if stringToIP(ip) == nil {
logger.Error("ip [%s] is invalid", ip)
os.Exit(1)
}
res = append(res, fmt.Sprintf("%s:%s", ip, port))
}
}
return res
}

// Cmp compares two IPs, returning the usual ordering:
// a < b : -1
// a == b : 0
// a > b : 1
func Cmp(a, b net.IP) int {
aa := ipToInt(a)
bb := ipToInt(b)

if aa == nil || bb == nil {
logger.Error("ip range %s-%s is invalid", a.String(), b.String())
os.Exit(-1)
}
return aa.Cmp(bb)
}
func ipToInt(ip net.IP) *big.Int {
if v := ip.To4(); v != nil {
return big.NewInt(0).SetBytes(v)
}
return big.NewInt(0).SetBytes(ip.To16())
}

func intToIP(i *big.Int) net.IP {
return net.IP(i.Bytes())
}
func stringToIP(i string) net.IP {
return net.ParseIP(i).To4()
}

// NextIP returns IP incremented by 1
func NextIP(ip net.IP) net.IP {
i := ipToInt(ip)
return intToIP(i.Add(i, big.NewInt(1)))
}

0 comments on commit c8c61a6

Please sign in to comment.