简体   繁体   English

从sh文件发送命令并通过ssh保持登录状态

[英]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. 我想发送一个简单的.sh文件中的一些命令(功能),并在ssh到远程计算机时保持登录状态。

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. 您需要在$SERVER处保留一个终端,使用-t开关即可。 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:~ 首先使用scp复制文件,如下所示: 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 这会将脚本sshf.sh放在$SERVER上的主目录中,然后您可以ssh进入计算机并运行它ssh $SERVER cat ~/sshf.sh

As a script called copy_run_stay.sh with sshf.sh containing echo hello would look like this: 作为一个名为copy_run_stay.sh的脚本, sshf.sh包含echo hello sshf.sh如下所示:

#!/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 $ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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