How to connect to client in GCE in GO - go

I can't able to connect to client. Is there any way to pass private key id and private key to client for get authorized?
So, far i see:
ctx := context.Background()
client, err := google.DefaultClient(ctx, compute.ComputeScope)
if err != nil {
//...
}
computeService, err := compute.New(client)
if err != nil {
//...
}

Firstly, Need to create a credential for service account in GCE and it will download a json file and it will use for authorize the client.
Sample Code :
data, err := ioutil.ReadFile("downloadedfile.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(data, compute.ComputeScope) // give the specific permission for this client.
if err != nil {
log.Fatal(err)
}
client = conf.Client(oauth2.NoContext)
computeService, err := compute.New(client)
if err != nil {
//...
}

Related

How to use kubernetes go-client on amazon eks service?

I've been looking for documentation for a long time and still couldn't find any clear connection procedure.
I came up with this code sample :
package aws
import (
"fmt"
"net/http"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/joho/godotenv"
)
func Connect() {
godotenv.Load(".env")
session := session.Must(session.NewSession())
svc := eks.New(session)
clusters, err := svc.ListClusters(&eks.ListClustersInput{})
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(clusters)
}
i mean, this still returns a 403 forbidden error because of env variable mess, but the code is valid i guess. My question is, having this connection established : how to convert this svc variable into the *kubernetes.Clientset one from the go driver ?
Have you had a look at the client-go example on how to authenticate in-cluster?
Code that authenticate to the Kubernetes API typically start like this:
// creates the in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
I use the following code to automatically detect where its running from local machine or any kubernetes cluster.
var config *rest.Config
if _, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token"); err == nil {
config, err = rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
} else if os.IsNotExist(err) {
config, err = clientcmd.BuildConfigFromFlags("", *kubeConfig)
if err != nil {
log.Fatal("No serviceaccount mounted or -kubeconfig flag passed or .kube/config file \n " ,err)
}
}
// Create an rest client not targeting specific API version
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}

Is the output from ssh guaranteed to be retrieved?

