Skip to content

Commit c8c61a6

Browse files
committed
fix(v1.0): support IP段
1 parent 0a6c8c2 commit c8c61a6

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

cmd/root.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package cmd
1717
import (
1818
"fmt"
1919
"github.com/cuisongliu/sshcmd/pkg/sshutil"
20+
"github.com/cuisongliu/sshcmd/pkg/utils"
2021
"github.com/wonderivan/logger"
2122
"golang.org/x/crypto/ssh"
2223
"os"
@@ -79,6 +80,7 @@ func validate(tSSH *sshutil.SSH) {
7980
}
8081
var session *ssh.Session
8182
var errors []error
83+
host = utils.ParseIPs(host)
8284
for _, h := range host {
8385
session, err := tSSH.Connect(h)
8486
if err != nil {

pkg/utils/utils.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package utils
2+
3+
import (
4+
"fmt"
5+
"github.com/wonderivan/logger"
6+
"math/big"
7+
"net"
8+
"os"
9+
"strings"
10+
)
11+
12+
// ParseIPs 解析ip 192.168.0.2-192.168.0.6
13+
func ParseIPs(ips []string) []string {
14+
return DecodeIPs(ips)
15+
}
16+
17+
func DecodeIPs(ips []string) []string {
18+
var res []string
19+
var port string
20+
for _, ip := range ips {
21+
port = "22"
22+
if ipport := strings.Split(ip, ":"); len(ipport) == 2 {
23+
ip = ipport[0]
24+
port = ipport[1]
25+
}
26+
if iprange := strings.Split(ip, "-"); len(iprange) == 2 {
27+
for Cmp(stringToIP(iprange[0]), stringToIP(iprange[1])) <= 0 {
28+
res = append(res, fmt.Sprintf("%s:%s", iprange[0], port))
29+
iprange[0] = NextIP(stringToIP(iprange[0])).String()
30+
}
31+
} else {
32+
if stringToIP(ip) == nil {
33+
logger.Error("ip [%s] is invalid", ip)
34+
os.Exit(1)
35+
}
36+
res = append(res, fmt.Sprintf("%s:%s", ip, port))
37+
}
38+
}
39+
return res
40+
}
41+
42+
// Cmp compares two IPs, returning the usual ordering:
43+
// a < b : -1
44+
// a == b : 0
45+
// a > b : 1
46+
func Cmp(a, b net.IP) int {
47+
aa := ipToInt(a)
48+
bb := ipToInt(b)
49+
50+
if aa == nil || bb == nil {
51+
logger.Error("ip range %s-%s is invalid", a.String(), b.String())
52+
os.Exit(-1)
53+
}
54+
return aa.Cmp(bb)
55+
}
56+
func ipToInt(ip net.IP) *big.Int {
57+
if v := ip.To4(); v != nil {
58+
return big.NewInt(0).SetBytes(v)
59+
}
60+
return big.NewInt(0).SetBytes(ip.To16())
61+
}
62+
63+
func intToIP(i *big.Int) net.IP {
64+
return net.IP(i.Bytes())
65+
}
66+
func stringToIP(i string) net.IP {
67+
return net.ParseIP(i).To4()
68+
}
69+
70+
// NextIP returns IP incremented by 1
71+
func NextIP(ip net.IP) net.IP {
72+
i := ipToInt(ip)
73+
return intToIP(i.Add(i, big.NewInt(1)))
74+
}

0 commit comments

Comments
 (0)