简体   繁体   中英

Send commands from sh file and stay logged in over ssh

I want to send a few commands (functions) that are inside a simple .sh file AND stay logged in when ssh-ing to a remote computer.

I've tried many ways, but none have worked so far. Here's just one:

msh(){
    SERVER=$1
    LOCAL=10.20.1.1
    SSHF=`cat /tmp/sshf.sh`
    ssh $SERVER -R 47471:$LOCAL:22 "$SSHF; bash --login"
}

I've also tried copying over the file with pipes and streams and whatnot, none have worked.

You need to reserve a terminal at $SERVER , you do this with the -t switch. If I change your function to:

msh(){
    SERVER=$1
    LOCAL=10.20.1.1
    SSHF=`cat /tmp/sshf.sh`
    ssh -t $SERVER -R 47471:$LOCAL:22 "$SSHF; bash --login"
}

It seems to do what you want.

First copy the file over with scp like this scp /tmp/sshf.sh $SERVER:~

This will place your script sshf.sh in your home directory on $SERVER then you can ssh into the machine and run it ssh $SERVER cat ~/sshf.sh

As a script called copy_run_stay.sh with sshf.sh containing echo hello would look like this:

#!/bin/bash

# get server name as argument to script
SERVER=$1
script='sshf.sh' 
# copy script to server
scp $script $SERVER:~
# run script on server
ssh $SERVER cat ~/sshf.sh
# stay on server
ssh $SERVER

And would produce:

# run the script on laptop
laptop $ ./copy_run_stay.sh
# sshf.sh gets copied to server and ran
server $ hello 
# we are still on the server
server $ 

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