简体   繁体   中英

BASH. Sourcing local script on remote host on login

I have a local bash script with some useful functions I use frequently. Is there any way to source this file on a remote host on login?

Let's say, the name of the local file with functions helper.sh , it has test() function that just outputs "test msg"

localhost$ ls
helper.sh
localhost$. ./helper.sh
localhost$test
test msg

I log in to a remote host and want my test() function from the helper.sh working on the remote host without copying helper.sh onto the remote host in advance:

localhost$ ssh user@remotehost  # or something else to make my script work on  remote host
remotehost$ test
test msg

I have a special function for this:

function ssh_with_rcfile
{
    if (( $# == 1 )); then
        local remote_hostname=$(echo ${1:?Need remote hostname} | sed 's/^[^@]*@//')  # always rsync as default user
        rsync --quiet \
            $LINUX_CONFIG_DIR/.sshrc \
            $LINUX_CONFIG_DIR/some_other_file.sh \
            $remote_hostname:/tmp/${USER}/
        /usr/bin/ssh -t $1 "bash --rcfile /tmp/${USER}/.sshrc -i"
    else
        # TODO: This is not very useful, probably better to just append any remaining arguments to the ssh command above
        /usr/bin/ssh "$@"
    fi
}

ssh -t combined with the remote bash --rcfile command allows you to effectively source a remote file upon login. So I just rsync my .sshrc file up to the remote before logging in.

One caveat is that you can only have a single rcfile , so if you want to source multiple files (eg some_other_file.sh above), you have to handle them all from inside of .sshrc .

ssh user@server './test/file.sh'

The command logs you in with a command to be run, in this example which is to run the file.sh

The backticks are used to run the command on the remote machine, and then pass the output to your local machine, as if you entered the command on the local machine.

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