在使用scp

时间:2015-04-22 13:34:18

标签: bash ip-address scp

我正在编写文件传输脚本,它变得相当复杂。因此,在我生成要转移的IP地址的开头,我想验证我确实可以连接到它。该区域的代码如下所示:

USER_ID=$1
if [[ $GROUP == "A" ]]; then
    ADDRESS="${USER_ID}@morgan.company.gov"
elif [[ $GROUP == "B" ]]; then
    ADDRESS="${USER_ID}@mendel.company.gov"
else
    log_msg fatal "Couldn't resolve group $GROUP. Exiting"
    exit 1;
fi

// HERE I want to test that $ADDRESS exists, and I can connect right now I
// have what is below.  I just think there is a better way to do it

ssh -q $ADDRESS exit
if [ $? != 0 ]; then
    log_msg fatal "Couldn't resolve host, do you have login privileges with $ADDRESS"
fi

... // lots of other things happen

scp $ADDRESS:$INCOMING_FILE $NEW_FILE 

我的作品,但它似乎不是一个优雅的解决方案。我不想实际ssh并退出服务器,只是测试连接。

3 个答案:

答案 0 :(得分:1)

您可以使用此shell函数测试主机是否打开ssh端口:

#!/bin/bash
function isUp(){
    local ip=$1
    local sshport=22
    if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        if [[ $(nmap -P0 $ip -p$sshport | grep ^$sshport | cut -d' ' -f2) == "open" ]]; then
            return 0
        else
            return 1
        fi
    fi
}
if isUp $1; then
    ssh $1 uptime
else
    echo "Host $1 is not available"
fi

或使用这个(对我而言)bash功能:

#!/bin/bash
function isUp(){
   local ip=$1
   if echo > /dev/tcp/$ip/22 >/dev/null 2>&1; then
      return 0
   else
      return 1
   fi
}

答案 1 :(得分:0)

如果您想彻底检查连接,那么最好分析return codes from an scp connection。这将使您了解连接失败的原因并因此而行动(在不同级别可能存在各种原因,例如,从通常缺乏连接到关键问题)。

如果您只对二进制答案感兴趣(“我的连接是否正常?”)那么您的代码很好,但我会直接使用scp

答案 2 :(得分:0)

你的行没有错:

ssh -q $ADDRESS exit

这是测试连接的最佳/最快方式。