How to use ssh method of gce Package

Best Syzkaller code snippet using gce.ssh

gce.go

Source:gce.go Github

copy

Full Screen

...47 GCE *gce.Context48 debug bool49 name string50 ip string51 gceKey string // per-instance private ssh key associated with the instance52 sshKey string // ssh key53 sshUser string54 closed chan bool55}56func ctor(env *vmimpl.Env) (vmimpl.Pool, error) {57 if env.Name == "" {58 return nil, fmt.Errorf("config param name is empty (required for GCE)")59 }60 cfg := &Config{61 Count: 1,62 }63 if err := config.LoadData(env.Config, cfg); err != nil {64 return nil, fmt.Errorf("failed to parse gce vm config: %v", err)65 }66 if cfg.Count < 1 || cfg.Count > 1000 {67 return nil, fmt.Errorf("invalid config param count: %v, want [1, 1000]", cfg.Count)68 }69 if env.Debug {70 cfg.Count = 171 }72 if cfg.Machine_Type == "" {73 return nil, fmt.Errorf("machine_type parameter is empty")74 }75 if cfg.GCE_Image == "" && cfg.GCS_Path == "" {76 return nil, fmt.Errorf("gcs_path parameter is empty")77 }78 if cfg.GCE_Image == "" && env.Image == "" {79 return nil, fmt.Errorf("config param image is empty (required for GCE)")80 }81 if cfg.GCE_Image != "" && env.Image != "" {82 return nil, fmt.Errorf("both image and gce_image are specified")83 }84 GCE, err := gce.NewContext()85 if err != nil {86 return nil, fmt.Errorf("failed to init gce: %v", err)87 }88 Logf(0, "GCE initialized: running on %v, internal IP %v, project %v, zone %v, net %v/%v",89 GCE.Instance, GCE.InternalIP, GCE.ProjectID, GCE.ZoneID, GCE.Network, GCE.Subnetwork)90 if cfg.GCE_Image == "" {91 cfg.GCE_Image = env.Name92 gcsImage := filepath.Join(cfg.GCS_Path, env.Name+"-image.tar.gz")93 Logf(0, "uploading image to %v...", gcsImage)94 if err := uploadImageToGCS(env.Image, gcsImage); err != nil {95 return nil, err96 }97 Logf(0, "creating GCE image %v...", cfg.GCE_Image)98 if err := GCE.DeleteImage(cfg.GCE_Image); err != nil {99 return nil, fmt.Errorf("failed to delete GCE image: %v", err)100 }101 if err := GCE.CreateImage(cfg.GCE_Image, gcsImage); err != nil {102 return nil, fmt.Errorf("failed to create GCE image: %v", err)103 }104 }105 pool := &Pool{106 cfg: cfg,107 env: env,108 GCE: GCE,109 }110 return pool, nil111}112func (pool *Pool) Count() int {113 return pool.cfg.Count114}115func (pool *Pool) Create(workdir string, index int) (vmimpl.Instance, error) {116 name := fmt.Sprintf("%v-%v", pool.env.Name, index)117 // Create SSH key for the instance.118 gceKey := filepath.Join(workdir, "key")119 keygen := osutil.Command("ssh-keygen", "-t", "rsa", "-b", "2048", "-N", "", "-C", "syzkaller", "-f", gceKey)120 if out, err := keygen.CombinedOutput(); err != nil {121 return nil, fmt.Errorf("failed to execute ssh-keygen: %v\n%s", err, out)122 }123 gceKeyPub, err := ioutil.ReadFile(gceKey + ".pub")124 if err != nil {125 return nil, fmt.Errorf("failed to read file: %v", err)126 }127 Logf(0, "deleting instance: %v", name)128 if err := pool.GCE.DeleteInstance(name, true); err != nil {129 return nil, err130 }131 Logf(0, "creating instance: %v", name)132 ip, err := pool.GCE.CreateInstance(name, pool.cfg.Machine_Type, pool.cfg.GCE_Image, string(gceKeyPub))133 if err != nil {134 return nil, err135 }136 ok := false137 defer func() {138 if !ok {139 pool.GCE.DeleteInstance(name, true)140 }141 }()142 sshKey := pool.env.SSHKey143 sshUser := pool.env.SSHUser144 if sshKey == "" {145 // Assuming image supports GCE ssh fanciness.146 sshKey = gceKey147 sshUser = "syzkaller"148 }149 Logf(0, "wait instance to boot: %v (%v)", name, ip)150 if err := pool.waitInstanceBoot(name, ip, sshKey, sshUser, gceKey); err != nil {151 return nil, err152 }153 ok = true154 inst := &instance{155 env: pool.env,156 cfg: pool.cfg,157 debug: pool.env.Debug,158 GCE: pool.GCE,159 name: name,160 ip: ip,161 gceKey: gceKey,162 sshKey: sshKey,163 sshUser: sshUser,164 closed: make(chan bool),165 }166 return inst, nil167}168func (inst *instance) Close() {169 close(inst.closed)170 inst.GCE.DeleteInstance(inst.name, false)171}172func (inst *instance) Forward(port int) (string, error) {173 return fmt.Sprintf("%v:%v", inst.GCE.InternalIP, port), nil174}175func (inst *instance) Copy(hostSrc string) (string, error) {176 vmDst := "./" + filepath.Base(hostSrc)177 args := append(sshArgs(inst.debug, inst.sshKey, "-P", 22), hostSrc, inst.sshUser+"@"+inst.ip+":"+vmDst)178 if _, err := runCmd(inst.debug, "scp", args...); err != nil {179 return "", err180 }181 return vmDst, nil182}183func (inst *instance) Run(timeout time.Duration, stop <-chan bool, command string) (<-chan []byte, <-chan error, error) {184 conRpipe, conWpipe, err := osutil.LongPipe()185 if err != nil {186 return nil, nil, err187 }188 conAddr := fmt.Sprintf("%v.%v.%v.syzkaller.port=1@ssh-serialport.googleapis.com",189 inst.GCE.ProjectID, inst.GCE.ZoneID, inst.name)190 conArgs := append(sshArgs(inst.debug, inst.gceKey, "-p", 9600), conAddr)191 con := osutil.Command("ssh", conArgs...)192 con.Env = []string{}193 con.Stdout = conWpipe194 con.Stderr = conWpipe195 if _, err := con.StdinPipe(); err != nil { // SSH would close connection on stdin EOF196 conRpipe.Close()197 conWpipe.Close()198 return nil, nil, err199 }200 if err := con.Start(); err != nil {201 conRpipe.Close()202 conWpipe.Close()203 return nil, nil, fmt.Errorf("failed to connect to console server: %v", err)204 }205 conWpipe.Close()206 var tee io.Writer207 if inst.debug {208 tee = os.Stdout209 }210 merger := vmimpl.NewOutputMerger(tee)211 var decoder func(data []byte) (int, int, []byte)212 if inst.env.OS == "windows" {213 decoder = kd.Decode214 }215 merger.AddDecoder("console", conRpipe, decoder)216 // We've started the console reading ssh command, but it has not necessary connected yet.217 // If we proceed to running the target command right away, we can miss part218 // of console output. During repro we can crash machines very quickly and219 // would miss beginning of a crash. Before ssh starts piping console output,220 // it usually prints:221 // "serialport: Connected to ... port 1 (session ID: ..., active connections: 1)"222 // So we wait for this line, or at least a minute and at least some output.223 {224 var output []byte225 timeout := time.NewTimer(time.Minute)226 connectedMsg := []byte("serialport: Connected")227 permissionDeniedMsg := []byte("Permission denied (publickey)")228 loop:229 for {230 select {231 case out := <-merger.Output:232 output = append(output, out...)233 if bytes.Contains(output, connectedMsg) {234 // Just to make sure (otherwise we still see trimmed reports).235 time.Sleep(5 * time.Second)236 break loop237 }238 if bytes.Contains(output, permissionDeniedMsg) {239 // This is a GCE bug.240 break loop241 }242 case <-timeout.C:243 break loop244 }245 }246 timeout.Stop()247 if len(output) == 0 || bytes.Contains(output, permissionDeniedMsg) {248 con.Process.Kill()249 merger.Wait()250 return nil, nil, fmt.Errorf("no output from console or permission denied")251 }252 }253 sshRpipe, sshWpipe, err := osutil.LongPipe()254 if err != nil {255 con.Process.Kill()256 merger.Wait()257 sshRpipe.Close()258 return nil, nil, err259 }260 if inst.env.OS == "linux" {261 if inst.sshUser != "root" {262 command = fmt.Sprintf("sudo bash -c '%v'", command)263 }264 }265 args := append(sshArgs(inst.debug, inst.sshKey, "-p", 22), inst.sshUser+"@"+inst.ip, command)266 ssh := osutil.Command("ssh", args...)267 ssh.Stdout = sshWpipe268 ssh.Stderr = sshWpipe269 if err := ssh.Start(); err != nil {270 con.Process.Kill()271 merger.Wait()272 sshRpipe.Close()273 sshWpipe.Close()274 return nil, nil, fmt.Errorf("failed to connect to instance: %v", err)275 }276 sshWpipe.Close()277 merger.Add("ssh", sshRpipe)278 errc := make(chan error, 1)279 signal := func(err error) {280 select {281 case errc <- err:282 default:283 }284 }285 go func() {286 select {287 case <-time.After(timeout):288 signal(vmimpl.ErrTimeout)289 case <-stop:290 signal(vmimpl.ErrTimeout)291 case <-inst.closed:292 signal(fmt.Errorf("instance closed"))293 case err := <-merger.Err:294 con.Process.Kill()295 ssh.Process.Kill()296 merger.Wait()297 con.Wait()298 if cmdErr := ssh.Wait(); cmdErr == nil {299 // If the command exited successfully, we got EOF error from merger.300 // But in this case no error has happened and the EOF is expected.301 err = nil302 } else if merr, ok := err.(vmimpl.MergerError); ok && merr.R == conRpipe {303 // Console connection must never fail. If it does, it's either304 // instance preemption or a GCE bug. In either case, not a kernel bug.305 Logf(1, "%v: gce console connection failed with %v", inst.name, merr.Err)306 err = vmimpl.ErrTimeout307 } else {308 // Check if the instance was terminated due to preemption or host maintenance.309 time.Sleep(5 * time.Second) // just to avoid any GCE races310 if !inst.GCE.IsInstanceRunning(inst.name) {311 Logf(1, "%v: ssh exited but instance is not running", inst.name)312 err = vmimpl.ErrTimeout313 }314 }315 signal(err)316 return317 }318 con.Process.Kill()319 ssh.Process.Kill()320 merger.Wait()321 con.Wait()322 ssh.Wait()323 }()324 return merger.Output, errc, nil325}326func (pool *Pool) waitInstanceBoot(name, ip, sshKey, sshUser, gceKey string) error {327 pwd := "pwd"328 if pool.env.OS == "windows" {329 pwd = "dir"330 }331 for startTime := time.Now(); time.Since(startTime) < 5*time.Minute; {332 if !vmimpl.SleepInterruptible(5 * time.Second) {333 return fmt.Errorf("shutdown in progress")334 }335 args := append(sshArgs(pool.env.Debug, sshKey, "-p", 22), sshUser+"@"+ip, pwd)336 if _, err := runCmd(pool.env.Debug, "ssh", args...); err == nil {337 return nil338 }339 }340 output, err := pool.getSerialPortOutput(name, gceKey)341 if err != nil {342 output = []byte(fmt.Sprintf("failed to get boot output: %v", err))343 }344 return vmimpl.BootError{"can't ssh into the instance", output}345}346func (pool *Pool) getSerialPortOutput(name, gceKey string) ([]byte, error) {347 conRpipe, conWpipe, err := osutil.LongPipe()348 if err != nil {349 return nil, err350 }351 defer conRpipe.Close()352 defer conWpipe.Close()353 conAddr := fmt.Sprintf("%v.%v.%v.syzkaller.port=1.replay-lines=10000@ssh-serialport.googleapis.com",354 pool.GCE.ProjectID, pool.GCE.ZoneID, name)355 conArgs := append(sshArgs(pool.env.Debug, gceKey, "-p", 9600), conAddr)356 con := osutil.Command("ssh", conArgs...)357 con.Env = []string{}358 con.Stdout = conWpipe359 con.Stderr = conWpipe360 if _, err := con.StdinPipe(); err != nil { // SSH would close connection on stdin EOF361 return nil, err362 }363 if err := con.Start(); err != nil {364 return nil, fmt.Errorf("failed to connect to console server: %v", err)365 }366 conWpipe.Close()367 done := make(chan bool)368 go func() {369 timeout := time.NewTimer(time.Minute)370 defer timeout.Stop()371 select {372 case <-done:373 case <-timeout.C:374 }375 con.Process.Kill()376 }()377 var output []byte378 buf := make([]byte, 64<<10)379 for {380 n, err := conRpipe.Read(buf)381 if err != nil || n == 0 {382 break383 }384 output = append(output, buf[:n]...)385 }386 close(done)387 con.Wait()388 return output, nil389}390func uploadImageToGCS(localImage, gcsImage string) error {391 GCS, err := gcs.NewClient()392 if err != nil {393 return fmt.Errorf("failed to create GCS client: %v", err)394 }395 defer GCS.Close()396 localReader, err := os.Open(localImage)397 if err != nil {398 return fmt.Errorf("failed to open image file: %v", err)399 }400 defer localReader.Close()401 localStat, err := localReader.Stat()402 if err != nil {403 return fmt.Errorf("failed to stat image file: %v", err)404 }405 gcsWriter, err := GCS.FileWriter(gcsImage)406 if err != nil {407 return fmt.Errorf("failed to upload image: %v", err)408 }409 defer gcsWriter.Close()410 gzipWriter := gzip.NewWriter(gcsWriter)411 tarWriter := tar.NewWriter(gzipWriter)412 tarHeader := &tar.Header{413 Name: "disk.raw",414 Typeflag: tar.TypeReg,415 Mode: 0640,416 Size: localStat.Size(),417 ModTime: time.Now(),418 // This is hacky but we actually need these large uids.419 // GCE understands only the old GNU tar format and420 // there is no direct way to force tar package to use GNU format.421 // But these large numbers force tar to switch to GNU format.422 Uid: 100000000,423 Gid: 100000000,424 Uname: "syzkaller",425 Gname: "syzkaller",426 }427 if err := tarWriter.WriteHeader(tarHeader); err != nil {428 return fmt.Errorf("failed to write image tar header: %v", err)429 }430 if _, err := io.Copy(tarWriter, localReader); err != nil {431 return fmt.Errorf("failed to write image file: %v", err)432 }433 if err := tarWriter.Close(); err != nil {434 return fmt.Errorf("failed to write image file: %v", err)435 }436 if err := gzipWriter.Close(); err != nil {437 return fmt.Errorf("failed to write image file: %v", err)438 }439 if err := gcsWriter.Close(); err != nil {440 return fmt.Errorf("failed to write image file: %v", err)441 }442 return nil443}444func runCmd(debug bool, bin string, args ...string) ([]byte, error) {445 if debug {446 Logf(0, "running command: %v %#v", bin, args)447 }448 output, err := osutil.RunCmd(time.Minute, "", bin, args...)449 if debug {450 Logf(0, "result: %v\n%s", err, output)451 }452 return output, err453}454func sshArgs(debug bool, sshKey, portArg string, port int) []string {455 args := []string{456 portArg, fmt.Sprint(port),457 "-i", sshKey,458 "-F", "/dev/null",459 "-o", "UserKnownHostsFile=/dev/null",460 "-o", "BatchMode=yes",461 "-o", "IdentitiesOnly=yes",462 "-o", "StrictHostKeyChecking=no",463 "-o", "ConnectTimeout=10",464 }465 if debug {466 args = append(args, "-v")467 }468 return args469}...

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 computeService, err := compute.NewService(ctx)5 if err != nil {6 fmt.Println("Error creating client: %v", err)7 }8 instanceDetails, err := computeService.Instances.Get(project, zone, instance).Do()9 if err != nil {10 fmt.Println("Error getting instance details: %v", err)11 }12 fmt.Println("ssh key: ", sshKey)13}

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2type GCE struct {3}4func (g *GCE) GetInstanceIP() string {5 if g.InstanceIP != "" {6 }7 cmd := exec.Command("gcloud", "compute", "instances", "describe", g.InstanceName, "--zone", g.Zone, "--format=flattened")8 stdout, err := cmd.StdoutPipe()9 if err != nil {10 log.Fatal(err)11 }12 if err := cmd.Start(); err != nil {13 log.Fatal(err)14 }15 b, err := ioutil.ReadAll(stdout)16 if err != nil {17 log.Fatal(err)18 }19 if err := cmd.Wait(); err != nil {20 log.Fatal(err)21 }22 lines := strings.Split(string(b), "23 for _, line := range lines {24 if strings.HasPrefix(line, "natIP:") {25 g.InstanceIP = strings.TrimSpace(strings.TrimPrefix(line, "natIP:"))26 }27 }28}29func (g *GCE) GetInstanceStatus() string {30 if g.InstanceStatus != "" {31 }32 cmd := exec.Command("gcloud", "compute", "instances", "describe", g.InstanceName, "--zone", g.Zone, "--format=flattened")33 stdout, err := cmd.StdoutPipe()34 if err != nil {35 log.Fatal(err)36 }37 if err := cmd.Start(); err != nil {38 log.Fatal(err)39 }40 b, err := ioutil.ReadAll(stdout)41 if err != nil {42 log.Fatal(err)43 }44 if err := cmd.Wait(); err != nil {45 log.Fatal(err)46 }

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 usr, err := user.Current()4 if err != nil {5 log.Fatal(err)6 }7 pubKey, err := os.ReadFile(usr.HomeDir + "/.ssh/id_rsa.pub")8 if err != nil {9 log.Fatal(err)10 }11 privKey, err := os.ReadFile(usr.HomeDir + "/.ssh/id_rsa")12 if err != nil {13 log.Fatal(err)14 }15 signers, err := ssh.ParsePrivateKey(privKey)16 if err != nil {17 log.Fatal(err)18 }19 sshConfig := &ssh.ClientConfig{20 Auth: []ssh.AuthMethod{21 ssh.PublicKeys(signers),22 },23 HostKeyCallback: ssh.InsecureIgnoreHostKey(),24 }25 sshConn, err := ssh.Dial("tcp", "

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 projectID, err := metadata.ProjectID()4 if err != nil {5 log.Fatal(err)6 }7 zone, err := metadata.Zone()8 if err != nil {9 log.Fatal(err)10 }11 instanceName, err := metadata.InstanceName()12 if err != nil {13 log.Fatal(err)14 }15 publicKey, err := metadata.Get("instance/attributes/publicKey")16 if err != nil {17 log.Fatal(err)18 }19 err = ioutil.WriteFile("publickey", []byte(publicKey), 0644)20 if err != nil {21 log.Fatal(err)22 }23 username, err := metadata.Get("instance/attributes/username")24 if err != nil {25 log.Fatal(err)26 }27 password, err := metadata.Get("instance/attributes/password")28 if err != nil {29 log.Fatal(err)30 }31 privateKey, err := metadata.Get("instance/attributes/privateKey")32 if err != nil {33 log.Fatal(err)34 }35 err = ioutil.WriteFile("privatekey", []byte(privateKey), 0644)36 if err != nil {37 log.Fatal(err)38 }39 ipAddress, err := metadata.Get("instance/network-interfaces/0/access-configs/0/external-ip")40 if err != nil {41 log.Fatal(err)42 }43 client := &http.Client{}44 publicKey, err = metadata.Get("instance/attributes/publicKey")45 if err != nil {46 log.Fatal(err)47 }48 err = ioutil.WriteFile("publickey", []byte(publicKey), 0644)49 if err != nil {50 log.Fatal(err)51 }

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client, err := gce.NewClient("service-account.json")4 if err != nil {5 panic(err)6 }7 instances, err := client.Instances.List("my-project-id")8 if err != nil {9 panic(err)10 }11 for _, instance := range instances {12 fmt.Println(instance.Name)13 }14}15import (16func main() {17 client, err := gce.NewClient("service-account.json")18 if err != nil {19 panic(err)20 }21 instance, err := client.Instances.Create("my-project-id", "my-instance-name", "us-central1-a", "debian-7")22 if err != nil {23 panic(err)24 }25 fmt.Println(instance.Name)26}27import (28func main() {29 client, err := gce.NewClient("service-account.json")30 if err != nil {31 panic(err)32 }33 instance, err := client.Instances.Create("my-project-id", "my-instance-name", "us-central1-a", "debian-7")34 if err != nil {35 panic(err)36 }37 fmt.Println(instance.Name)38}39import (40func main() {41 client, err := gce.NewClient("service-account.json")42 if err != nil {43 panic(err)44 }

Full Screen

Full Screen

ssh

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, world.")4}5import (6func main() {7 fmt.Println("Hello, world.")8}9import (10func main() {11 fmt.Println("Hello, world.")12}13import (14func main() {15 fmt.Println("Hello, world.")16}17import (18func main() {19 fmt.Println("Hello, world.")20}21import (22func main() {23 fmt.Println("Hello, world.")24}25import (26func main() {27 fmt.Println("Hello, world.")28}29import (30func main() {31 fmt.Println("Hello, world.")32}33import (34func main() {35 fmt.Println("Hello, world.")36}37import (38func main() {39 fmt.Println("Hello, world.")40}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful