5

分享一个连接远端计算机与传输文件的脚本 - Philbert

 1 year ago
source link: https://www.cnblogs.com/liangxuran/p/16909080.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

分享一个连接远端计算机与传输文件的脚本

用了一个月超算,由于本地是linux系统,需要用到ssh命令连接远端计算机,需要用到scp命令进行文件传输。
但是连接远端的命令太复杂,于是我写成了一个bash脚本,使用起来非常方便。

将ssh和scp命令整合,可以连接特定的远端计算机,或者收发文件。
该脚本共设置了三个选项
-o--option 可以选择send,receive和connect三种模式,前两种将调用scp命令传输文件,后一种将使用ssh连接远端
-l--local 后面加本地文件夹或者本地文件名。如果包含“?”等模糊匹配的字符需要加引号。在receive模式下必填该选项。
-r--remote 后面加远端文件名或者远端文件夹。如果包含“?
”等模糊匹配的字符需要加引号。在send模式下必填该选项。

在工作目录下提前准备好两个文件:一个文件是脚本bash文件“chaosuan.sh”,第二个是与远端计算机连接的密钥文件“id_key”

# 脚本的使用方法(以下方式均可)
bash chaosuan.sh -h 
bash chaosuan.sh --help
# 输出结果为
# Usage: bash chaosuan.sh [-o|--option] [-r|--remote] [-l|--local]
# option: connect (1|c) receive (2|r) send (3|s)

# 连接远端计算机(以下方式均可,类似ssh命令)
bash chaosuan.sh --option connect 
bash chaosuan.sh -o c
bash chaosuan.sh -o 1 

# 发送本地文件到远端(以下方式均可,类似scp命令)
bash chaosuan.sh --option send -l localfile_or_localdir -r remotefile_or_remotedir 
bash chaosuan.sh -o s -l localfile -r remotefile 
bash chaosuan.sh -o 3 -l localfile 

# 接收远端文件到本地(以下方式均可,类似scp命令)
bash chaosuan.sh --option receive  -r remotefile_or_remotedir -l localfile_or_localdir
bash chaosuan.sh -o r  -r remotefile -l localfile 
bash chaosuan.sh -o 2 -r remotefile 

脚本名称为“chaosuan.sh”:

#!/bin/bash
#time:  2022-10-8
#email: [email protected]
#首先根据调试好的ssh命令修改web里的内容
web=”ssh.cn-xxxxxxx.com“

usage() {
    echo "Usage: bash ${0} [-o|--option] [-r|--remote] [-l|--local]"
    echo "option: connect (1|c) receive (2|r) send (3|s)" 1>&2
    exit 1
}

r=" "
l=" "
while [[ $# -gt 0 ]]; do 
    key=${1}
    case ${key} in 
        -o|--option)
            o=${2}
            shift 2
            ;;
        -r|--remote)
            r=${2}
            shift 2
            ;;
        -l|--local)
            l=${2}
            shift 2
            ;;
        *)
            usage 
            shift
            ;;
    esac
done


if [ ${o} == "c" ] || [ ${o} == "connect" ] || [ ${o} == "1" ]; then
  ssh -i id_key ${web}
elif [ ${o} == "r" ] || [ ${o} == "receive" ] || [ ${o} == "2" ]; then
  scp -i id_key -r ${web}:/home/username/${r} ${l}
elif [ ${o} == "s" ] || [ ${o} == "send" ] || [ ${o} == "3" ]; then
  scp -i id_key -r ${l} ${web}:/home/username/${r}
else 
  usage
fi

__EOF__


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK