How do I execute a command every time after ssh'ing from one machine to another? - ssh

How do I execute a command every time after ssh'ing from one machine to another?
e.g
ssh mymachine
stty erase ^H
I'd rather just have "stty erase ^H" execute every time after my ssh connection completes.
This command can't simply go into my .zshrc file. i.e. for local sessions, I can't run the command (it screws up my keybindings). But I need it run for my remote sessions.

Put the commands in ~/.ssh/rc

You can put something like this into your shell's startup file:
if [ -n "$SSH_CONNECTION" ]
then
stty erase ^H
end
The -n test will determine if SSH_CONNECTION is set which happens only when logged in via SSH.

If you're logging into a *nix box with a shell, why not put it in your shell startup?
.bashrc or .profile in most cases.

Assuming a linux target, put it in your .profile

Try adding the command below the end of your ~/.bashrc. It should be exited upon logoff. Do you want this command only executed when logging off a ssh session? What about local sessions, etc?
trap 'stty erase ^H; exit 0' 0
You probably could setup a .logout file from /etc/profile using this same pattern as well.

An answer for us, screen/byobu users:
The geocar's solution will not work as screen will complain that "Must be connected to a terminal.". (This is probably caused by the fact that .ssh/rc is processed before shell is started. See LOGIN PROCESS section from man 8 sshd).
Robert's solution is better here but since screen and byobu open it's own bash instance, we need to avoid infinite recursion. So here is adjusted byobu-friendly version:
## RUN BYOBU IF SSH'D ##
## '''''''''''''''''' ##
# (but only if this is a login shell)
if shopt -q login_shell
then
if [ -n "$SSH_CONNECTION" ]
then
byobu
exit
fi
fi
Note that I also added exit after byobu, since IMO if you use byobu in the first place, you normally don't want to do anything outside of it.

Related

How to not initialize ssh session

Well I was smart enough to put an exit 0 in one of my dotfiles on a remote machine. Whenever I log in, the shell exits instantly now. How can I ssh into a machine without sourcing all the dot files?
I found a workaround to solve this problem by directly running a command:
ssh -t remotehost vim /dotfile/i/had/to/revert

Unable to exit from SSH when executed from TCLSH

I have hard requirement of logging into a terminal via SSH from TCL console and relaunch a tcl script from that terminal. For this I use exec command and it does get executed. The only problem is it doesn't return back to parent code.
I have automated SSH login and it works fine from a bash/csh terminal
But from TCL console, the following happens
Simple example
exec ssh hostname pwd
puts "Done"
When I execute this code in TCL, "Done" never gets printed. I just get the output of pwd and that's it.
I have a need of looping SSH into multiple terminals and run TCL jobs on a hardware, but the loop gets stuck after executing the first SSH.
I search the internet for answers and I am not able to find any. Please help.
There could be a lot issues going on here. Running ssh with an explicit command (pwd) will usually default to not allocating a tty (ssh -T) and will run the remote shell in non-interactive mode. And the output of a command called from exec is not normally echoed to standard output, so I would not expect you to see the output if you call it from a script. You have to print the result of exec to see the output of the pwd command. Also, different shell startup scripts are run on the remote host depending on which shell the account is set up with and whether it is an interactive or non-interactive shell. It could be .bashrc, .bash_profile, .profile, .cshrc, etc., and if the script behaves differently when it has a tty vs. when it doesn't, that could explain differing behavior between a bash/csh shell and the TCL console.
Without having access to your system, it is hard for me to troubleshoot. I would start with a script like this:
set result [exec ssh -T hostname pwd]
puts "result = $result"
puts "Done."
Then I would try changing the -T to a -t and trying again. If the output of "pwd" is appearing before the "result =" line, then you can tell that the command is writing the result to a tty instead of standard output, and that's useful information for troubleshooting.

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

rsync exits with the message "stdin is not a tty"

I want to use rsync to my remote server for which I have SSH access. I use the following command:
rsync -e 'ssh -p 22222' -rtz --delete content_dir/ user#example.com:/home/user/public_html
After entering the command, it asks for the password for the remote location. When I type it, it exits with the message,
stdin: is not a tty
How do I supply the password to rsync? The method suggested should also work when I use it in a shell script.
You need to add:
[ -z "$PS1" ] && return
to the beginig of .bashrc that is located in your home dir.
The password is being accepted here, as you've stated yourself the operation does happen.
The error message "stdin: is not a tty" is due to something in the startup script on your server attempting to process an action that should only happen for interactive logins (when you connect with ssh direct to the server, etc).
[ -z "$PS1" ] && return solves the problem but it checks whether the prompt string length equals to zero and if it does then exits. Although $PS1 will not be set in a non-interactive shell, $PS1 being of zero length doesn't ultimately mean that the shell is not interactive.
Better approach is to check the shell's current options using $-. For example [[ $- != *i* ]] && return.
In case a simple return doesn't do the job, here's another approach taken from this blog article:
if `tty -s`; then
mesg n
fi
tty -s checks if there's a TTY attached (the -s tells it to do so silently and just exit with the appropriate return code). tty returns the tty attached (e.g. "/dev/pts/1"). This should be safer than checking some shell variable ;)
mesg controls the write access to your terminal (msg n disallows writing to the (in our case non-existing) terminal), and thus requires one to be present.
On some systems (in my case Debian Jessie, but there are also reports on Ubuntu) mesg n1 is set unconditionally in either ~/.bashrc or ~/.profile. So if it exists that way, this might be the culprit.
As with the other examples, you can of course make that a one-liner: [[ $(tty -s ) ]] && mesg n. And nobody keeps you from combining the two:
if [[ $(tty -s ) ]]; then
mesg n
else
return
fi
Btw: According to the linked article, this fragment should go to the .bashrc of the machine you connect to (the "remote") – so if that's johndoe#somehost, this should be applied at the start of /home/johndoe/.bashrc on somehost. In my case I only got rid of the message after having applied this change on the "calling host" as well.
PS: Also check the .profile if it has a stand-alone msg n command (it did in my case). If it does, wrap it there.
1: mesg n is used to prevent other users on the machine writing to your current terminal device, which per se is a good thing – but not helpful for some rsync job ;)

running command on remote machine using ssh

i want to run some command on several machine using ssh. I know it can be done by just using the command "ssh user#hostname command". However, the command i want to run print some string on the console. Is there any way that send all the strings back to the console that i'm on?
You could run the commands in a screen:
screen -S test
ssh user#hostname command1
ssh user#hostname2 command2
You can then detach (Ctrl-D) from the screen, let it run for however long it will run, then re-attach (screen -r test) to the screen and see all of the output. This assumes that you won't have a ton of output from the commands, however. Here's a link to a tutorial on screen.
ssh user#hostname command
Does just that. if 'command' outputs something, it'll show on the terminal you ran ssh from.
Try e.g. ssh user#hostname ls -l
But as others have said, GNU screen is invaluable for this type of work.
You probably want to use Gnu Screen for this. You can start a process in a "virtual" terminal, "detach" the terminal and log out for however long you want... Then you can ssh back in and re-attach the terminal to see the console output.
Also have a look at nohup, for example:
ssh user#domain.com nohup script_that_outputs_strings.py > the_strings.txt
Then if you want to go back and monitor the progress, you could check back and tail the file or scp the output back to your local machine.
Why don't you send you an email back?
Or use a log file, and scp it to your current computer?
otherwise, I don't know!