Bash脚本中需要FTP连接确认

问题描述 投票:0回答:3

我正在使用以下代码连接ftp节点。我只想知道如何检查无法连接ftp服务器或ftp服务器没有响应。无论如何,它都会提醒我ftp服务器正常或故障。实际上,我想嵌入普通的bash代码以检查连接性。

#!/bin/ksh  
ftp -nv <<EOF  
open xxx.xx.xx.xx  
user xxx xxxxxxxxx  
bye  
EOF  
ftp ksh
3个回答
1
投票

如何对ftp的输出进行grep处理?我不确定成功上传后您的ftp版本会返回什么,但是类似:

#!/bin/ksh

(
ftp -nv <<EOF
open xxx.xx.xx.xx
user xxx xxxxxxxxx
bye
EOF
) | grep -i "success"
if [[ "$?" -eq "0" ]]
then
        echo "FTP SUCCESS"
else
        echo "FTP FAIL"
fi

应该工作..


0
投票

我之前遇到过同样的问题,通过检查ftp命令的输出来解决。尽管如此,发现它还是很奇怪,所以我决定使用PERL。

#!/usr/bin/perl
use strict;
use warnings;
use Net::FTP;

# open connection
my $ftp = Net::FTP->new("127.0.0.1");
if (! $ftp) {
    print "connection failed!";
    exit 1;
}

# in case you would need to test login too
# if (! $ftp->login("username", "password")) {
#    print "login failed!";
#    exit 2;
#}

$ftp->close();
exit 0;

0
投票

使用此命令检查ftp服务器是否可用:

sleep 1 | telnet ftp.example.com 21 2> /dev/null | grep -c 'FTP'

它的作用:

  • [通过端口21建立到ftp.example.com的连接(对于sftp使用端口22)
  • 等待一秒钟然后终止连接
  • 忽略“远程主机关闭的连接”-来自telnet的“ 2> / dev / null”响应]
  • 如果来自被寻址服务器的响应包含“ FTP”,则返回“ 1”,如果不包含,则返回“ 0”。

如果您要检查的ftp服务器的预期欢迎响应与标准响应不同,则可能需要调整grep模式'FTP',该标准响应通常会读取以下内容:

   Trying 93.184.216.34...
   Connected to ftp.example.com.
   Escape character is '^]'.
   220 FTP Service
© www.soinside.com 2019 - 2024. All rights reserved.