示例#1
0
文件: ssh.go 项目: reth-/mole
func sshOnConn(conn net.Conn, h conf.Host) (*ssh.ClientConn, error) {
	var auths []ssh.ClientAuth

	if h.Pass != "" {
		auths = append(auths, ssh.ClientAuthPassword(password(h.Pass)))
		auths = append(auths, ssh.ClientAuthKeyboardInteractive(challenge(h.Pass)))
	}

	if h.Key != "" {
		k := &keyring{}
		err := k.loadPEM([]byte(h.Key))
		if err != nil {
			return nil, err
		}
		auths = append(auths, ssh.ClientAuthKeyring(k))
	}

	config := &ssh.ClientConfig{
		User: h.User,
		Auth: auths,
	}

	debugln("handshake & authenticate")
	client, err := ssh.Client(conn, config)
	if err != nil {
		return nil, err
	}
	return client, nil
}
示例#2
0
func (d *ESX5Driver) connect() error {
	address := fmt.Sprintf("%s:%d", d.Host, d.Port)

	auth := []gossh.ClientAuth{
		gossh.ClientAuthPassword(ssh.Password(d.Password)),
		gossh.ClientAuthKeyboardInteractive(
			ssh.PasswordKeyboardInteractive(d.Password)),
	}

	// TODO(dougm) KeyPath support
	sshConfig := &ssh.Config{
		Connection: ssh.ConnectFunc("tcp", address),
		SSHConfig: &gossh.ClientConfig{
			User: d.Username,
			Auth: auth,
		},
		NoPty: true,
	}

	comm, err := ssh.New(sshConfig)
	if err != nil {
		return err
	}

	d.comm = comm
	return nil
}
示例#3
0
func TestNew_Invalid(t *testing.T) {
	clientConfig := &ssh.ClientConfig{
		User: "******",
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password("i-am-invalid")),
		},
	}

	conn := func() (net.Conn, error) {
		conn, err := net.Dial("tcp", newMockLineServer(t))
		if err != nil {
			t.Fatalf("unable to dial to remote side: %s", err)
		}
		return conn, err
	}

	config := &Config{
		Connection: conn,
		SSHConfig:  clientConfig,
	}

	_, err := New(config)
	if err == nil {
		t.Fatal("should have had an error connecting")
	}
}
示例#4
0
func TestStart(t *testing.T) {
	clientConfig := &ssh.ClientConfig{
		User: "******",
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password("pass")),
		},
	}

	conn := func() (net.Conn, error) {
		conn, err := net.Dial("tcp", newMockLineServer(t))
		if err != nil {
			t.Fatalf("unable to dial to remote side: %s", err)
		}
		return conn, err
	}

	config := &Config{
		Connection: conn,
		SSHConfig:  clientConfig,
	}

	client, err := New(config)
	if err != nil {
		t.Fatalf("error connecting to SSH: %s", err)
	}

	var cmd packer.RemoteCmd
	stdout := new(bytes.Buffer)
	cmd.Command = "echo foo"
	cmd.Stdout = stdout

	client.Start(&cmd)
}
示例#5
0
func (h *RemoteHelper) Init(username, password string) {
	h.config = &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(clientPassword(password)),
		},
	}
}
示例#6
0
// SSHConfigPassword is a convience function that takes a username and password
// and returns a new ssh.ClientConfig setup to pass that username and password.
func SSHConfigPassword(user string, pass string) *ssh.ClientConfig {
	return &ssh.ClientConfig{
		User: user,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(simpleSSHPassword(pass)),
		},
	}
}
示例#7
0
func ScpHaproxyConf(appConf config.ConfigInfo) (errinfo error) {

	server := fmt.Sprintf("%s:%d", appConf.SlaveServerIp, appConf.SlaveServerSSHPort)
	username := appConf.SlaveRemoteUser
	password := clientPassword(appConf.SlaveRemotePasswd)

	// An SSH client is represented with a slete). Currently only
	// the "password" authentication method is supported.
	//
	// To authenticate with the remote server you must pass at least one
	// implementation of ClientAuth via the Auth field in ClientConfig.

	conf := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			// ClientAuthPassword wraps a ClientPassword implementation
			// in a type that implements ClientAuth.
			ssh.ClientAuthPassword(password),
		},
	}
	client, err := ssh.Dial("tcp", server, conf)
	if err != nil {
		errinfo = errors.New(fmt.Sprintf("Failed to dial: %s", err.Error()))
		return
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	defer client.Close()
	// Create a session
	session, err := client.NewSession()
	if err != nil {
		errinfo = errors.New(fmt.Sprintf("unable to create session: %s", err.Error()))
		return
	}
	defer session.Close()

	confBytes, err := ioutil.ReadFile(appConf.NewHAProxyConfPath)
	if err != nil {
		errinfo = errors.New(fmt.Sprintf("Failed to run: %s", err.Error()))
		return
	}
	content := string(confBytes)
	go func() {
		w, _ := session.StdinPipe()
		defer w.Close()
		fmt.Fprintln(w, "C0644", len(content), "new_conf")
		fmt.Fprint(w, content)
		fmt.Fprint(w, "\x00")
	}()
	cmd := fmt.Sprintf("%s -tq %s && %s", appConf.ScpCommandPath, appConf.SlaveConf, appConf.SlaveRestartScript)
	if err := session.Run(cmd); err != nil {
		errinfo = errors.New(fmt.Sprintf("Failed to run: %s", err.Error()))
		return
	}
	return
}
示例#8
0
func main() {
	flag.Parse()

	config := &ssh.ClientConfig{
		User: *sshuser,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password(*sshpass)),
		},
	}
	conn, err := ssh.Dial("tcp", *sshhost+":22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}

	log.Println("connected to ssh server")
	defer conn.Close()

	http.HandleFunc("/", home)
	if *debug {
		http.HandleFunc("/resend", resend)
	}
	http.Handle("/stream", websocket.Handler(streamMail))

	sln, err := conn.Listen("tcp", *smtpListen)
	if err != nil {
		log.Fatalf("error listening for SMTP: %v", err)
	}

	hln, err := conn.Listen("tcp", *webListen)
	if err != nil {
		log.Fatalf("error listening for HTTP: %v", err)
	}
	log.Printf("websomtep listening for HTTP on %q and SMTP on %q\n", *webListen, *smtpListen)
	go http.Serve(hln, nil)

	s := &smtpd.Server{
		OnNewMail: func(c smtpd.Connection, from smtpd.MailAddress) (smtpd.Envelope, error) {
			log.Printf("New message from %q", from)
			e := &Message{
				From: from.Email(),
			}
			return e, nil
		},
	}

	smtpCountListener := &countingListener{
		Listener: sln,
		fn: func(count int) {
			broadcast(&Message{msg: &SMTPStat{NumSenders: count}})
		},
	}

	err = s.Serve(smtpCountListener)
	if err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}
示例#9
0
func exec(server, username, password, cmd string, c chan Results) {
	// To authenticate with the remote server you must pass at least one
	// implementation of ClientAuth via the Auth field in ClientConfig.
	// Currently only the "password" authentication method is supported.

	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			// ClientAuthPassword wraps a ClientPassword implementation
			// in a type that implements ClientAuth.
			ssh.ClientAuthPassword(clientPassword(password)),
		},
	}
	client, err := ssh.Dial("tcp", server, config)
	if err != nil {
		err = errors.New("Failed to dial: " + err.Error())
		c <- Results{err: err}
		return
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	defer client.Close()

	// Create a session
	session, err := client.NewSession()
	if err != nil {
		c <- Results{err: err}
		return
	}
	defer session.Close()

	// Set up terminal modes
	modes := ssh.TerminalModes{
		ssh.ECHO:          0,     // disable echoing
		ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		err := errors.New("request for pseudo terminal failed: " + err.Error())
		c <- Results{err: err}
		return
	}

	var stdout, stderr bytes.Buffer
	session.Stdout = &stdout
	session.Stderr = &stderr
	rc := 0
	if err := session.Run(cmd); err != nil {
		if ugh, ok := err.(*ssh.ExitError); ok {
			rc = ugh.Waitmsg.ExitStatus()
		}
	}
	c <- Results{nil, rc, stdout.String(), stderr.String()}
}
示例#10
0
func Connect(server string, user string, pwd string) (*ssh.ClientConn, error) {
	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(clientPassword(pwd)),
			//TODO ssh.ClientAuthKeyring(clientKey),
		},
	}
	return ssh.Dial("tcp", server, config)
}
示例#11
0
文件: ssh.go 项目: robinbowes/packer
func sshConfig(state map[string]interface{}) (*gossh.ClientConfig, error) {
	config := state["config"].(*config)

	return &gossh.ClientConfig{
		User: config.SSHUser,
		Auth: []gossh.ClientAuth{
			gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)),
			gossh.ClientAuthKeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.SSHPassword)),
		},
	}, nil
}
示例#12
0
func (ss *ScpStorage) Connect() error {
	var err error

	clientConfig := &ssh.ClientConfig{
		User: ss.User,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password(ss.Password)),
			ssh.ClientAuthKeyring(ss.Keychain),
		},
	}

	ss.connexion, err = ssh.Dial("tcp", ss.Endpoint, clientConfig)
	if err != nil {
		return fmt.Errorf("Failed to dial: %s", err.Error())
	}

	return nil
}
示例#13
0
func main() {

	fmt.Printf("Please enter a username: "******"password" authentication method is supported.
	//
	// To authenticate with the remote server you must pass at least one
	// implementation of ClientAuth via the Auth field in ClientConfig.
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			// ClientAuthPassword wraps a ClientPassword implementation
			// in a type that implements ClientAuth.
			ssh.ClientAuthPassword(userPass(username)),
		},
	}

	client, err := ssh.Dial("tcp", server+":22", config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()

	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/uname"); err != nil {
		panic("Failed to run: " + err.Error())
	}

	fmt.Println(b.String())
}
示例#14
0
文件: ssh.go 项目: carriercomm/sky-1
// SSH logic
func (c *SSHConn) Connect(host, user string) error {
	c.host = host
	c.user = user

	config := &ssh.ClientConfig{
		User: c.user,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(c),
		},
	}

	var err error
	c.client, err = ssh.Dial("tcp", c.host, config)
	if err != nil {
		return err
	}

	return nil
}
示例#15
0
func main() {
	config := &ssh.ClientConfig{
		User: *USER,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password(*PASS)),
		},
	}

	log.Println("Starting ... ")
	t1 := time.Now()
	var conns sync.WaitGroup
	conns.Add(*CONNS)
	for i := 0; i < *CONNS; i++ {
		go startConn(config, &conns)
	}
	conns.Wait()
	t2 := time.Since(t1)
	log.Printf("Test duration %v", t2)
}
示例#16
0
// Connect implements the ssh connection phase
func (c *HostConnection) connect() error {
	c.connectionMutex.Lock()
	if c.connection == nil {
		config := &ssh.ClientConfig{
			User: c.Host.Username,
			Auth: []ssh.ClientAuth{
				ssh.ClientAuthPassword(password(c.Host.Password)),
			},
		}
		var err error
		url := c.Host.Hostname + ":" + strconv.Itoa(c.Host.Port)
		c.connection, err = ssh.Dial("tcp", url, config)
		if err != nil {
			return err
		}
	}
	c.connectionMutex.Unlock()
	return nil
}
示例#17
0
文件: t1.go 项目: willemvds/T1
func doSSH(c chan *ssh.Session, sship string, username string, pw password) {
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(pw),
		},
	}
	client, err := ssh.Dial("tcp", sship, config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}

	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	c <- session

	stdout, err := session.StdoutPipe()
	if err != nil {
		fmt.Println(err)
	}
	ccout <- &stdout

	stderr, err := session.StderrPipe()
	if err != nil {
		fmt.Println(err)
	}
	ccerr <- &stderr

	stdin, err := session.StdinPipe()
	if err != nil {
		fmt.Println(err)
	}
	ccin <- &stdin

	if err := session.Shell(); err != nil {
		fmt.Println(err)
	}
}
示例#18
0
func main() {
	config := &ssh.ClientConfig{
		User: *sshuser,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(password(*sshpass)),
		},
	}
	conn, err := ssh.Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
示例#19
0
文件: ssh.go 项目: B-Rich/packer
func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(*config)

	auth := []gossh.ClientAuth{
		gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)),
		gossh.ClientAuthKeyboardInteractive(
			ssh.PasswordKeyboardInteractive(config.SSHPassword)),
	}

	if config.SSHKeyPath != "" {
		keyring, err := sshKeyToKeyring(config.SSHKeyPath)
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.ClientAuthKeyring(keyring))
	}

	return &gossh.ClientConfig{
		User: config.SSHUser,
		Auth: auth,
	}, nil
}
示例#20
0
文件: client.go 项目: joy999/gossh
func (c *Client) Connect() (e error) {
	if c.Port == 0 {
		c.Port = 22
	}
	var auths []ssh.ClientAuth

	if c.password != "" {
		auths = append(auths, ssh.ClientAuthPassword(c))
	}

	if c.Agent, e = net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); e == nil {
		auths = append(auths, ssh.ClientAuthAgent(ssh.NewAgentClient(c.Agent)))
	}

	config := &ssh.ClientConfig{
		User: c.User,
		Auth: auths,
	}
	c.Conn, e = ssh.Dial("tcp", fmt.Sprintf("%s:%d", c.Host, c.Port), config)
	if e != nil {
		return e
	}
	return nil
}
示例#21
0
// This blocks until SSH becomes available, and sends the communicator
// on the given channel.
func (s *stepWaitForSSH) waitForSSH(state map[string]interface{}) (packer.Communicator, error) {
	config := state["config"].(*config)
	ui := state["ui"].(packer.Ui)
	sshHostPort := state["sshHostPort"].(uint)

	ui.Say("Waiting for SSH to become available...")
	var comm packer.Communicator
	var nc net.Conn
	for {
		if nc != nil {
			nc.Close()
		}

		time.Sleep(5 * time.Second)

		if s.cancel {
			log.Println("SSH wait cancelled. Exiting loop.")
			return nil, errors.New("SSH wait cancelled")
		}

		// Attempt to connect to SSH port
		nc, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort))
		if err != nil {
			log.Printf("TCP connection to SSH ip/port failed: %s", err)
			continue
		}

		// Then we attempt to connect via SSH
		sshConfig := &gossh.ClientConfig{
			User: config.SSHUser,
			Auth: []gossh.ClientAuth{
				gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)),
				gossh.ClientAuthKeyboardInteractive(
					ssh.PasswordKeyboardInteractive(config.SSHPassword)),
			},
		}

		sshConnectSuccess := make(chan bool, 1)
		go func() {
			comm, err = ssh.New(nc, sshConfig)
			if err != nil {
				log.Printf("SSH connection fail: %s", err)
				sshConnectSuccess <- false
				return
			}

			sshConnectSuccess <- true
		}()

		select {
		case success := <-sshConnectSuccess:
			if !success {
				continue
			}
		case <-time.After(5 * time.Second):
			log.Printf("SSH handshake timeout. Trying again.")
			continue
		}

		ui.Say("Connected via SSH!")
		break
	}

	// Store the connection so we can close it later
	s.conn = nc
	return comm, nil
}
示例#22
0
// This blocks until SSH becomes available, and sends the communicator
// on the given channel.
func (s *stepWaitForSSH) waitForSSH(state map[string]interface{}) (packer.Communicator, error) {
	config := state["config"].(*config)
	ui := state["ui"].(packer.Ui)
	vmxPath := state["vmx_path"].(string)

	handshakeAttempts := 0

	ui.Say("Waiting for SSH to become available...")
	var comm packer.Communicator
	for {
		time.Sleep(5 * time.Second)

		if s.cancel {
			log.Println("SSH wait cancelled. Exiting loop.")
			return nil, errors.New("SSH wait cancelled")
		}

		// First we wait for the IP to become available...
		log.Println("Lookup up IP information...")
		ipLookup, err := s.dhcpLeaseLookup(vmxPath)
		if err != nil {
			log.Printf("Can't lookup via DHCP lease: %s", err)
		}

		ip, err := ipLookup.GuestIP()
		if err != nil {
			log.Printf("IP lookup failed: %s", err)
			continue
		}

		log.Printf("Detected IP: %s", ip)

		// Attempt to connect to SSH port
		connFunc := ssh.ConnectFunc(
			"tcp", fmt.Sprintf("%s:%d", ip, config.SSHPort), 5*time.Minute)
		nc, err := connFunc()
		if err != nil {
			log.Printf("TCP connection to SSH ip/port failed: %s", err)
			continue
		}
		nc.Close()

		// Then we attempt to connect via SSH
		config := &ssh.Config{
			Connection: connFunc,
			SSHConfig: &gossh.ClientConfig{
				User: config.SSHUser,
				Auth: []gossh.ClientAuth{
					gossh.ClientAuthPassword(ssh.Password(config.SSHPassword)),
					gossh.ClientAuthKeyboardInteractive(
						ssh.PasswordKeyboardInteractive(config.SSHPassword)),
				},
			},
		}

		comm, err = ssh.New(config)
		if err != nil {
			log.Printf("SSH handshake err: %s", err)

			handshakeAttempts += 1
			if handshakeAttempts < 10 {
				// Try to connect via SSH a handful of times
				continue
			}

			return nil, err
		}

		ui.Say("Connected via SSH!")
		break
	}

	return comm, nil
}
示例#23
0
文件: main.go 项目: kr/sftp
func main() {
	var auths []ssh.ClientAuth
	if agent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
		auths = append(auths, ssh.ClientAuthAgent(ssh.NewAgentClient(agent)))
	}
	if *PASS != "" {
		auths = append(auths, ssh.ClientAuthPassword(password(*PASS)))
	}

	config := ssh.ClientConfig{
		User: *USER,
		Auth: auths,
	}
	addr := fmt.Sprintf("%s:%d", *HOST, *PORT)
	conn, err := ssh.Dial("tcp", addr, &config)
	if err != nil {
		log.Fatalf("unable to connect to [%s]: %v", addr, err)
	}
	defer conn.Close()

	client, err := sftp.NewClient(conn)
	if err != nil {
		log.Fatalf("unable to start sftp subsytem: %v", err)
	}
	defer client.Close()
	switch cmd := flag.Args()[0]; cmd {
	case "ls":
		if len(flag.Args()) < 2 {
			log.Fatalf("%s %s: remote path required", cmd, os.Args[0])
		}
		walker := client.Walk(flag.Args()[1])
		for walker.Step() {
			if err := walker.Err(); err != nil {
				log.Println(err)
				continue
			}
			fmt.Println(walker.Path())
		}
	case "fetch":
		if len(flag.Args()) < 2 {
			log.Fatalf("%s %s: remote path required", cmd, os.Args[0])
		}
		f, err := client.Open(flag.Args()[1])
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		if _, err := io.Copy(os.Stdout, f); err != nil {
			log.Fatal(err)
		}
	case "put":
		if len(flag.Args()) < 2 {
			log.Fatalf("%s %s: remote path required", cmd, os.Args[0])
		}
		f, err := client.Create(flag.Args()[1])
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		if _, err := io.Copy(f, os.Stdin); err != nil {
			log.Fatal(err)
		}
	case "stat":
		if len(flag.Args()) < 2 {
			log.Fatalf("%s %s: remote path required", cmd, os.Args[0])
		}
		f, err := client.Open(flag.Args()[1])
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		fi, err := f.Stat()
		if err != nil {
			log.Fatalf("unable to stat file: %v", err)
		}
		fmt.Printf("%s %d %v\n", fi.Name(), fi.Size(), fi.Mode())
	case "rm":
		if len(flag.Args()) < 2 {
			log.Fatalf("%s %s: remote path required", cmd, os.Args[0])
		}
		if err := client.Remove(flag.Args()[1]); err != nil {
			log.Fatalf("unable to remove file: %v", err)
		}
	case "mv":
		if len(flag.Args()) < 3 {
			log.Fatalf("%s %s: old and new name required", cmd, os.Args[0])
		}
		if err := client.Rename(flag.Args()[1], flag.Args()[2]); err != nil {
			log.Fatalf("unable to rename file: %v", err)
		}
	default:
		log.Fatal("unknown subcommand: %v", cmd)
	}
}
示例#24
0
func main() {
	fmt.Print("Remote host? (Default=localhost): ")
	server := scanConfig()
	if server == "" {
		server = "localhost"
	}
	fmt.Print("Port? (Default=22): ")
	port := scanConfig()
	if port == "" {
		port = "22"
	}
	server = server + ":" + port
	fmt.Print("UserName?: ")
	user := scanConfig()
	fmt.Print("Password?: ")
	p := scanConfig()

	var pass = password(p)
	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.ClientAuth{
			// ClientAuthPassword wraps a ClientPassword implementation
			// in a type that implements ClientAuth.
			ssh.ClientAuthPassword(pass),
		},
	}
	conn, err := ssh.Dial("tcp", server, config)
	if err != nil {
		panic("Failed to dial: " + err.Error())
	}
	defer conn.Close()

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := conn.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()

	// Set IO
	session.Stdout = os.Stdout
	session.Stderr = os.Stderr
	in, _ := session.StdinPipe()

	// Set up terminal modes
	modes := ssh.TerminalModes{
		ssh.ECHO:          0,     // disable echoing
		ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}

	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		log.Fatalf("request for pseudo terminal failed: %s", err)
	}

	// Start remote shell
	if err := session.Shell(); err != nil {
		log.Fatalf("failed to start shell: %s", err)
	}

	// Accepting commands
	for {
		reader := bufio.NewReader(os.Stdin)
		str, _ := reader.ReadString('\n')
		fmt.Fprint(in, str)
	}

}
示例#25
0
package sshpool_test

import (
	"bytes"
	"code.google.com/p/go.crypto/ssh"
	"github.com/kr/sshpool"
	"os"
)

var config = &ssh.ClientConfig{
	User: "******",
	Auth: []ssh.ClientAuth{
		// ClientAuthPassword wraps a ClientPassword implementation
		// in a type that implements ClientAuth.
		ssh.ClientAuthPassword(password("yourpassword")),
	},
}

func Example() {
	sess, err := sshpool.Open("tcp", "127.0.0.1:22", config)
	if err != nil {
		panic(err)
	}

	var b bytes.Buffer
	sess.Stdout = &b
	err = sess.Run("ls")
	if err != nil {
		panic(err)
	}
	os.Stdout.Write(b.Bytes())
示例#26
0
文件: pool_test.go 项目: kr/sshpool
}

var (
	clientPassword = password("foo")
	serverConfig   = &ssh.ServerConfig{
		PasswordCallback: func(conn *ssh.ServerConn, user, pass string) bool {
			return user == "testuser" && pass == string(clientPassword)
		},
		PublicKeyCallback: func(conn *ssh.ServerConn, user, algo string, pubkey []byte) bool {
			return false
		},
	}
	clientConfig = &ssh.ClientConfig{
		User: "******",
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthPassword(clientPassword),
		},
	}
)

func init() {
	if err := serverConfig.SetRSAPrivateKey([]byte(testServerPrivateKey)); err != nil {
		panic("unable to set private key: " + err.Error())
	}
}

type serverBehavior struct {
	sessionDelay time.Duration
}

func dial(t *testing.T) net.Conn {
示例#27
0
文件: ssh.go 项目: juju2013/gsnova
func InitSSH() error {
	if enable, exist := common.Cfg.GetIntProperty("SSH", "Enable"); exist {
		if enable == 0 {
			return nil
		}
	}
	SSHEnable = true
	log.Println("Init SSH.")
	if proxy, exist := common.Cfg.GetProperty("SSH", "Proxy"); exist {
		sshLocalProxy, _ = url.Parse(proxy)
	}
	if enable, exist := common.Cfg.GetIntProperty("SSH", "RemoteResolve"); exist {
		sshResolveRemote = (enable != 0)
	}

	var manager SSH
	RegisteRemoteConnManager(&manager)

	index := 0
	for ; ; index = index + 1 {
		v, exist := common.Cfg.GetProperty("SSH", "Server["+strconv.Itoa(index)+"]")
		if !exist || len(v) == 0 {
			break
		}
		var ssh_conn SSHRawConnection
		if u, err := url.Parse(v); nil == err {
			ssh_conn.Server = u.Host
			if !strings.Contains(u.Host, ":") {
				ssh_conn.Server = net.JoinHostPort(u.Host, "22")
			}
			if u.User == nil {
				log.Printf("Invalid SSH server url:%s, no user found in url.\n", v)
				continue
			} else {
				if pass, exist := u.User.Password(); exist {
					ssh_conn.ClientConfig = &ssh.ClientConfig{
						User: u.User.Username(),
						Auth: []ssh.ClientAuth{
							ssh.ClientAuthPassword(password(pass)),
						},
					}
				} else {
					if identify := u.Query().Get("i"); len(identify) > 0 {
						if content, err := ioutil.ReadFile(identify); nil != err {
							log.Printf("Invalid SSH identify path:%s for reason:%v.\n", identify, err)
							continue
						} else {
							block, _ := pem.Decode([]byte(content))
							if nil == block {
								log.Printf("Invalid pem content for path:%s.\n", identify)
								continue
							}
							clientKeychain := new(keychain)
							if strings.Contains(block.Type, "RSA") {
								rsakey, err := ssh.ParsePrivateKey(block.Bytes)
								if err != nil {
									log.Printf("Invalid RSA private key for %v.\n", err)
									continue
								}
								clientKeychain.add(rsakey)
							} else {
								dsakey, err := ssh.NewSignerFromKey(block.Bytes)
								if err != nil {
									log.Printf("Invalid DSA private key for %v.\n", err)
									continue
								}
								clientKeychain.add(dsakey)
							}

							ssh_conn.ClientConfig = &ssh.ClientConfig{
								User: u.User.Username(),
								Auth: []ssh.ClientAuth{
									ssh.ClientAuthKeyring(clientKeychain),
								},
							}
						}

					} else {
						log.Printf("Invalid SSH server url:%s, no pass/identify found in url.\n", v)
						continue
					}

				}
			}
			if _, err := ssh_conn.GetClientConn(true); nil == err {
				manager.selector.Add(&ssh_conn)
				log.Printf("SSH server %s connected.\n", ssh_conn.Server)
			} else {
				log.Printf("Invalid SSH server url:%s to connect for reason:%v\n", v, err)
			}
		} else {
			log.Printf("Invalid SSH server url:%s for reason:%v\n", v, err)
		}
	}
	if index == 0 {
		return errors.New("No configed SSH server.")
	}

	return nil
}