Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with non-interactive command handle #212

Closed
inot opened this issue Aug 22, 2023 · 1 comment
Closed

Problem with non-interactive command handle #212

inot opened this issue Aug 22, 2023 · 1 comment

Comments

@inot
Copy link

inot commented Aug 22, 2023

Hello, got strange problem. Everything fine if I've connected by a ssh client, got a shell prompt, sent a message, got an answer.

But If I tried to use script for the same commands. After script I've got error here "line, readLineError := term.ReadLine()" and readLineError=EOF. Looks like script cant send command or server cant get it.

I'm absolutely sure that I done something wrong. Can you send me the right signals? )

ssh client output

[email protected]'s password:
inot $ id
ID

script output:

inot $ Wrong Command

Server Part

func main() {

	// Create a new server instance
	s := &ssh.Server{
		Addr:            "0.0.0.0:2222",
		Handler:         handleSession,
		PasswordHandler: handleAuthentication,
		IdleTimeout:     60 * time.Second,
	}

	key, err := ReadPrivateKeyFromFile("key.rsa")
	if err != nil {
		panic(err)
	}
	s.AddHostKey(key)
	log.Printf("[+]Starting SSH server on address: %v\n", s.Addr)
	log.Fatal(s.ListenAndServe())

}

func handleSession(s ssh.Session) {
	defer s.Exit(0)
	term := term.NewTerminal(s, s.User()+" $ ")
	line, readLineError := term.ReadLine()
	if readLineError != nil {
		log.Print("Error: ")
		log.Println(readLineError)
	}
	proccessIncomeMessage(line, s)
}

func proccessIncomeMessage(line string, s ssh.Session) {
	switch line {
	case "id":
		io.WriteString(s, "ID")
	default:
		io.WriteString(s, "Wrong Command")
	}
}

Client Part

	client, err := ssh.Dial("tcp", host+":"+port, config)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// start session
	sess, err := client.NewSession()
	if err != nil {
		log.Fatal(err)
	}
	defer sess.Close()

	// setup standard out and error
	// uses writer interface
	sess.Stdout = os.Stdout
	sess.Stderr = os.Stderr

	// run single command
	err = sess.Run(cmd)
	if err != nil {
		log.Fatal(err)
	}
@inot
Copy link
Author

inot commented Aug 22, 2023

I've changed handleSession to

func handleSession(s ssh.Session) {
	defer s.Exit(0)
	line := s.RawCommand()
	proccessIncomeMessage(line, s)
}

now everything ok.

@inot inot closed this as completed Aug 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant