Netflix/go-expect

go-expect seems not work with "ssh" command

sesky4 opened this issue ยท 2 comments

After googling, ssh seems directly write to /dev/tty, not stdout.
Any workaround or support in future?๐Ÿ˜„

package main

import (
	"log"
	"os"
	"os/exec"

	expect "github.com/Netflix/go-expect"
)

func main() {
	c, err := expect.NewConsole(expect.WithStdout(os.Stdout))
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	cmd := exec.Command("ssh", "<redacted>")
	cmd.Stdin = c.Tty()
	cmd.Stdout = c.Tty()
	cmd.Stderr = c.Tty()

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

	c.SendLine("cat /etc/os-release")
	c.SendLine("exit")
	c.Expect(expect.RegexpPattern(`Connection to [^\s]* closed.`))

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

An example of it in action:

โฏ go run .
cat /etc/os-release
exit
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-66-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Jun  2 17:14:52 UTC 2020

  System load:  0.08              Processes:           97
  Usage of /:   3.4% of 77.36GB   Users logged in:     0
  Memory usage: 44%               IP address for eth0: <redacted>
  Swap usage:   0%

 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch

65 packages can be updated.
0 updates are security updates.


*** System restart required ***
Last login: Tue Jun  2 17:13:50 2020 from <redacted>
cat /etc/os-release
exit
root@minecraft:~# cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
root@minecraft:~# exit
logout
Connection to <redacted> closed.

Thanks! SSH write to stdout when stdin is not terminal. Using a tty library can help.