Closed
Description
Ubuntu 20.04 LTS
go version go1.19.3 linux/amd64
package main
import (
"fmt"
"github.com/go-git/go-git/v5"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"io/ioutil"
"os"
)
const (
PublicKeysName = "ssh-public-keys"
)
// PublicKeys implements AuthMethod by using the given key pairs.
type PublicKeys struct {
User string
KnownHost string
Signer ssh.Signer
}
func NewPublicKeys(user string, pemBytes []byte, knownHost, password string) (*PublicKeys, error) {
signer, err := ssh.ParsePrivateKey(pemBytes)
if _, ok := err.(*ssh.PassphraseMissingError); ok {
signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password))
}
if err != nil {
return nil, err
}
return &PublicKeys{User: user, KnownHost: knownHost, Signer: signer}, nil
}
func (a *PublicKeys) Name() string {
return PublicKeysName
}
func (a *PublicKeys) String() string {
return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
}
func (a *PublicKeys) ClientConfig() (*ssh.ClientConfig, error) {
hostKeyCallback, err := knownhosts.New(a.KnownHost)
if err != nil {
return nil, fmt.Errorf("client config %+v", err)
}
return &ssh.ClientConfig{
User: a.User,
Auth: []ssh.AuthMethod{ssh.PublicKeys(a.Signer)},
HostKeyCallback: hostKeyCallback,
}, nil
}
// CheckIfError should be used to naively panics if an error is not nil.
func CheckIfError(err error, track string) {
if err == nil {
return
}
fmt.Printf("\x1b[31;1m%s\x1b[0m\n", fmt.Sprintf("track:%s error: %s", track, err))
os.Exit(1)
}
func GetAuth() (*PublicKeys, error) {
sshKey, _ := ioutil.ReadFile("/home/demo1/.deploy/9CaCEM6QhP4jdP3DyhWYzbYCrJVFkhLC0B3Nwki59Nod45r6OmVZMVASnww9")
publicKeys, err := NewPublicKeys("git", sshKey, "/home/demo1/.deploy/known_hosts", "")
if err != nil {
return nil, fmt.Errorf("NewPublicKeys failed %+v", err)
}
return publicKeys, nil
}
func pull(path string, auth *PublicKeys) {
// We instantiate a new repository targeting the given path (the .git folder)
r, err := git.PlainOpen(path)
CheckIfError(err, "2")
// Get the working directory for the repository
w, err := r.Worktree()
CheckIfError(err, "3")
err = w.Pull(&git.PullOptions{
// RemoteName: "origin",
SingleBranch: true,
Auth: auth,
Progress: os.Stdout,
})
CheckIfError(err, "5")
// Print the latest commit that was just pulled
ref, err := r.Head()
CheckIfError(err, "6")
commit, err := r.CommitObject(ref.Hash())
CheckIfError(err, "7")
fmt.Println(commit)
}
// Pull changes from a remote repository
func main() {
path := "/home/demo1/.deploy/repos/json"
// ssh-keyscan -H github.com >> /home/demo1/.deploy/known_hosts
err := os.Setenv("SSH_KNOWN_HOSTS", "/home/demo1/.deploy/known_hosts")
auth, err := GetAuth()
CheckIfError(err, "4")
// clone is working
/* r, err := git.PlainClone(path, false, &git.CloneOptions{
Auth: auth,
URL: "git@github.com:surjit/json.git",
Progress: os.Stdout,
Depth: 1,
})
CheckIfError(err, "1")
fmt.Printf("r %+v\n", r)
*/
// not working
pull(path, auth)
}
Metadata
Metadata
Assignees
Labels
No labels