Unable to use `read` command in .ssh/rc

0

I want to read input from keyboard when SSH connection established. So I edited .ssh/rc file and used read command, just like:

#!/bin/sh

read -p "input: " something
echo $something

But the output is blank; the read command does not work.

However, this can normally work when put in .bashrc file. How could I use read command in .ssh/rc file?

Alexander Zhang

Posted 2019-05-05T09:28:35.233

Reputation: 21

I answered your explicit question but maybe using read in ~/.ssh/rc is not the best way to do whatever you want to do. Compare XY problem. You got answer to Y, so the question shouldn't be substantially changed now, even if there's X behind it. Still you can ask a separate question about X, if needed.

– Kamil Maciorowski – 2019-05-05T10:28:42.860

Answers

0

man 8 sshd in my Debian reads [emphasis mine]:

If ~/.ssh/rc exists and the sshd_config(5) PermitUserRC option is set, runs it; else if /etc/ssh/sshrc exists, runs it; otherwise runs xauth. The “rc” files are given the X11 authentication protocol and cookie in standard input.

[…]

If the file ~/.ssh/rc exists, sh(1) runs it after reading the environment files but before starting the user's shell or command. It must not produce any output on stdout; stderr must be used instead. If X11 forwarding is in use, it will receive the "proto cookie" pair in its standard input (and DISPLAY in its environment). The script must call xauth(1) because sshd will not run xauth automatically to add X11 cookies.

Even if X11 forwarding is not in use, your read doesn't interact with what you type because stdin is taken from elsewhere. (Note in addition echo prints to stdout, while it shouldn't).

If you request X11 forwarding (and all is set right for it to work), your read will indeed read something and echo will print something. Try it (ssh -X the_server). Example output:

MIT-MAGIC-COOKIE-1 d936faac03ac21db21160fb6cab5be86

And if you add ls -l /proc/$$/fd/ to the script then it will show you the file descriptor 0 (stdin) is not what you expected. Example:

lr-x------ 1 kamil kamil 64 May  5 12:03 0 -> pipe:[5335679]
lrwx------ 1 kamil kamil 64 May  5 12:03 1 -> /dev/pts/4
lrwx------ 1 kamil kamil 64 May  5 12:03 2 -> /dev/pts/4
lr-x------ 1 kamil kamil 64 May  5 12:03 3 -> /proc/13928/fd

In case you don't know: 0 is stdin, 1 is stdout, 2 is stderr.

You can make read interact with the TTY:

</dev/tty read -p "input: " something
echo "$something" >&2

Notes:

  • The shebang you used is irrelevant, sshd uses sh to run the file regardless.
  • In general you should double-quote variables.
  • My code prints to stderr, as the manual requested.
  • The script doesn't run xauth, so you wont be able to forward X11.

Kamil Maciorowski

Posted 2019-05-05T09:28:35.233

Reputation: 38 429