Exemplo n.º 1
0
func CopyFile(conn *ssh.Client, FileName, DirectoryPath string) bool {
	defer conn.Close()
	if !strings.HasSuffix(DirectoryPath, "/") {
		DirectoryPath = DirectoryPath + "/"
	}
	con, err := sftp.NewClient(conn, sftp.MaxPacket(5e9))
	if err != nil {
		color.Red("%s传输文件新建会话错误: %s\n", conn.RemoteAddr(), err)
		return false
	}
	sFile, _ := os.Open(FileName)
	defer sFile.Close()
	dFile := DirectoryPath + FileName
	fmt.Printf("%s 目标路径:%s\n", conn.RemoteAddr(), dFile)
	File, err := con.OpenFile(dFile, os.O_CREATE|os.O_TRUNC|os.O_RDWR)
	if err != nil {
		color.Red("%s 创建文件%s错误: %s \n", conn.RemoteAddr(), dFile, err)
		return false
	}
	defer File.Close()
	for {
		buf := make([]byte, 1024)
		n, err := sFile.Read(buf)
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return false
		}
		File.Write(buf[:n])
	}
	Result <- fmt.Sprintf("上传%s到%s成功.\n", FileName, conn.RemoteAddr())
	return true
}
Exemplo n.º 2
0
func Sftp(ip, path, localpath, action string) {
	var auths []ssh.AuthMethod
	if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
		auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))

	}
	auth_list := parse("passlist", ip)
	if len(auth_list) == 0 {
		log.Println("获取用户和密码失败.")
		os.Exit(-1)
	}
	auths = append(auths, ssh.Password(auth_list[2]))

	config := ssh.ClientConfig{
		User: auth_list[1],
		Auth: auths,
	}
	addr := fmt.Sprintf("%s:%s", ip, auth_list[3])
	conn, err := ssh.Dial("tcp", addr, &config)
	if err != nil {
		log.Fatalf("unable to connect to [%s]: %v", addr, err)
	}
	defer conn.Close()
	c, err := sftp.NewClient(conn, sftp.MaxPacket(6e9))
	if err != nil {
		log.Fatalf("unable to start sftp subsytem: %v", err)
	}
	defer c.Close()
	switch action {
	case "get":
		fs, e := c.Open(path)
		if e != nil {
			log.Println(e)
			os.Exit(-1)
		}
		filename := filepath.Base(path)
		info, _ := fs.Stat()
		File, err := os.Create(fmt.Sprintf(`%s/%s`, strings.TrimRight(localpath, `/`), filename))
		if err != nil {
			log.Println(err)
			os.Exit(-1)
		}
		log.Println("保存路径:", fmt.Sprintf(`%s/%s`, strings.TrimRight(localpath, `/`), filename))
		defer File.Close()
		io.Copy(File, io.LimitReader(fs, info.Size()))
	case "push":
		filename := filepath.Base(path)
		fs, err := c.Create(fmt.Sprintf(`%s/%s`, strings.TrimRight(localpath, `/`), filename))
		if err != nil {
			log.Println(err)
			os.Exit(-1)
		}
		defer fs.Close()
		log.Println("保存路径:", fmt.Sprintf(`%s/%s`, strings.TrimRight(localpath, `/`), filename))
		File, err := os.Open(path)
		if err != nil {
			log.Println(err)
			os.Exit(-1)
		}
		defer File.Close()
		io.Copy(io.MultiWriter(fs), File)
	}
}