Example #1
0
func getConn(host *host.Host) (*ssh.ClientConn, error) {
	hostkey := host.Id
	if con, ok := conns[hostkey]; ok {
		return con, nil
	}
	if host.User == "" {
		return nil, fmt.Errorf("user not set")
	}
	for _, keyfile := range host.Keyfiles {
		// TODO add key to global keyring, ok?
		if err := keys.loadPEM(keyfile); err != nil {
			return nil, fmt.Errorf("unable to load %s: %v", keyfile, err)
		}
	}
	config := &ssh.ClientConfig{
		User: host.User,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthKeyring(keys),
		},
	}
	conn, err := ssh.Dial("tcp", host.ConnStr(), config)
	if err != nil {
		return nil, fmt.Errorf("unable to connect to %s: %v", host, err)
	}
	conns[hostkey] = conn
	return conn, nil
}
Example #2
0
func (h *RemoteHelper) runCmd(host, cmd string) string {
	client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", host), h.config)
	if err != nil {
		log.Fatalf("Failed to dial: " + err.Error())
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		log.Fatal("unable to create session: %s", err)
	}
	defer session.Close()

	err = session.RequestPty("xterm", 80, 40, ssh.TerminalModes{})
	if err != nil {
		log.Fatal("request for pseudo terminal failed: %s", err)
	}

	var b bytes.Buffer
	session.Stdout = &b

	err = session.Run(cmd)
	if err != nil {
		log.Fatal("Failed to run: " + err.Error())
	}

	return strings.Replace(strings.Replace(b.String(), "\n", "", -1), "\r", "", -1)
}
Example #3
0
func forward(localConn net.Conn, config *ssh.ClientConfig, serverAddrString, remoteAddrString string) {
	// Setup sshClientConn (type *ssh.ClientConn)
	sshClientConn, err := ssh.Dial("tcp", serverAddrString, config)
	if err != nil {
		log.Fatalf("ssh.Dial failed: %s", err)
	}
	//defer sshClientConn.Close()

	// Setup sshConn (type net.Conn)
	sshConn, err := sshClientConn.Dial("tcp", remoteAddrString)
	if err != nil {
		log.Fatalf("sshClientConn.Dial failed: %s", err)
	}
	//defer sshConn.Close()

	// Copy localConn.Reader to sshConn.Writer
	go func() {
		_, err = io.Copy(sshConn, localConn)
		if err != nil {
			log.Printf("io.Copy from local to remote failed: %v", err)
		}
	}()

	// Copy sshConn.Reader to localConn.Writer
	go func() {
		_, err = io.Copy(localConn, sshConn)
		if err != nil {
			log.Printf("io.Copy from remote to local failed: %v", err)
		}
	}()
}
Example #4
0
func TestSshCmd(t *testing.T) {
	kc := new(keychain)
	kc.load()
	config := &ssh.ClientConfig{
		User: os.Getenv("USER"),
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthKeyring(kc),
		},
	}
	client, err := ssh.Dial("tcp", "localhost: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/whoami"); err != nil {
		panic("Failed to run: " + err.Error())
	}
	log.Printf("Result of running whoami via ssh: %s\n", b)
	//fmt.Println(b.String())
}
// Dials to setup tcp connection to remote host, used for memory information
func dialClient() {
	t_key, _ := getKeyFile()
	if err != nil {
		panic(err)
	}
	key = t_key

	config := &ssh.ClientConfig{
		User: remote_host_user,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(key),
		},
	}

	t_client, err := ssh.Dial("tcp", remote_host+":"+ssh_port, config)
	if err != nil {
		fmt.Println("\n", "Failed to dial: "+err.Error())
		fmt.Println("Unable to establish connection to remote machine.")
		fmt.Println("Make sure that password-less connection is possible.")
		fmt.Println("************************************")
		mem_flag = false
		return
	}
	ssh_client = t_client
}
Example #6
0
// remoteCmdOutput runs the given command on a remote server at the given hostname as the given user.
func remoteCmdOutput(username, hostname, cmd string, privateKey []byte) (b []byte, err error) {
	p, err := ssh.ParseRawPrivateKey(privateKey)
	if err != nil {
		return b, err
	}
	s, err := ssh.NewSignerFromKey(p)
	if err != nil {
		return b, err
	}
	pub := ssh.PublicKeys(s)
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{pub},
	}
	client, err := ssh.Dial("tcp", hostname, clientConfig)
	if err != nil {
		return b, errors.New("ERROR: Failed to dial: " + err.Error())
	}
	defer client.Close()
	session, err := client.NewSession()
	if err != nil {
		return b, errors.New("ERROR: Failed to create session: " + err.Error())
	}
	defer session.Close()
	b, err = session.Output(cmd)
	if err != nil {
		return b, fmt.Errorf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
	}
	return b, nil
}
Example #7
0
func ExecuteCmd(cmd, hostname string, config *ssh.ClientConfig, stdout chan string, stderr chan error) {
	conn, err := ssh.Dial("tcp", hostname+":22", config)
	if err != nil {
		stderr <- err
		return
	}

	session, err := conn.NewSession()
	defer session.Close()

	if err != nil {
		stderr <- err
		return
	}

	pipe, _ := session.StdoutPipe()
	session.Start(cmd)

	buffer := bufio.NewReader(pipe)
	for {
		line, err := buffer.ReadString('\n')
		if len(line) > 0 {
			stdout <- line
		}
		if err != nil {
			if err == io.EOF {
				close(stdout)
				return
			} else {
				stderr <- err
				return
			}
		}
	}
}
Example #8
0
func main() {
	if len(os.Args) < 2 {
		usage()
		return
	}

	username, hostnames, pass := parse()

	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(string(pass)),
		},
	}

	hosts := []*Host{}
	for _, host := range hostnames {
		client, err := ssh.Dial("tcp", host+":22", config)
		if err != nil {
			log.Fatal("Failed to dial: ", err)
		}
		hosts = append(hosts, &Host{host, client})
	}

	lock := make(chan string)

	for {
		fmt.Print("$ ")
		reader := bufio.NewReader(os.Stdin)
		input, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal("Error getting user input: ", err)
		}

		for _, host := range hosts {
			go func(host *Host) {
				// Each ClientConn can support multiple interactive sessions,
				// represented by a Session.
				session, err := host.client.NewSession()
				if err != nil {
					log.Fatal("Failed to create session: ", err)
				}

				// 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(input); err != nil {
					lock <- fmt.Sprintf("%v\n%v", host.hostname, err)
				} else {
					lock <- fmt.Sprintf("%v\n%v", host.hostname, b.String())
				}
			}(host)
		}

		for _ = range hosts {
			fmt.Println(<-lock)
		}
	}
}
func NewTranportSSH(target string, config *ssh.ClientConfig) (*TransportSSH, error) {
	if !strings.Contains(target, ":") {
		target = fmt.Sprintf("%s:%d", target, SSH_DEFAULT_PORT)
	}

	conn, err := ssh.Dial("tcp", target, config)
	if err != nil {
		return nil, err
	}

	sess, err := conn.NewSession()
	if err != nil {
		return nil, err
	}

	si, err := sess.StdinPipe()
	if err != nil {
		return nil, err
	}

	so, err := sess.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if err := sess.RequestSubsystem(SSH_NETCONF_SUBSYSTEM); err != nil {
		return nil, err
	}

	return &TransportSSH{sshConn: conn, sshSession: sess, sshStdin: si, sshStdout: so}, nil
}
func (s *Command) Connect() error {
	host := helpers.StringOrDefault(s.Host, "localhost")
	user := helpers.StringOrDefault(s.User, "root")
	port := helpers.StringOrDefault(s.Port, "22")

	methods, err := s.getSSHAuthMethods()
	if err != nil {
		return err
	}

	config := &ssh.ClientConfig{
		User: user,
		Auth: methods,
	}

	connectRetries := s.ConnectRetries
	if connectRetries == 0 {
		connectRetries = 3
	}

	var finalError error

	for i := 0; i < connectRetries; i++ {
		client, err := ssh.Dial("tcp", host+":"+port, config)
		if err == nil {
			s.client = client
			return nil
		}
		time.Sleep(sshRetryInterval * time.Second)
		finalError = err
	}

	return finalError
}
Example #11
0
func remoteCmdOutput(username, hostname, privateKey, cmd string) []byte {
	block, _ := pem.Decode([]byte(privateKey))
	rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
	clientKey := &keychain{rsakey}
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthKeyring(clientKey),
		},
	}
	client, err := ssh.Dial("tcp", hostname, clientConfig)
	if err != nil {
		log.Println("ERROR: Failed to dial: " + err.Error())
		return []byte{}
	}
	session, err := client.NewSession()
	if err != nil {
		log.Println("ERROR: Failed to create session: " + err.Error())
		return []byte{}
	}
	defer session.Close()
	output, err := session.Output(cmd)
	if err != nil {
		log.Printf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
		return []byte{}
	}
	return output
}
Example #12
0
func getConnection(hostname string) (conn *ssh.ClientConn, err error) {
	connectedHostsMutex.Lock()
	conn = connectedHosts[hostname]
	connectedHostsMutex.Unlock()
	if conn != nil {
		return
	}

	defer func() {
		if msg := recover(); msg != nil {
			err = errors.New("Panic: " + fmt.Sprint(msg))
		}
	}()
	conn, err = ssh.Dial("tcp", hostname+":22", makeConfig())
	if err != nil {
		return
	}

	sendProxyReply(&ConnectionProgress{ConnectedHost: hostname})

	connectedHostsMutex.Lock()
	connectedHosts[hostname] = conn
	connectedHostsMutex.Unlock()

	return
}
Example #13
0
func main() {
	key, err := getKeyFile()
	if err != nil {
		panic(err)
	}
	config := &ssh.ClientConfig{
		User: "******",
		Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
	}
	client, err := ssh.Dial("tcp", "localhost:22", config)
	if err != nil {
		panic(err)
	}
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()
	var b bytes.Buffer
	session.Stdout = &b
	if err := session.Run("/usr/bin/whoami"); err != nil {
		panic(err.Error())
	}
	fmt.Println(b.String())
} //godoc -http=:1989 -index=true
Example #14
0
//TODO 某种认证方法只有一个会被使用,需要多次猜测
func DialInConsole(addr string, username string) (client *ssh.Client, err error) {
	//find cert file
	pathList := certFilePathList()
	authList := []ssh.AuthMethod{}
	for _, path := range pathList {
		clientKeyBytes, err := ioutil.ReadFile(path)
		if err != nil {
			if !os.IsNotExist(err) {
				return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err)
			}
		} else {
			signer, err := ssh.ParsePrivateKey(clientKeyBytes)
			if err != nil {
				return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err)
			}
			//clientKey := &keychain{signer}
			authList = append(authList, ssh.PublicKeys(signer))
		}
	}
	authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) {
		fmt.Printf("[ssh] password for %s@%s", username, addr)
		secret = string(gopass.GetPasswd())
		return
	}))
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: authList,
	}
	client, err = ssh.Dial("tcp", addr, clientConfig)
	if err != nil {
		return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error())
	}
	return
}
Example #15
0
func getSftpClient(conf Config) []*sftp.Client {
	// process the keyfile
	buf, err := ioutil.ReadFile(conf.KeyFile)
	if err != nil {
		log.Fatalf("error in reading private key file %s\n", err)
	}
	key, err := ssh.ParsePrivateKey(buf)
	if err != nil {
		log.Fatalf("error in parsing private key %s\n", key)
	}
	// client config
	config := &ssh.ClientConfig{
		User: conf.User,
		Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
	}
	// connection
	clients := make([]*sftp.Client, 0)
	for _, r := range conf.Remotes {
		c, err := ssh.Dial("tcp", r, config)
		if err != nil {
			log.Fatalf("error in ssh connection %s\n", err)
		}
		// sftp handler
		sftp, err := sftp.NewClient(c)
		if err != nil {
			log.Fatalf("error in sftp connection %s\n", err)
		}
		clients = append(clients, sftp)
	}
	return clients
}
Example #16
0
func (c *SftpClient) Connect() error {
	auth := []ssh.AuthMethod{}
	if c.authMethod == "key" {
		key, _ := c.GetKey(c.keyPath)

		auth = []ssh.AuthMethod{
			ssh.PublicKeys(key),
		}
	} else if c.authMethod == "password" {
		auth = []ssh.AuthMethod{
			ssh.Password(c.password),
		}
	}
	config := &ssh.ClientConfig{
		User: c.username,
		Auth: auth,
	}
	sHost := strings.Join([]string{c.hostname, strconv.FormatInt(c.port, 10)}, ":")

	sshClient, err := ssh.Dial("tcp", sHost, config)
	if err != nil {
		return err
	}
	sftpClient, err := sftp.NewClient(sshClient)
	if err == nil {
		c.Client = sftpClient
	}
	return err
}
Example #17
0
// connect is a private function to set up the ssh connection. It is called at the beginning of every public
// function.
func (config *Config) connect() (*ssh.Session, error) {

	sshconfig := &ssh.ClientConfig{
		User: config.User,
	}

	if config.User == "" {
		u, err := user.Current()
		if err != nil {
			return nil, err
		}
		sshconfig.User = u.Username
	}

	if config.Password != "" {
		sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password))
	}

	// By default, we try to include ~/.ssh/id_rsa. It is not an error if this file
	// doesn't exist.
	keyfile := os.Getenv("HOME") + "/.ssh/id_rsa"
	pkey, err := parsekey(keyfile)
	if err == nil {
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	// Include any additional key files
	for _, keyfile = range config.KeyFiles {
		pkey, err = parsekey(keyfile)
		if err != nil {
			if config.AbortOnError == true {
				log.Fatalf("%s", err)
			}
			return nil, err
		}
		sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
	}

	host := config.Host
	if strings.Contains(host, ":") == false {
		host = host + ":22"
	}
	client, err := ssh.Dial("tcp", host, sshconfig)
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}

	session, err := client.NewSession()
	if err != nil {
		if config.AbortOnError == true {
			log.Fatalf("%s", err)
		}
		return nil, err
	}
	return session, err
}
Example #18
0
/*
	Find or create our connection to the named host. If a connection doesn't
	exist, then we'll create one. If the rsync data is present, then we'll
	rsynch stuff over while we have the lock.
*/
func (b *Broker) connect2(host string) (c *connection, err error) {
	err = nil
	need_sync := false // must detect early and execute late so flag if needed

	if b == nil || b.was_closed {
		err = fmt.Errorf("run_cmd: broker pointer was nil, or broker has been closed")
		return
	}

	if strings.Index(host, ":") < 0 {
		host = host + ":22" // add default port if not supplied
	}

	b.conns_lock.RLock() // get a read lock
	c = b.conns[host]
	b.conns_lock.RUnlock()
	if c != nil && c.active { // we've already connected, just return
		return
	}

	if b.rsync_src != nil && b.rsync_dir != nil { // no connection, rsynch if we need to
		need_sync = true // but wait until we auth the connection to prevent prompt
	}

	b.conns_lock.Lock()         // get a write lock
	defer b.conns_lock.Unlock() // hold until we return

	c = b.conns[host]
	if c != nil { // created while we were waiting on lock or existed but not active
		if c.active {
			return // if active, then safe to send it back now
		}
	} else {
		c = &connection{host: host}
		c.retry_ch = make(chan *Broker_msg, 1024) // the host retry queue
	}

	c.schan, err = ssh.Dial("tcp", host, b.config) // establish the tcp session (ssh channel)
	if err != nil {
		c = nil
		return
	}

	if need_sync {
		toks := strings.Split(host, ":") // must split off port for rsynch
		err = b.synch_host(&toks[0])
		if err != nil {
			err = fmt.Errorf("unable to rsynch to %s: %s", host, err)
			c.schan.Close() // if rsynch fails connection "fails"
			c.active = false
			return
		}
	}

	c.last_cmd = time.Now().Unix()
	c.active = true
	b.conns[host] = c // finally, add to our map (host:port)
	return
}
Example #19
0
func main() {
	logger = log.New(os.Stdout, "wam: ", log.LstdFlags|log.Lshortfile)
	logger.Println("sandhog")

	configData, err := loadConfig()
	if err != nil {
		printUsage()
		logger.Fatalln(err)
	}

	keyring, err := LoadKeyring(configData.keyPath)
	if err != nil {
		logger.Fatalln(err)
	}
	logger.Printf("loaded keyring: %s", keyring)

	sshConfig := &ssh.ClientConfig{
		User: "******",
		Auth: []ssh.ClientAuth{
			ssh.ClientAuthKeyring(keyring),
		},
	}
	logger.Printf("created SSH client config: %s", sshConfig)

	// Dial your ssh server.
	logger.Println("connecting")
	conn, err := ssh.Dial("tcp", "localhost:22", sshConfig)
	if err != nil {
		logger.Fatalf("unable to connect: %s\n", err)
	}
	defer conn.Close()
	logger.Println("connected!")

	// Request the remote side to open port 8080 on all interfaces.
	// When they
	remoteListenEndpoint := fmt.Sprintf("127.0.0.1:%d", configData.remotePort)
	logger.Printf("requesting remote host listen on: %s\n", remoteListenEndpoint)
	listener, err := conn.Listen("tcp", remoteListenEndpoint)
	if err != nil {
		log.Fatalf("unable to register tcp forward: %s", err)
	}
	defer listener.Close()

	logger.Printf("remote host listening on %s\n", remoteListenEndpoint)

	for {
		conn, err := listener.Accept()
		if err != nil {
			logger.Println(err)
			break
		}
		go handleConn(conn, *configData)
	}
	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(listener, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
Example #20
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)
	}
}
Example #21
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
}
Example #22
0
func openSshConnection() *ssh.Client {
	user, host, _ := parseRemoteBackup(backupPath)
	log.Printf("Connecting to %s %s", user, host)
	backupSsh, err := ssh.Dial("tcp", host+":22", &ssh.ClientConfig{User: user, Auth: []ssh.AuthMethod{getPublicKey()}})
	if err != nil {
		log.Fatalf("Error connecting to the server: %v", err)
	}
	return backupSsh
}
Example #23
0
func (this *Handel) check() (err error) {
	if this.auth == nil {
		keys := new(keychain)
		if err = keys.LoadPEM(this.PrivateKey); err != nil {
			return
		}
		this.auth = &ssh.ClientConfig{
			User: this.User,
			Auth: []ssh.ClientAuth{
				ssh.ClientAuthKeyring(keys),
			},
		}
	}
	if this.Port == "" {
		this.Port = SSH_PORT
	}
	if this.client == nil {
		this.client, err = ssh.Dial("tcp", this.Host+":"+this.Port, this.auth)
		if err != nil {
			return
		}
	}
	if this.session == nil {
		this.session, err = this.client.NewSession()
		if err != nil {
			return
		}
	}

	//stdin
	if this.FileIn == "" {
		this.session.Stdin = os.Stdin
	} else if fd, err := os.Open(this.FileIn); err == nil {
		this.session.Stdin = fd
	} else {
		return errors.New("process config error : bad input file : " + err.Error())
	}
	//stdout
	if this.FileOut == "" {
		this.session.Stdout = os.Stdout
	} else if fd, err := os.OpenFile(this.FileOut, os.O_WRONLY|os.O_CREATE, 0666); err == nil {
		this.session.Stdout = fd
	} else {
		return errors.New("process config error : bad output file : " + err.Error())
	}
	//stderr
	if this.FileErr == "" {
		this.session.Stderr = os.Stderr
	} else if fd, err := os.OpenFile(this.FileErr, os.O_WRONLY|os.O_CREATE, 0666); err == nil {
		this.session.Stderr = fd
	} else {
		return errors.New("process config error : bad error file : " + err.Error())
	}

	return
}
Example #24
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()}
}
Example #25
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)
}
Example #26
0
func NewRemotePassAuthRunner(user, host, password string) (*Remote, error) {
	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{ssh.Password(password)},
	}
	server, err := ssh.Dial("tcp", host, config)
	if err != nil {
		return nil, err
	}
	return &Remote{server}, nil
}
Example #27
0
func (self *Script) Execute(host *Host, out io.Writer) error {
	usr, err := user.Current()
	if err != nil {
		return err
	}
	if host.User == "" {
		host.User = usr.Username
	}
	cfg := &ssh.ClientConfig{
		User: host.User,
	}
	if host.Password != "" {
		cfg.Auth = []ssh.AuthMethod{
			ssh.Password(host.Password),
		}
	} else {
		content, err := ioutil.ReadFile(usr.HomeDir + "/.ssh/id_rsa")
		if err != nil {
			content, err = ioutil.ReadFile(usr.HomeDir + "/.ssh/id_dsa")
			if err != nil {
				return err
			}
		}
		key, err := ssh.ParsePrivateKey(content)
		if err != nil {
			return err
		}
		cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
	}
	client, err := ssh.Dial("tcp", host.Name+":"+strconv.Itoa(host.Port), cfg)
	if err != nil {
		fmt.Fprintln(out, err.Error())
		return err
	}
	session, err := client.NewSession()
	if err != nil {
		fmt.Fprintln(out, err.Error())
		return err
	}
	defer session.Close()
	session.Stdout = out
	session.Stderr = out
	if !self.HideBoundaries {
		fmt.Fprintln(out, "---------------------- script started ----------------------")
	}
	if err := session.Run(self.Content); err != nil {
		return err
	}
	if !self.HideBoundaries {
		fmt.Fprintln(out, "---------------------- script finished ----------------------")
	}
	return nil
}
Example #28
0
func (c *Client) Connect() (err error) {
	var client *ssh.ClientConn

	client, err = ssh.Dial("tcp", c.Addr, c.Config)
	if err != nil {
		return
	}

	c.Client = client

	return
}
Example #29
0
func (sshTransport *SSHTransport) getClientSession() (*ssh.Client, *ssh.Session, error) {
	address := fmt.Sprintf("%s:%d", sshTransport.Host, sshTransport.Port)
	client, err := ssh.Dial("tcp", address, sshTransport.Config)
	if err != nil {
		return nil, nil, err
	}
	session, err := client.NewSession()
	if err != nil {
		return nil, nil, err
	}
	return client, session, nil

}
Example #30
0
func DialWithPassword(addr string, username string, password string) (client *ssh.Client, err error) {
	clientConfig := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
		},
	}
	client, err = ssh.Dial("tcp", addr, clientConfig)
	if err != nil {
		return nil, fmt.Errorf("[DialWithPassword] Failed to dial: %s", err.Error())
	}
	return
}