1

我从 perl 脚本中摘录了以下用于自动化 FTP 会话的摘录,我希望有人能解释它是如何工作的。

system("rsh some_server ftp -in ftp.something.com << !
user anonymous someone\@somewhere.org
some ftp commands
bye");

的背景。这个 perl 脚本在 Linux 机器上运行,它远程连接到 Solaris 机器。FTP 会话必须从 Solaris 机器执行,因为 FTP 站点执行 IP 地址检查。

以前这个脚本直接在 Solaris 机器上运行(即它不使用 rsh),我修改了它并想出了这个似乎可行的方法。但是我不知道如何,特别是我不理解<< !第一行末尾的那一点。它看起来有点像这里的文档,但我不太确定。

欢迎任何解释。

4

2 回答 2

2

You are right, << is a heredoc, which is made clear by the following warning (which I get when I take out the rsh command):

sh: line 2: warning: here-document at line 0 delimited by end-of-file (wanted `!')

The construct

<< HEREDOC

reads as standard input everything from HEREDOC up to a line containing only HEREDOC or up to an end-of-file character. When you put this after a command, it is equivalent to

command < file

where file contains the text in the heredoc. In your case, instead of HEREDOC the delimiter is !, so the ! is not passed to ftp but everything after ! is. This is equivalent to

$ cat file
user anonymous someone\@somewhere.org
some ftp commands
bye
$ ftp -in ftp.something.com < file

rsh takes that entire command and runs it on your remote host.

As illustrated by user1146334's answer, this command does not act on the principal of least surprise. At the very least, make it less confusing by changing it to

system("rsh some_server ftp -in ftp.something.com << HEREDOC
user anonymous someone\@somewhere.org
some ftp commands
bye
HEREDOC");

Or even better, as mpapec mentioned in the comments, use Net::FTP and Net::SSH2.

于 2013-08-14T16:42:59.190 回答
0

你看过手册页吗?

-i    Turns off interactive prompting during multiple file transfers.

-n    Restrains ftp from attempting “auto-login” upon initial connection.  If auto-login is enabled, ftp will check the .netrc (see netrc(5)) file in the user's
       home directory for an entry describing an account on the remote machine.  If no entry exists, ftp will prompt for the remote machine login name (default is
       the user identity on the local machine), and, if necessary, prompt for a password and an account with which to login.


 The client host and an optional port number with which ftp is to communicate may be specified on the command line.  If this is done, ftp will immediately attempt
 to establish a connection to an FTP server on that host; otherwise, ftp will enter its command interpreter and await instructions from the user.  When ftp is
 awaiting commands from the user the prompt ‘ftp>’ is provided to the user.  The following commands are recognized by ftp:

 ! [command [args]]
             Invoke an interactive shell on the local machine.  If there are arguments, the first is taken to be a command to execute directly, with the rest of
             the arguments as its arguments.

所以本质上你是在 ftp'​​ing 并在每行内联而不是从文件中提供一个新命令。

于 2013-08-14T14:36:16.830 回答