简体   繁体   中英

How to execute a command on the remote at login with ssh, after .bashrc sourcing?

I am working on different machines where my home is NFS-mounted. I want to switch easily to another machine if the one I am working on is too much loaded.

I often modify my environment in the shell I am working, and I would like to find the same modified (with respect to the bashrc) environment when I switch to another machine. I tried the following script, but it does not work because the .bashrc is sourced after source $HOME/.env-dump.txt .

Is there a clean way to execute some commands when logging to a machine with ssh as if you type them at the prompt after logged?

#!/usr/bin/env sh

if [[ $# != 1 ]]; 
    echo 'sssh USAGE:'
    echo '  sssh remotename'
    exit 1
fi

printenv | sed -e '/_=.*/ d;s/\([^=]\+\)=\(.*\)/export \1="\2"/' > $HOME/.env-dump.txt
ssh $1 -t 'source $HOME/.env-dump.txt; bash -l'

Add the following lines to your ~/.bash_profile

[ -f "$HOME/.bashrc" ] && . $HOME/bashrc
[ -f "$HOME/.env-dump.txt" ] && source $HOME/.env-dump.txt

And create a ~/.bash_logout file with the line

[ -f "$HOME/.env-dump.txt" ] && rm  $HOME/.env-dump.txt

Now you can simply call ssh $1 -t 'bash -l' in the last line of your script.

WARNING

The output of printenv contains some variables which are machine dependent like GNOME_KEYRING_CONTROL , SESSION_MANAGER , DBUS_SESSION_BUS_ADDRESS ... (These variables are form a Ubuntu 12.04). These variables should be removed from the ~/.env-dump.txt file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM