コード例 #1
0
func main() {
	flag.Parse()

	if *username == "" {
		fmt.Printf("Enter a valid username: "******"<get-system-information/>"))
	if err != nil {
		panic(err)
	}
	var q SystemInformation

	xml.Unmarshal([]byte(reply.RawReply), &q)
	fmt.Printf("hostname: %s\n", q.HostName)
	fmt.Printf("model: %s\n", q.HardwareModel)
	fmt.Printf("version: %s\n", q.OsVersion)
}
コード例 #2
0
ファイル: ssh_example1.go プロジェクト: Juniper/go-netconf
func main() {
	sshConfig := &ssh.ClientConfig{
		Config: ssh.Config{
			Ciphers: []string{"aes128-cbc", "hmac-sha1"},
		},
		User: "******",
		Auth: []ssh.AuthMethod{ssh.Password("mypass")},
	}

	s, err := netconf.DialSSH("1.1.1.1", sshConfig)

	if err != nil {
		log.Fatal(err)
	}

	defer s.Close()

	fmt.Println(s.ServerCapabilities)
	fmt.Println(s.SessionID)

	// Sends raw XML
	reply, err := s.Exec(netconf.RawMethod("<get-chassis-inventory/>"))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Reply: %+v", reply)
}
コード例 #3
0
ファイル: ssh_example.go プロジェクト: nashtsai/go-netconf
func main() {
	username := flag.String("username", "", "User to login with")
	password := flag.String("password", "", "Password to login with")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [flags] targets...\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(2)
	}

	flag.Parse()

	if flag.NArg() == 0 {
		flag.Usage()
	}

	s, err := netconf.DialSSH(flag.Arg(0),
		netconf.SSHConfigPassword(*username, *password))
	if err != nil {
		panic(err)
	}

	defer s.Close()

	fmt.Printf("Server Capabilities: '%+v'\n", s.ServerCapabilities)
	fmt.Printf("Session Id: %d\n\n", s.SessionID)

	//reply, err := s.Exec([]byte("<rpc><get-config><source><running/></source></get-config></rpc>"))
	reply, err := s.ExecRPC(netconf.RPCGetConfig("running"))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Reply: %+v", reply)

}
コード例 #4
0
ファイル: junos_agent.go プロジェクト: RobWC/jmcom
// dial connect to host
func (a *JunosAgent) dial() error {
	var err error
	if a.HostProfile.Username != "" && len(a.HostProfile.GetSSHClientConfig().Auth) > 0 {
		a.Session, err = netconf.DialSSH(a.HostProfile.Host, a.HostProfile.GetSSHClientConfig())
		if err != nil {
			return err
		}
		a.SessionID = a.Session.SessionID
		return nil
	}
	err = errors.New("Host Profile incorrectly defined")
	return err
}
コード例 #5
0
func (zr *ChassisZonesRequest) Run(count int, replyChan chan<- *netconf.RPCReply) {

	go func() {
		ticker := time.NewTicker(zr.Interval)

		for {
			select {
			case <-ticker.C:
				// Get SSH/NETCONF session going for use throughout the life of this request.
				if s, err := netconf.DialSSH(zr.LoopBackIP.String(),
					netconf.SSHConfigPassword(zr.UserName, zr.Password)); err != nil {
					log.Errorln(err)
					s.Close()
					close(replyChan)
				} else if ncReply, err := s.Exec(zr.Method()); err != nil {
					log.Errorln(err)
					s.Close()
					close(replyChan)
				} else {
					s.Close()
					replyChan <- ncReply
				}

				count--
				if count < 0 {
					break
				}
			}
		}
	}()

	/*		cfg := config.GetConfig()

			file, err := os.Create(cfg.ChassisZonesResultsFile)

			if err != nil {
				log.Fatalln(err)
			}

			for _ = range ticker.C {
				if ncReply, err := s.Exec(zr.Method()); err != nil {
					log.Error(err)
				} else if chassisEnvResp, err := response.NewChassisEnvResponse(&ncReply.Data); err != nil {
					log.Error(err)
				} else {
					chassisEnvResp.WriteCSV(file)
				}
			}*/
}
コード例 #6
0
func main() {

	rawMethod := netconf.RawMethod("<traceroute><host>8.8.8.8</host></traceroute>")
	s := new(netconf.Session)
	var err error

	if s, err = netconf.DialSSH("192.168.1.1", netconf.SSHConfigPassword("username", "password")); err != nil {
		log.Fatal(err)
	} else {
		defer s.Close()
	}

	tr := new(traceroute.TraceRoute)
	if ncReply, err := s.Exec(rawMethod); err != nil {
		log.Fatal(err)
	} else if _, err := tr.ReadXMLFrom(bytes.NewBuffer([]byte(ncReply.Data))); err != nil {
		log.Fatal(err)
	} else {
		tr.WriteCLITo(os.Stdout)
	}
}
コード例 #7
0
ファイル: test.go プロジェクト: RobWC/jmcom
func foo() {
	username := "******"
	password := "******"
	host := "172.19.100.49"

	s, err := netconf.DialSSH(host, netconf.SSHConfigPassword(username, password))
	if err != nil {
		panic(err)
	}

	defer s.Close()

	fmt.Printf("Session Id: %d\n\n", s.SessionID)

	reply, err := s.Exec(netconf.RawMethod("<command format=\"ascii\">show version</command>"))
	if err != nil {
		panic(err)
	}
	p := &Parser{}
	v := p.Trim(reply.Data)
	fmt.Println("REPLY START")
	fmt.Printf("%s", v)
	fmt.Println("REPLY END")
}
コード例 #8
0
ファイル: gohan_remote.go プロジェクト: gitter-badger/gohan
//SetUp sets up vm to with environment
func init() {
	gohanRemoteInit := func(env *Environment) {
		vm := env.VM

		builtins := map[string]interface{}{
			"gohan_netconf_open": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 2 {
					panic("Wrong number of arguments in gohan_netconf_open call.")
				}
				rawHost, _ := call.Argument(0).Export()
				host, ok := rawHost.(string)
				if !ok {
					return otto.NullValue()
				}
				rawUserName, _ := call.Argument(1).Export()
				userName, ok := rawUserName.(string)
				if !ok {
					return otto.NullValue()
				}
				config := util.GetConfig()
				publicKeyFile := config.GetString("ssh/key_file", "")
				if publicKeyFile == "" {
					return otto.NullValue()
				}
				sshConfig := &ssh.ClientConfig{
					User: userName,
					Auth: []ssh.AuthMethod{
						util.PublicKeyFile(publicKeyFile),
					},
				}
				s, err := netconf.DialSSH(host, sshConfig)

				if err != nil {
					ThrowOttoException(&call, "Error during gohan_netconf_open: %s", err.Error())
				}
				value, _ := vm.ToValue(s)
				return value
			},
			"gohan_netconf_close": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 1 {
					panic("Wrong number of arguments in gohan_netconf_close call.")
				}
				rawSession, _ := call.Argument(0).Export()
				s, ok := rawSession.(*netconf.Session)
				if !ok {
					ThrowOttoException(&call, "Error during gohan_netconf_close")
				}
				s.Close()
				return otto.NullValue()
			},
			"gohan_netconf_exec": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 2 {
					panic("Wrong number of arguments in gohan_netconf_exec call.")
				}
				rawSession, _ := call.Argument(0).Export()
				s, ok := rawSession.(*netconf.Session)
				if !ok {
					return otto.NullValue()
				}
				rawCommand, _ := call.Argument(1).Export()
				command, ok := rawCommand.(string)
				if !ok {
					return otto.NullValue()
				}
				reply, err := s.Exec(netconf.RawMethod(command))
				resp := map[string]interface{}{}
				if err != nil {
					resp["status"] = "error"
					resp["output"] = err.Error()
				} else {
					resp["status"] = "success"
					resp["output"] = reply
				}
				value, _ := vm.ToValue(resp)
				return value
			},
			"gohan_ssh_open": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 2 {
					panic("Wrong number of arguments in gohan_netconf_open call.")
				}
				rawHost, _ := call.Argument(0).Export()
				host, ok := rawHost.(string)
				if !ok {
					return otto.NullValue()
				}
				rawUserName, _ := call.Argument(1).Export()
				userName, ok := rawUserName.(string)
				if !ok {
					return otto.NullValue()
				}
				config := util.GetConfig()
				publicKeyFile := config.GetString("ssh/key_file", "")
				if publicKeyFile == "" {
					return otto.NullValue()
				}
				sshConfig := &ssh.ClientConfig{
					User: userName,
					Auth: []ssh.AuthMethod{
						util.PublicKeyFile(publicKeyFile),
					},
				}
				conn, err := ssh.Dial("tcp", host, sshConfig)
				if err != nil {
					ThrowOttoException(&call, "Error during gohan_ssh_open %s", err)
				}
				session, err := conn.NewSession()
				if err != nil {
					ThrowOttoException(&call, "Error during gohan_ssh_open %s", err)
				}
				value, _ := vm.ToValue(session)
				return value
			},
			"gohan_ssh_close": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 1 {
					panic("Wrong number of arguments in gohan_netconf_close call.")
				}
				rawSession, _ := call.Argument(0).Export()
				s, ok := rawSession.(*ssh.Session)
				if !ok {
					ThrowOttoException(&call, "Error during gohan_ssh_close")
				}
				s.Close()
				return otto.NullValue()
			},
			"gohan_ssh_exec": func(call otto.FunctionCall) otto.Value {
				if len(call.ArgumentList) != 2 {
					panic("Wrong number of arguments in gohan_netconf_exec call.")
				}
				rawSession, _ := call.Argument(0).Export()
				s, ok := rawSession.(*ssh.Session)
				if !ok {
					return otto.NullValue()
				}
				rawCommand, _ := call.Argument(1).Export()
				command, ok := rawCommand.(string)
				if !ok {
					return otto.NullValue()
				}
				var stdoutBuf bytes.Buffer
				s.Stdout = &stdoutBuf
				err := s.Run(command)
				resp := map[string]interface{}{}
				if err != nil {
					resp["status"] = "error"
					resp["output"] = err.Error()
				} else {
					resp["status"] = "success"
					resp["output"] = stdoutBuf.String()
				}
				value, _ := vm.ToValue(resp)
				return value
			},
		}
		for name, object := range builtins {
			vm.Set(name, object)
		}
	}
	RegistInit(gohanRemoteInit)
}
コード例 #9
0
func (cer *ChassisEnvCmd) Run() (<-chan *netconf.RPCReply, <-chan error) {

	replyChan := make(chan *netconf.RPCReply)
	errChan := make(chan error)

	go func() {
		const thisFunc = "*ChassisEnvCmd.Run()"
		cntxLog := log.WithFields(log.Fields{
			"func":     thisFunc,
			"deadline": cer.Deadline,
			"interval": cer.Interval,
			"username": cer.UserName,
			"ip":       cer.LoopBackIP,
		})

		cntxLog.Debugln("Starting")

		// Flag for breaking loop
		done := false

		// Use a ticker to notify us when it's time to execute the command again.
		ticker := time.NewTicker(cer.Interval)
		// Use time.After to let us know when we've reached our deadline.
		deadline := time.After(cer.Deadline)

		for !done {
			select {
			case <-ticker.C:
				cntxLog.Debugln("dialing SSH")
				if s, err := netconf.DialSSH(cer.LoopBackIP.String(),
					netconf.SSHConfigPassword(cer.UserName, cer.Password)); err != nil {
					cntxLog.Debugln(err)
					errChan <- &RunError{
						Method:    thisFunc,
						ClientErr: fmt.Sprintf("could not dial %s via NETCONF over SSH", cer.LoopBackIP.String()),
						Err:       err,
						Cmd:       cer,
					}
				} else if ncReply, err := s.Exec(cer.Method()); err != nil {
					cntxLog.Debugln(err)
					s.Close()
					errChan <- &RunError{
						Method:    thisFunc,
						ClientErr: fmt.Sprintf("could not execute show chassis enviornment command"),
					}
				} else {
					s.Close()
					replyChan <- ncReply
				}
			case <-deadline:
				cntxLog.Debugln("deadline reached")
				close(replyChan)
				close(errChan)
				done = true
			case <-cer.cancelled:
				cntxLog.Debugln("command cancelled")
				close(replyChan)
				close(errChan)
				done = true
			}
		}

		cntxLog.Debugln("Exiting")
	}()

	return replyChan, errChan
}