我正在创建一个脚本来测试HELO的电子邮件..
直接在telnet
控制台中,命令运行正常,但在脚本中,我无法获得输出。
在bash中:
$ telnet alt1.aspmx.l.google.com 25
HELO verify-email.org
MAIL FROM: <check@verify-email.org>
RCPT TO: <test@gmail.com>
quit
结果:
root@san [~]# telnet alt1.aspmx.l.google.com 25
Trying 2a00:1450:4010:c09::1a...
Connected to alt1.aspmx.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP qm6si6508388lbb.110 - gsmtp
HELO verify-email.org
250 mx.google.com at your service
MAIL FROM: <check@verify-email.org>
250 2.1.0 OK qm6si6508388lbb.110 - gsmtp
RCPT TO: <test@gmail.com>
550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 https://support.google.com/mail/answer/6596 qm6si6508388lbb.110 - gsmtp
quit
221 2.0.0 closing connection qm6si6508388lbb.110 - gsmtp
Connection closed by foreign host.
在剧本中:
cat << EOF | telnet alt1.aspmx.l.google.com 25
HELO verify-email.org
MAIL FROM: <check@verify-email.org>
RCPT TO: <test@gmail.com>
quit
EOF
OR
{ echo "HELO verify-email.org"; sleep 1; echo "MAIL FROM: <check@verify-email.org>"; sleep 1; echo "RCPT TO: <test@gmail.com>" ; sleep 1 ; echo quit } | telnet alt1.aspmx.l.google.com 25
OR
#!/usr/bin/expect -f
spawn alt1.aspmx.l.google.com 25
send '"HELO verify-email.org\r"'
send '"MAIL FROM: <check@verify-email.org>\r"'
send '"RCPT TO: <test@gmail.com>\r"'
send '"quit\r"'
OR
sh aa 1> aa.txt 2>&1
OR
sh aa &> aa.txt
没有结果。
答案 0 :(得分:3)
通常,您可能不希望将内容管道传输到telnet。一个合理的替代方案是netcat
(在大多数系统上都是nc
。
那就是说,我前一段时间写了a tiny bash HTTP client,依靠bash的内部支持来建立TCP套接字连接。 SMTP客户端稍微复杂一些,但仍然相当容易。 SMTP很好。您可以加载一堆命令,然后只需一次读取多个响应行。
#!/usr/bin/env bash
target="$1"
address="$2"
success=""
# Open a two-way socket connection on fd/3
exec 3<>/dev/tcp/$target/25
# Stand back, we're doing SMTP!
printf "HELO $HOSTNAME\r\n" >&3
printf "MAIL FROM: <$USER@$HOSTNAME>\r\n" >&3
printf "RCPT TO: <$address>\r\n" >&3
printf "QUIT\r\n" >&3
# Now that we've had our say, it's time to listen.
while read -u 3 code message; do
echo ">> <$code> ${message%$'\r'}" # Debugging output
case "$code" in
2??) success="${success:-true}" ;; # Only set variable if it's not already set
5??) success=false ;; # (i.e. false overrides all other responses)
esac
done
# Close connections, clean up after ourselves
exec 3<&-; exec 3>&-
if [ -z "$success" ]; then
echo "NOTICE: Not sure we reached an SMTP server..."
exit 1
elif $success; then
echo "NOTICE: All's well, $target accepts mail for $address"
else
echo "NOTICE: I detected a failure."
exit 1
fi
请注意${message%$'\r'}
的参数扩展,如果它是CR,则会删除该行中的最后一个字符。这样做是因为SMTP响应使用\r\n
作为换行符,而您的脚本可能认为\r
仅仅是行的一部分(或$ message变量)。