I use the ssh package to connect to a Linux server and retrieve the output of commands. The helper function I wrote for that is below:
func sshRunCommand(host string, command string) (output string, err error) {
keyData, err := ioutil.ReadFile("srv.private.openssh")
if err != nil {
return "", err
}
key, err := ssh.ParsePrivateKey(keyData)
if err != nil {
return "", err
}
// Authentication
config := &ssh.ClientConfig{
User: "root",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
// Connect
client, err := ssh.Dial("tcp", net.JoinHostPort(host, "22"), config)
if err != nil {
return "", err
}
// Create a session. It is one session per command.
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b // 👈 this is the place I am concerned with
// Finally, run the command
err = session.Run(command)
return b.String(), err
}
This command usually works fine: it always connects but randomly does not return the output.
Before going further in my investigations, I wanted to make sure that the output buffer is flushed before returning the output. Is this the case?
In this use-case/issue, you can see stdout and stderr being linked to the same buffer.
See if that helps in your case.
sess, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer sess.Close()
stdin, err := sess.StdinPipe()
if err != nil {
log.Fatal(err)
}
var b bytes.Buffer
sess.Stdout = &b
sess.Stderr = &b
err = sess.Shell()
if err != nil {
log.Fatal(err)
}
...
_, err = fmt.Fprintf(stdin, "%s\n", cmd)

Go SMB2 , reading and listing directory

I'm trying to list directory contents on a share from Linux to Windows using Go.
So far I've managed to Create/Remove new files inside a share with full Read/Write permissions.
Go module: https://godoc.org/github.com/hirochachacha/go-smb2#Client
Functions:
func connect_client(host string, share string, session map[string]string) *smb2.Client {
//Checks for a connection on port
conn, err := net.Dial("tcp", host+":445")
if err != nil {
panic(err)
}
//smb auth
d := &smb2.Dialer{
Initiator: &smb2.NTLMInitiator{
User: session["Username"],
Password: session["Password"],
Domain: session["Domain"],
},
}
//Returns a client session
client, err := d.Dial(conn)
if err != nil {
fmt.Println("Connection failed")
client.Logoff()
} else {
fmt.Println("Connection Succeeded")
}
return client
}
func check_write(host string, client *smb2.Client) {
file := "asdasdas.txt"
fs, err := client.Mount(host)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
defer fs.Umount()
share := strings.Split(host, `\\`)
f, err := fs.Create(file)
if err != nil {
fmt.Println("You do not have write permissions on directory:%s ! \n", strings.Split(share[1], `\`)[1])
os.Exit(0)
}
defer fs.Remove(file)
defer f.Close()
fmt.Printf("You have write permissions to directory: %s \n", strings.Split(share[1], `\`)[1]))
}
func list_all(client *smb2.Client, host string) {
fs, err := client.Mount(host)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
defer fs.Umount()
_, err = fs.Open(`Test.txt`)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
}
func main() {
host, share, action, session := get_flags()
client := connect_client(host, share, session)
full_host := `\\` + host + `\` + share
//File create
if action == "check_write" {
check_write(full_host, client)
}
if action == "list_files" {
list_all(client, full_host)
}
}
In the function list_all() everything works, but when I am trying to access \\192.168.1.19\Sharing only..
When I input just a host with directory name it seas it can not list the directory path because it can not find the object specified.
I can't understand how I can get pointer used for *RemoteFile in order to use the functions:
f.Readdir()
f.Name()
etc....
So far I managed to use *RemoteFileSystem only for all other actions but I want to list all contents of the directory..
Help would be much appreciated!
Edit:
If it wasn't clear enough, in order to use functions like:
f.Readdir()
f.Name()
I need to get a pointer for *RemoteFile, this is my main issue
https://godoc.org/github.com/hirochachacha/go-smb2#RemoteFileSystem.Open
Use Open on a RemoteFileSystem and either a directory name, or empty string for the directory at the root of the filesystem.
e.g.
client, err := d.Dial(conn)
if err != nil {
return err
}
rfs, err := client.Mount("jrwren")
if err != nil {
return err
}
// cat the NOTES file.
f, err := rfs.Open("NOTES")
if err != nil {
return err
}
defer f.Close()
io.Copy(os.Stdout, f)
// List all the files
dir, err := rfs.Open("")
if err != nil {
return err
}
fis, err := dir.Readdir(10)
if err != nil {
return err
}
for i := range fis {
fmt.Println(fis[i].Name())
}
func list_all(client *smb2.Client, host string) {
fs, err := client.Mount(host)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
dir, err := fs.Open("")
if err != nil {
fmt.Println(err)
os.Exit(0)
}
fis, err := dir.Readdir(-1)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
for i := range fis {
fmt.Println(fis[i].Name())
}
}
This would be the answer thank you!

BOX / JWT OAuth 2.0 by golang

I want to upload image from my server without user. I made box application and setting.
I try to create JWT token and got access token. after that, I try to get file information from my Box file. but this api return 404 status.
I don't know where I missed. If you know, please help me.
My code is follow as.
package main
import (
"fmt"
"io/ioutil"
"time"
"encoding/json"
"github.com/dgrijalva/jwt-go"
"net/http"
"net/url"
"strings"
)
type BoxToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RestrictedTo []string `json:"restricted_to"`
TokenType string `json:"token_type"`
}
func main() {
token := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.MapClaims{
"iss": "application client id",
"sub": "enterprise id",
"box_sub_type": "enterprise",
"aud": "https://api.box.com/oauth2/token",
"jti": "unique id",
"exp": time.Now().Unix() + 60,
})
token.Header["kid"] = "public key id"
privateKeyData, err := ioutil.ReadFile("private.key")
if err != nil {
panic(err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyData)
if err != nil {
panic(err)
}
// Generate encoded token and send it as response.
tokenStr, err := token.SignedString(key)
if err != nil {
panic(err)
}
//fmt.Println(tokenStr)
values := url.Values{}
values.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")
values.Add("client_id", "application client id")
values.Add("client_secret", "application client secret")
values.Add("assertion", tokenStr)
req, err := http.NewRequest(http.MethodPost, "https://api.box.com/oauth2/token", strings.NewReader(values.Encode()))
if err != nil {
panic(err)
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.StatusCode)
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var boxToken BoxToken
if err := json.Unmarshal(responseBody, &boxToken); err != nil {
panic(err)
}
req2, err := http.NewRequest("GET", "https://api.box.com/2.0/files/FILE_ID?fields=id,name", nil)
if err != nil {
panic(err)
}
req2.Header.Add("Authorization", `Bearer `+boxToken.AccessToken)
resp2, err := client.Do(req2)
if err != nil {
panic(err)
}
defer resp2.Body.Close()
fmt.Println(resp2.StatusCode)
responseBody2, err := ioutil.ReadAll(resp2.Body)
if err != nil {
panic(err)
}
fmt.Println(string(responseBody2))
}
and standard output is
404
{"type":"error","status":404,"code":"not_found","context_info":{"errors":[{"reason":"invalid_parameter","name":"item","message":"Invalid value 'f_${FILE_ID}'. 'item' with value 'f_${FILE_ID}' not found"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Not Found","request_id":"3de39rftkndh2qqn"}
I believe that you need to actually pass an actual file id in place of "FILE_ID" in:
req2, err := http.NewRequest("GET", "https://api.box.com/2.0/files/FILE_ID?fields=id,name", nil)
Based on reading the API Reference

How to pull image from custom docker registry with golang?

Using docker sources how to pull image from custom registry? As a result of using such code
// Prepare auth registry for usage
func (app *App) PrepareRegistry() error {
app.AuthConfig = types.AuthConfig{
Username: Username,
Password: Password,
ServerAddress: DefaultServer,
}
resp, err := app.Client.RegistryLogin(context.Background(), app.AuthConfig)
if err != nil {
panic(err)
}
fmt.Println(resp.Status)
if resp.IdentityToken != "" {
app.AuthConfig.IdentityToken = resp.IdentityToken
}
app.AuthConfigEncoded, err = command.EncodeAuthToBase64(app.AuthConfig)
return err
}
func (app *App) ImagePull() error {
opts := types.ImagePullOptions{
All: true,
RegistryAuth: app.AuthConfigEncoded,
PrivilegeFunc: registryAuthentication(app.Name),
}
responseBody, err := app.Client.ImagePull(context.Background(), app.Name, opts)
defer responseBody.Close()
if err != nil {
return err
}
return nil
}
I am still getting the error
Login Succeeded
panic: Error response from daemon: Get https://registry-1.docker.io/v2/shalakhin/blender/tags/list: unauthorized: incorrect username or password
While ServerAddress is registry.gitlab.com, not registry-1.docker.io
Did you check identity token? That might cause an authentication problem.
A suggestion:
Docker client
This works fine, as I can see you did not specify the endpoint. I think you should add this info.
authConfig := types.AuthConfig{
Username: "username",
Password: "password",
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
panic(err)
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{RegistryAuth: authStr})
if err != nil {
panic(err)
}

Resources