时间:2021.06.22
环境:Windows
目的:批量通过ssh连接远程主机执行命令
说明:
作者:Zhong QQ交流群:121160124 欢迎加入!
ip_info.txt文件内容如下:
192.168.40.66
192.168.40.67
192.168.40.68
192.168.40.69
192.168.40.70
192.168.40.71
192.168.40.72
192.168.40.73
192.168.40.74
192.168.40.75
192.168.40.76
192.168.40.77
192.168.40.78
192.168.40.79
192.168.40.80
192.168.40.81
192.168.40.82
192.168.40.83
192.168.40.84
192.168.40.85
192.168.40.86
192.168.40.87
192.168.40.88
代码如下:
package main
import (
"fmt"
"sync"
"strings"
"golang.org/x/crypto/ssh"
"log"
"os"
"bufio"
"io"
"time"
"flag"
)
// 定义ip列表
var ip_list = []string{}
var user, passwd, port, ip_info string
var n int
type Glimit struct {
n int
c chan struct{}
}
// initialization Glimit struct
func New(n int) *Glimit {
return &Glimit{
n: n,
c: make(chan struct{}, n),
}
}
// Run f in a new goroutine but with limit.
func (g *Glimit) Run(f func()) {
g.c <- struct{}{}
go func() {
f()
<-g.c
}()
}
var wg sync.WaitGroup
//判断文件是否存在 存在返回 true 不存在返回false
func checkFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
func read_txt(ip_info string) {
file, err := os.Open(ip_info)
if err != nil {
fmt.Printf("系统无法找到指定的文件,请检查%v是否存在!\n", ip_info)
log.Fatal(err)
}
defer file.Close()
br := bufio.NewReader(file)
for {
a, _, c := br.ReadLine()
if c == io.EOF {
break
}
ip_list = append(ip_list, string(a))
}
}
func main(){
flag.StringVar(&ip_info, "t", "ip_info.txt", "ip地址数据文件") //获取string类型参数
flag.StringVar(&user, "u", "root", "用户名") //获取string类型参数
flag.StringVar(&passwd, "p", "", "密码")
flag.StringVar(&port, "port", "22", "端口")
flag.IntVar(&n, "n", 10, "Max exec number")
flag.Parse()
read_txt(ip_info)
txt_ls := len(ip_list)
fmt.Println(txt_ls)
t := time.Now()
number := txt_ls
g := New(n)
for i := 0; i < number; i++ {
wg.Add(1)
value :=i
goFunc := func() {
client, err := ssh.Dial("tcp", strings.Join([]string{ip_list[value], port}, ":"), &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(passwd)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
//log.Fatalf("SSH dial error: %s", err.Error())
fmt.Printf("SSH dial error: %s\n", err.Error())
//ch <- fmt.Sprintf("ip : %s error! SSH dial error: %s", ip, err.Error())
wg.Done()
return
}
// 建立新会话
session, err := client.NewSession()
defer session.Close()
if err != nil {
log.Fatalf("new session error: %s\n", err.Error())
}
result, err := session.Output("ls -a")
if err != nil {
fmt.Fprintf(os.Stdout, "Failed to run command, Err:%s\n", err.Error())
//ch <- fmt.Sprintf("ip : %s error! Failed to run command, Err:%s", ip, err.Error())
wg.Done()
return
//os.Exit(0)
}
fmt.Println(string(result))
//time.Sleep(time.Second)
wg.Done()
return
}
g.Run(goFunc)
}
wg.Wait()
elapsed := time.Since(t)
fmt.Println("app elapsed:", elapsed)
}
/*
go run main.go -u root -p 2021Zhong... -port 22 -n 20
*/
关注微信公众号
QQ交流群:121160124 欢迎加入