
package mainimport ( "bufio" "flag" "fmt" "io" "os" "path/filepath" "strings" "github.com/czxichen/autoWork/tools/split" "golang.org/x/crypto/ssh")var ( passwd = flag.String("p","","-p passwd 指定密码.") user = flag.String("u","root","-u root 指定登录用户.") cfg = flag.String("c","serverList","-c serverList 指定serverList") ip_port = flag.String("i","-i ip:port 指定目标机器的IP端口,必须和-p结合使用否则不生效.") dpath = flag.String("d","-d /tmp/20160531.zip 指定发送到的路径,不能为空.") spath = flag.String("s","-s 20160531.zip 指定要发送文件的路径,不能为空."))func main() { flag.Parse() if *dpath == "" || *spath == "" { flag.PrintDefaults() os.Exit(1) } file,err := os.Open(*spath) if err != nil { fmt.Println("打开文件失败:",err) os.Exit(1) } info,_ := file.Stat() defer file.Close() if *ip_port != "" && *passwd != "" { ClIEnt,err := dail(*user,*passwd,*ip_port) if err != nil { fmt.Printf("连接%s失败.\n",err) os.Exit(1) } scp(ClIEnt,file,info.Size(),*dpath) return } var List [][]string ok := (*passwd != "" && *ip_port == "") List = config(*cfg,ok) if len(List) <= 0 { fmt.Println("serverList 不能为空.") os.Exit(1) } for _,v := range List { if ok { *ip_port = v[0] } else { *user = v[0] *passwd = v[1] *ip_port = v[2] } ClIEnt,err) continue } scp(ClIEnt,*dpath) }}func dail(user,password,ip_port string) (*ssh.ClIEnt,error) { PassWd := []ssh.AuthMethod{ssh.Password(password)} Conf := ssh.ClIEntConfig{User: user,Auth: PassWd} return ssh.Dial("tcp",ip_port,&Conf)}func scp(ClIEnt *ssh.ClIEnt,file io.Reader,size int64,path string) { filename := filepath.Base(path) dirname := strings.Replace(filepath.Dir(path),"\","/",-1) defer ClIEnt.Close() session,err := ClIEnt.NewSession() if err != nil { fmt.Println("创建Session失败:",err) return } go func() { w,_ := session.StdinPipe() fmt.Fprintln(w,"C0644",size,filename) io.copyN(w,size) fmt.Fprint(w,"\x00") w.Close() }() if err := session.Run(fmt.Sprintf("/usr/bin/scp -qrt %s",dirname)); err != nil { fmt.Println("执行scp命令失败:",err) session.Close() return } else { fmt.Printf("%s 发送成功.\n",ClIEnt.RemoteAddr()) session.Close() } if session,err = ClIEnt.NewSession(); err == nil { defer session.Close() buf,err := session.Output(fmt.Sprintf("/usr/bin/md5sum %s",path)) if err != nil { fmt.Println("检查md5失败:",err) return } fmt.Printf("%s 的MD5:\n%s\n",ClIEnt.RemoteAddr(),string(buf)) }}func config(path string,ok bool) (List [][]string) { file,err := os.Open(path) if err != nil { fmt.Printf("打开配置文件失败:%s\n",err) os.Exit(1) } defer file.Close() buf := bufio.NewReader(file) for { line,_,err := buf.Readline() if err != nil { break } str := strings.Trimspace(string(line)) strs := split.Split(str) if ok { if len(strs) != 1 { continue } } else { if len(strs) != 3 { continue } } List = append(List,strs) } return} 总结 以上是内存溢出为你收集整理的golang实现跨平台scp批量群发文件全部内容,希望文章能够帮你解决golang实现跨平台scp批量群发文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)