使用 Netcat 发送电子邮件

是否可以从没有安装电子邮件客户端软件的主机发送电子邮件? 只要您有 netcat,当然可以!

Netcat(在 Red Hat Enterprise Linux 系统上为 /usr/bin/nc)是一个简单的实用程序,用于通过 TCP/UDP 连接读取和写入数据。 它通常用于测试和调试网络连接。 在其最基本用法中,netcat 允许您将数据流发送到特定主机上的特定端口,这非常适合我们的目的。 查看 netcat 手册页以获取有关其各种功能的更多信息。 /usr/share/doc/nc-*/ 下也有示例脚本。 如果您的 Red Hat Enterprise Linux、CentOS 或 Fedora 系统上未安装 netcat,您可以使用以下命令安装它yum install nc.

我们将使用 netcat 将数据流发送到邮件中继上的端口 25 (SMTP),使其相信它正在与常规电子邮件客户端通信。 为了做到这一点,我们首先需要弄清楚我们的电子邮件服务器希望从客户端看到什么。 这可以通过使用 telnet 连接到我们的 SMTP 中继主机并发出正确的 SMTP 命令来完成,如下例所示

   [user@host]# telnet smtp.domain.com 25
   Trying 192.168.0.1...
   Connected to smtp.domain.com (192.168.0.1).
   Escape character is '^]'.
   220 myrelay.domain.com ESMTP
   HELO smtp.domain.com
   250 myrelay.domain.com
   MAIL FROM:<alice@hacker.com>
   250 sender <alice@hacker.com> ok
   RCPT TO:<bob@secure.net>
   250 recipient <bob@secure.net> ok
   DATA
   354 go ahead
   From: [Alice Hacker] <alice@hacker.com>
   To: [Bob Smith] <bob@secure.net>
   Date: Mon, 12 Apr 2010 14:21:26 -0400
   Subject: Test Message

   Hi there!
   This is supposed to be a real email...

   Have a good day!
   Alice


   .
   250 ok:  Message 222220902 accepted
   QUIT
   221 myrelay.domain.com
   Connection closed by foreign host.
   [user@host]#

请注意,“From”地址的 userid 部分不必包含有效的 userid,只需包含有效的域名即可。 您必须将“smtp.domain.com”替换为允许从您的主机中继的有效 SMTP 中继。 通常,经验丰富的管理员会禁止从未知主机进行中继,以阻止垃圾邮件。 此外,电子邮件的正文(“DATA”命令之后的所有内容)以发送一个空行结束,后跟一个单独包含句点 (.) 的行。

现在我们知道了远程服务器希望看到什么,我们可以创建一个包含我们的 SMTP 命令和要发送的消息的文本文件。 收件人的邮件服务器将期望日期采用特定格式。

使用命令

date '+%a, %d %b %Y %H:%M:%S %z'

生成类似于以下的日期字符串

Mon, 12 Apr 2010 14:21:26 -0400

您的消息文件的内容应类似于此示例

   HELO host.example.com
   MAIL FROM:<test@host.example.com>
   RCPT TO:<bob@example.com>
   DATA
   From: [Alice] <alice@geek.com>
   To: <bob@example.com>
   Date: Mon, 12 Apr 2010 14:21:26 -0400
   Subject: Test Message

   Hi there! This is supposed to be a real email...

   Have a good day!
   Alice


   .
   QUIT

现在我们可以将此文本文件发送到 netcat 程序,如下所示

   # /usr/bin/nc smtp.domain.com 25 

And your email has been sent!

Again, what we did here was feed data to netcat, which then sends that data to port 25 on the specified host (our mail relay). Since we've formatted the data to look like an email. the SMTP server accepts it as it would any other email and sends it, assuming of course that we're allowed to relay email.

Given a little time and effort, a nice bash or korn shell script can be written that automates the creation of the message text file. You can specify multiple recipients in the email header, and include the output of other commands in the body of the email. For example, a monitoring script which is periodically executed via a cron job can email it's standard output to a list of recipients.

加载 Disqus 评论