ssh client (dropbear on a router) does no output when put in background - ssh

I'm trying to automate some things on remote Linux machines with bash scripting on Linux machine and have a working command (the braces are a relict from cmd concatenations):
(ssh -i /path/to/private_key user#remoteHost 'sh -c "echo 1; echo 2; echo 3; uname -a"')
But if an ampersand is concatenated to execute it in background, it seems to execute, but no output is printed, neither on stdout, nor on stderr, and even a redirection to a file (inside the braces) does not work...:
(ssh -i /path/to/private_key user#remoteHost 'sh -c "echo 1; echo 2; echo 3; uname -a"') &
By the way, I'm running the ssh client dropbear v0.52 in BusyBox v1.17.4 on Linux 2.4.37.10 (TomatoUSB build on a WRT54G).
Is there a way to get the output either? What's the reason for this behaviour?
EDIT:
For convenience, here's the plain ssh help output (on my TomatoUSB):
Dropbear client v0.52
Usage: ssh [options] [user#]host[/port][,[user#]host/port],...] [command]
Options are:
-p <remoteport>
-l <username>
-t Allocate a pty
-T Don't allocate a pty
-N Don't run a remote command
-f Run in background after auth
-y Always accept remote host key if unknown
-s Request a subsystem (use for sftp)
-i <identityfile> (multiple allowed)
-L <listenport:remotehost:remoteport> Local port forwarding
-g Allow remote hosts to connect to forwarded ports
-R <listenport:remotehost:remoteport> Remote port forwarding
-W <receive_window_buffer> (default 12288, larger may be faster, max 1MB)
-K <keepalive> (0 is never, default 0)
-I <idle_timeout> (0 is never, default 0)
-B <endhost:endport> Netcat-alike forwarding
-J <proxy_program> Use program pipe rather than TCP connection
Amendment after 1 day:
The braces do not hurt, with and without its the same result. I wanted to put the ssh authentication to background, so the -f option is not a solution. Interesting side note: if an unexpected option is specified (like -v), the error message WARNING: Ignoring unknown argument '-v' is displayed - even when put in background, so getting output from background processes generally works in my environment.
I tried on x86 Ubuntu regular ssh client: it works. I also tried dbclient on x86 Ubuntu: works, too. So this problem seems to be specific to the TomatoUSB build - or inside the "dropbear v0.52" was an unknown fix between the build in TomatoUSB and the one Ubuntu provides (difference in help output is just the double-sized default receive window buffer on Ubuntu)... how can a process know if it was put in background? Is there a solution to the problem?

I had the similar problem on my OpenWRT router. Dropbear SSH client does not write anything to output if there is no stdin, e.g. when run by cron. I presume that & has the same effect on process stdin (no input).
I found some workaround on author's bugtracker. Try to redirect input from /dev/zero.
Like:
ssh -i yourkey user#remotehost "echo 123" </dev/zero &
It worked for me as I tried to describe at my blog page.

Related

How to rsync with a non-standard port and two factor 2FA authentication?

I need to rsync to a remote server using a non-standard SSH port and 2FA which I use via Authy app. The SSH works with this command:
ssh -2 -p 9999 -i /Users/Me/.ssh/id_rsa user#9.9.9.9
This brings up a "Verification Code" prompt in the shell. Which I enter from Authy, and I'm in.
Given the discussion on this a StackOverflow answers I tried this variation of rsync:
rsync -rvz -e 'ssh -p 9999 -i /Users/Me/.ssh/id_rsa \
--progress /src/ user#9.9.9.9.9:/dest/
(Put here on two lines just for legibility, it's one line in my shell command).
This does bring up the Verification Code prompt, which I enter correctly, but then it produces this error:
protocol version mismatch -- is your shell clean?
(see the rsync man page for an explanation)
rsync error: protocol incompatibility (code 2) at compat.c(185) [sender=3.1.3]
How can I use rsync with 2FA? Many thanks.
Because #JGK mentioned the answer in the comment, adding answer here for posterity. This "is your shell clean" stuff is shown when remote server is echoing some output upon login, which in my case .bashrc indeed was. I've added a conditional to that echo only to apply when the shell login is "interactive", as mentioned in this Server Fault thread, and it works. Just for easier clarity, the IF condition reads as follows:
if echo "$-" | grep i > /dev/null; then
[any code that outputs text here]
fi
Many thanks.

How to deal with "Pseudo-terminal will not be allocated because stdin is not a terminal."

ssh -t remotehost vim /tmp/x.txt
I know that I can run a command like the above.
But I would like to be able to run any local bash code in a remote machine. For this reason, I'd like to call the remote 'bash -s' so that can process any local bash code.
ssh -t remotehost 'bash -s' <<< vim /tmp/x.txt
However, the above example shows "Pseudo-terminal will not be allocated because stdin is not a terminal." Is there any way to let ssh take local bash code via stdin and run it via the remote 'bash -s'? Thanks.
ssh -t remotehost 'bash -s' <<< vim /tmp/x.txt
You're getting the "Pseudo-terminal will not be allocated..." message because you're running ssh with a single -t option, when the standard input to the ssh process isn't a TTY. ssh prints that message specifically in this case. The documentation for -t says:
-t
Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
The -t command-line option is related to the ssh configuration option RequestTTY:
RequestTTY
Specifies whether to request a pseudo-tty for the session. The argument may be one of: no (never request a TTY), yes (always request a TTY when standard input is a TTY), force (always request a TTY) or auto (request a TTY when opening a login session). This option mirrors the -t and -T flags for ssh(1).
A single -t is equivalent to "RequestTTY yes", while two of them is equivalent to "RequestTTY force".
If you want your remote command(s) to run with a TTY, then specify -t twice:
ssh -tt remotehost 'bash -s' <<< vim /tmp/x.txt
or
ssh -t -t remotehost 'bash -s' <<< vim /tmp/x.txt
ssh will allocate a TTY for the remote system and it won't print that message.
If the command(s) being run on the remote system don't require a TTY, you can leave the -t option out:
ssh remotehost 'bash -s' <<< vim /tmp/x.txt
I believe the following might suit your purposes:
vim /tmp/x.txt ; ssh remotehost 'bash -s' < /tmp/x.txt
The first expression (vim ...) allows you to specify the commands you want to execute remotely as a local file called /tmp/x.txt; the second expression (ssh ...) calls the remote bash interpreter, and sends the contents of your local file to it for execution. Note that you do not need the -t option for ssh in this case (which gave rise to the pseudo-terminal warning), and that you do not need to use a here string (<<<) but can use the normal file input operator (<).
This solution seems to work for, e.g., the following file contents:
echo These commands are being executed on $HOSTNAME
echo This is a second command

How to automatically setup SSH key pass on first ansible command run for each new server?

Today I started learning ansible and first thing I came across while trying to run the command ping on remote server was
192.168.1.100 | UNREACHABLE! => {
"changed": false,
"msg": "(u'192.168.1.100', <paramiko.rsakey.RSAKey object at 0x103c8d250>, <paramiko.rsakey.RSAKey object at 0x103c62f50>)",
"unreachable": true
}
so I manually setup the SSH key, I think I faced this as no writeup or Tutorial by any devops explains the step why they don't need it or if they have manually set it up before the writing a tutorial or a video.
So I think it would be great if we can automate this step too..
If ssh keys haven't been set up you can always prompt for an ssh password
-k, --ask-pass ask for connection password
I use these commands for setting up keys on CentOS 6.8 under the root account:
cat ~/.ssh/id_rsa.pub | ssh ${user}#${1} -o StrictHostKeyChecking=no 'mkdir .ssh > /dev/null 2>&1; restorecon -R /root/; cat >> .ssh/authorized_keys'
ansible $1 -u $user -i etc/ansible/${hosts} -m raw -a "yum -y install python-simplejson"
ansible $1 -u $user -i etc/ansible/${hosts} -m yum -a "name=libselinux-python state=latest"
${1} is the first parameter passed to the script and should be the machine name.
I set ${user} elsewhere, but you could make it a parameter also.
${hosts} is my hosts file, and it has a default, but can be overridden with a parameter.
The restorecon command is to appease selinux. I just hardcoded it to run against the /root/ directory, and I can't remember exactly why. If you run this to setup a non-root user, I think that command is nonsense.
I think those installs, python-simplejson and libselinux-python are needed.
This will spam the authorized_keys files with duplicate entries if you run it repeatedly. There are probably better ways, but this is my quick and dirty run once script.
I made some slight variations in the script for CentOS 7 and Ubuntu.
Not sure what types of servers these are, but nearly all Ansible tutorials cover the fact that Ansible uses SSH and you need SSH access to use it.
Depending on how you are provisioning the server in the first place you may be able to inject an ssh key on first boot, but if you are starting with password-only login you can use the --ask-pass flag when running Playbooks. You could then have your first play use the authorized_key module to set up your key on the server.

how does fabric execute commands?

i am wondering how does fabric execute commands.
Let's say I give him env.user=User, env.host=HOST. Then i ask him to sudo('ls')
Is that equivalent to me typing in a shell : ssh User#host 'sudo(/bin/ls)'
or it's more : ssh User#host in a first time, then sudo ls commande in a seconde time ?
I'm asking that because sometimes using a shell, if the TTY has a bad configuration (I am a bit blurry on this), ssh User#Host 'sudo /bin/ls'
return : sudo: no tty present and no askpass program specified
but you can first log in with ssh User#Host then sudo ls and it works.
I don't know how to replicate the no tty error, but I know it can occurs. Would this block the sudo commande from Fabric?
Basically how it works is:
First a connection is established (equivalent as doing ssh User#host)
Over this connection a command is executed as follows:
sudo -S -p 'sudo password:' /bin/bash -l -c "your_command"
You can also allow Fabric not to request a pty with either pty=False argument, env.always_use_pty=False or --no-pty commandline option.

How to inject commands at the start of an interactive SSH session?

I want to be able to just ssh to a server where I cannot modify profiles and set up the environment with several commands before getting the usual interactive session.
Any ideas?
I've been using an expect script with an "interact" command at the end - which works for most things but is clumsy and breaks some console apps. Also been extermienting with empty-expect and socat. Any other suggestions?
If you're able to write somewhere on the filesystem, you may be able to invoke bash with a custom rc file like this:
ssh me#example.com -t bash --rcfile /home/user/my_private_profile -i
Note that this appears to only work for interactive shell, not login shells. The -t option to ssh makes it allocate a pty even though you're specifying a command.
If you can't write to the filesystem anywhere, you could use a subshell to supply a named pipe as the rcfile:
$ ssh ares -t "bash --rcfile <(echo 'FOO=foo';echo 'BAR=bar') -i"
axa#ares:~$ echo $FOO
foo
axa#ares:~$ echo $BAR
bar