分享一個連接遠端電腦與傳輸文件的腳本

分享一個連接遠端電腦與傳輸文件的腳本

用了一個月超頻,由於本地是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
Tags: