通过 shell 脚本使用 telnet 的交互式 SMTP 命令

通过 shell 脚本使用 telnet 的交互式 SMTP 命令

我正在尝试使用 telnet 和一个命令文件通过远程 shell 访问 SMTP 远程服务器,该命令文件command.txt包含发送到该 SMTP 服务器的命令,如上所示https://tecadmin.net/ways-to-send-email-from-linux-command-line/#(注意:在上面的网站上,这是交互完成的)但在这里我想在命令文件中执行此操作(我刚刚将黄色/红色(用户输入))复制到命令文件中。

HELO yahoo.com
mail from: [email protected]
rcpt to: [email protected]
data

Hey
This is test email only

Thanks
.

quit

然后使用telnet IP smtp < command.txtalways返回:

Trying 1.1.65.49...
Connected to 1.1.65.49.
Escape character is '^]'.
Connection closed by foreign host.

而当我与以下人员交互时:

perlhook@bbis:~/temp_25$ telnet 1.1.65.49 smtp
Trying 1.1.65.49...
Connected to 1.1.65.49.
Escape character is '^]'.
220 miraino-manabi.jp ESMTP Postfix
HELO yahoo.com
250 miraino-manabi.jp
mail from: [email protected]
250 2.1.0 Ok
rcpt to: [email protected]
554 5.7.1 <[email protected]>: Relay access denied
^]
telnet> quit

我收到返回码220 250 554

我还在here-doc shell脚本中尝试过,如下所示:

telnet 1.1.65.49 smtp <<END_SCRIPT
HELO yahoo.com
mail from: [email protected]
rcpt to: [email protected]
data

Hey
This is test email only

Thanks
.

quit
END_SCRIPT

并得到相同的结果。

我怎样才能解决这个问题并使脚本表现得像交互式的一样?

答案1

telnet由于各种原因而失败。首先,如果您strace发现相关错误是telnet需要标准输入上的 TTY,但其中没有(由于重定向),因此telnet会失败。

$ strace telnet mx.example.edu 25 < input
...
ioctl(0, SNDCTL_TMR_STOP or TCSETSW, {B0 -opost -isig -icanon -echo ...}) = -1 ENOTTY (Inappropriate ioctl for device)
ioctl(0, SNDCTL_TMR_START or TCSETS, {B0 -opost -isig -icanon -echo ...}) = -1 ENOTTY (Inappropriate ioctl for device)

如果改为使用ncor netcat,非交互式发送可能仍然是一个问题;要么一次性发送太多数据(这会让远程服务器感到困惑),要么服务器会过快地拒绝太多数据; SMTP 是一种交互式对话。如果一方正在轰炸,另一方可能会延迟或拒绝(发送太快可能表明垃圾邮件发送者)。如果您nc支持--delay并且远程邮件服务器原谅您可能能够发送。

$ strace -s 80 nc --crlf --delay 1 mx.example.edu 25 < input
...
recvfrom(3, "220 mx.example.edu ESMTP OpenSMTPD\r\n", 8192, ...
...
sendto(3, "HELO client.example.edu\r\nmail from: [email protected]\r\n...
...
shutdown(3, SHUT_WR)                    = 0
...
recvfrom(3, "500 5.5.1 Invalid command: Pipelining not supported\r\n",

这里OpenSMTPD拒绝发送;不同服务器上的 Postfix(此处未显示)允许上述发送。

实际上应该使用使用 SMTP 协议的 SMTP 客户端;这可以与类似的东西混在一起expect https://stackoverflow.com/questions/12320592/telnet-smtp-with-expect-or-shell-script否则,有各种语言的各种 SMTP 库将支持 TLS、SMTP AUTH、处理错误等。 shell 在这里不是一个好的选择...除非您使用像 ZSH 这样的 shell 的 TCP 功能,但可能有比“这里没有发明”另一个 SMTP 客户端更好的事情要做...

相关内容