- The Windows 95/98/NT Command-Line (Console) » ftp » Client Program
- Some Real FTP Server Examples:
- Каталог статей
- Три способа передачи файлов по FTP средствами Windows
- How do I use FTP from a command line?
- Connect using FTP
- Send and receive a file in FTP
- FTP commands
- MS-DOS Commands :: ftp
- Overview:
- Commands:
- Automation:
The Windows 95/98/NT Command-Line
(Console) » ftp » Client Program
If you type the letters ftp at a DOS-Window (Command Line) prompt, like this:
C:\WINDOWS> ftp you will be placed into an interactive program with its own prompt: ftp>
Entering a question mark (?) or the word «help» will output a list of commands on your screen like this: The ftp program in Windows 95 breaks the general rule of how you obtain help information directly from the command line. In most cases, you’d type the name followed by a space, a forward slash(/) and a question mark(?) to get it. But ftp requires a dash(-) and an (h) instead: These commands show that you can run ftp «in the background» as it’s called without ever having to interact with the program yourself. For now, let’s use the program interactively to figure out what the commands actually do:
The first thing you need to be aware of is that all the commands within ftp are case-sensitive. Commands to your own ftp program (those listed above) use only lower-case characters. For example, entering «HELP» at the ftp prompt, outputs this on your screen: ?Invalid command
Here’s the list of commands and a brief explanation of each one taken directly from the ftp helps within the program (and a few comments of my own):
Directory Commands: File Commands: Ending a Session:
Some Real FTP Server Examples:
Normally one would connect to a remote server by entering its URL on the same line as the ftp command itself (this way you can skip having to use the ‘open’ command). Our first fragment starts out this way ( I just thought you might like to see the header from Microsoft’s FTP server): This next example is longer and contains a number of commands in action: This last example is even longer and contains a file download among other things. This is the Geocities server that all the webpage authors use, so it can get pretty slow at times:
Windows 95/98 MS-DOS 7.0.
How To Make a Boot Disk.
«The Starman’s Realm» Home Page .
Каталог статей
Sets the root of the files visible to users of the
server.
e.g. ftproot=c:\myfiles
Default: c:\ftpfiles
ftp_alias= ,
Define an alias directory: whenever a user access a
path beginning with the server will
substitute
. You may use aliases to allow
access to several parts of a DOS drive, or to access
several different drives. For example:
ftp_alias=/drive-d,d:\
allows users to access drive D: using the path
/drive-d
You can have up to 4 aliases.
ftp_port=
Sets the port number used for connections to the
server, where
is between 1 and 65535.
e.g. ftp_port=2121
Default : 21
Anonymous=[yes|no] Allow or deny access to anonymous users. An
anonymous user may log in with the user name
“anonymous” and any non null password.
Default: no
ftp_timeout= Determine the length of time (in seconds) before an
ftp session is terminated. In most cases a timeout is
necessary to prevent inactive ftp sessions from
preventing other users to access the server. Only 2
concurrent sessions are allowed.
E.g. ftp_timeout=900
Default: 600 (10 minutes)
MaxTickSlice=[1..32768] The maximum number of 55ms timer ticks the web
server will run before suspending
e.g. maxTickSlice=2
Default: 1
MinTickGap=[1..32768] The minimum number of 55ms timer ticks before
2netftp resumes following a suspend.
e.g. minTickGap=2
Default: 1
мой файл 2net.cfg вообще простенький
мне достаточно этого
[2netftp]
ftproot=c:\
[network]
my_ip=192.168.1.11
netmask=255.255.255.0
Скачать сервер можно в каталоге файлов на нашем сайте
Скачать файл
Три способа передачи файлов по FTP средствами Windows
Утилиту «ftp.exe», входящую в состав Windows по умолчанию, можно запустить из командной строки. Она позволяет скачивать и загружать файлы по протоколу FTP вручную, но главное ее достоинство — функции автоматизации. С ее помощью можно запланировать и автоматизировать передачу файлов по FTP на регулярной основе.
Чтобы получить справку по утилите FTP, введите в командной строке ftp -? и нажмите [Enter]. Чтобы посмотреть список доступных команд, введите ftp и нажмите [Enter] для запуска утилиты, а затем введите ? и снова нажмите [Enter]. Для завершения работы утилиты введите bye и нажмите [Enter].
Для автоматизации загрузки и скачивания можно использовать командные файлы и сценарии FTP. Ниже приводятся примеры таких сценариев. Замените в них выделенный курсивом текст на нужное имя хоста, имя пользователя, пароль, путь к локальному файлу и путь к удаленному каталогу.
Передача одного файла
Скопируйте в Блокнот (Notepad) следующий текст, подставив нужные значения, и сохраните его как «H:\TransferTest\transfer.bat».
• ftp — запускает утилиту FTP;
• -v — отключает вывод информации об ответах удаленного FTP-сервера;
• -n — отключает автоматический вход;
• -s: — указывает путь к файлу, содержащему команды для FTP-передачи. Путь не должен содержать пробелов .
Затем скопируйте в Блокнот следующий текст, подставив нужные значения, и сохраните его как «H:\TransferTest\transfer.ftp».
• open — открывает удаленный FTP-сервер;
• user — указывает имя пользователя для входа на сервер;
• password — указывает пароль для входа на сервер;
• cd — переходит в указанный удаленный каталог для загрузки файлов, в данном примере — «/public_ftp/test»;
• put — загружает указанный локальный файл на удаленный сервер; кавычки можно не использовать, если путь не содержит пробелов;
• bye — завершает сеанс подключения и работу утилиты FTP.
Совет: команды FTP можно сокращать до трех символов — например, использовать bin вместо binary.
Еще один совет: длинные пути неудобно вводить вручную — это слишком долго, да к тому же, высока вероятность совершить ошибку. Чтобы облегчить себе задачу, воспользуйтесь одним из следующих методов:
• Откройте в Проводнике папку, в которой хранится нужный файл, нажмите правой кнопкой мыши на любом фрагменте адреса в адресной строке и выберите опцию «Копировать адрес как текст» (Copy Address as Text). Вставьте скопированный адрес в сценарий FTP и добавьте к нему имя файла.
• Нажмите правой кнопкой мыши на файле в Проводнике, выберите опцию «Свойства» (Properties) и откройте вкладку «Безопасность» (Security). Скопируйте полный путь к файлу из строки «Имя объекта» (Object name) и вставьте его в сценарий FTP.
В командной строке введите H:\TransferTest\transfer.bat и нажмите [Enter] или запустите командный файл двойным щелчком. При этом может появиться предупреждение безопасности, показанное на рис. I.
Для скачивания файла с удаленного сервера на клиентский ПК используется команда get.
Передача нескольких файлов
Скопируйте в Блокнот следующий текст, подставив нужные значения, и сохраните его как «H:\TransferTest\multiple_transfer.bat».
Скопируйте в Блокнот следующий текст, подставив нужные значения, и сохраните его как «H:\TransferTest\multiple_transfer.ftp».
• open — открывает удаленный FTP-сервер;
• user — указывает имя пользователя для входа на сервер;
• password — указывает пароль для входа на сервер;
• cd — переходит в указанный удаленный каталог для загрузки файлов, в данном примере — «/public_ftp/test»;
• prompt — отключает интерактивные приглашения на ввод при загрузке множественных файлов с использование команды mput;
• mput — загружает указанные файлы ASCII с локального ПК; кавычки можно не использовать, если путь не содержит пробелов;
• lcd — переходит в указанный локальный каталог, в котором хранятся файлы для загрузки, в данном примере — «\Projects\PSWW\VIC\Package»;
• binary — переключается в режим двоичной передачи;
• mput — загружает указанные бинарные файлы с локального ПК; кавычки можно не использовать, если путь не содержит пробелов;
• bye — завершает сеанс подключения и работу утилиты FTP.
Теперь в командной строке введите H:\TransferTest\multiple_transfer.bat и нажмите [Enter] или запустите командный файл двойным щелчком (рис. K).
Обратите внимание — я использовал команду cd для смены каталога в командном файле и команду lcd для смены локального каталога в сценарии FTP, чтобы упростить команду mput за счет использования относительного пути вместо полного.
Совет: пробелы в именах файлов могут привести к возникновению проблем при передаче файлов, поэтому вместо них желательно использовать подчеркивания, если это возможно.
Команда mput позволяет загрузить несколько файлов с клиентского компьютера на удаленный сервер. Если на сервере такие файлы уже существуют, они будут заменены.
Для скачивания нескольких файлов с удаленного сервера на локальный ПК используйте команду mget.
Передача текстовых и бинарных файлов
Передача текстовых (ASCII) и двоичных файлов с помощью утилиты FTP осуществляется по-разному. По умолчанию, утилита загружает файлы в режиме ASCII — именно такой способ используется в приведенном выше примере с передачей одного файла. В примере с загрузкой нескольких файлов присутствуют оба типа файлов — и ASCII, и бинарные. Чтобы предотвратить потерю данных, необходимо использовать подходящий метод передачи для каждого конкретного файла.
При передаче файлов по протоколу FTP возникает очевидная угроза безопасности. Если имя пользователя и пароль хранятся в незашифрованном текстовом файле, их может украсть любой, кто имеет доступ к компьютеру. Так что сценарий FTP стоит зашифровать. Подробнее о шифровании можно узнать в штатной справке Windows, воспользовавшись поиском по ключевому слову «шифрование». Нужные сведения содержатся в разделе «Шифрование или расшифровка папки или файла» (Encrypt or Decrypt a Folder or File). О шифровании в Windows 2000, Windows Server 2003, Windows XP, Windows Vista и Windows 7 рассказывается также на сайте Microsoft. В Википедии приводится полный версий Windows, поддерживающих систему шифрования данных Encrypting File System (EFS). Кроме того, можно воспользоваться сторонним приложением для шифрования, например, TrueCrypt.
Проблемы при использовании брандмауэра
Если при попытке подключиться к FTP-серверу вы получаете сообщение об ошибке «425 Невозможно установить соединение: Время ожидания истекло» (Unable to build data connection: Connection timed out), скорее всего, проблема связана с брандмауэром. Утилита FTP не поддерживает передачу данных в пассивном режиме, поэтому при использовании брандмауэра могут возникать ошибки в передаче данных. Я сталкивался с такой проблемой при использовании Comodo Firewall 4.0. Чтобы ее устранить, необходимо разрешить утилите FTP удаленный доступ в настройках брандмауэра.
Прежде чем пускаться на поиски стороннего приложения для работы с FTP, обратите внимание на встроенные инструменты Windows. Возможно, одного из описанных методов будет вполне достаточно для выполнения стоящих перед вами задач.
Автор: Alan Norton
Перевод SVET
How do I use FTP from a command line?
To connect to and use FTP from a command line interface, like MS-DOS or the Linux shell, click a link below for instructions.
FTP is not an encrypted transmission, which means any data sent over it, including your username and password, could be read by anyone intercepting your transmission. If you want a more secure transmission, we suggest using SFTP.
Connect using FTP
To connect to another computer using FTP at the MS-DOS prompt, command line, or Linux shell, type FTP, and press Enter . Once in FTP, use the open command to connect to the FTP server, as shown in the following example.
In the example above, you’d substitute example.com for the domain name or IP address of where you are connecting. An example would be open 192.168.1.12.
By default, the open command uses the TCP port 21 to make the FTP connection. If a different TCP port is needed to connect, enter the port number after the domain name or IP address in the open command.
Once connected, a username and password prompt appears. Once these credentials are entered, the server allows you to browse, send, or receive files, depending on your rights. Some servers may also allow anonymous logins using guest or an e-mail address.
Send and receive a file in FTP
To get files from the server onto your computer, use the get command, as shown in the following example. In this example, you would get the file myfile.htm.
If you want to get more than one file, use mget and wildcards. For example, if you wanted to get all files that end with .htm, you could type mget *.htm. Finally, if you do not want to be prompted as each file is being sent, make sure to type prompt to disable prompting.
Use the send command, as shown in the following example, to move a file to another connected computer. In this example, we are sending the myfile.htm to the current directory.
It is important to realize that the files being sent must be in your local working directory. In other words, the directory you were in when you typed the FTP command. If you want to change to the local directory containing your files, use the lcd command. For example, in Windows, you’d type lcd c:\windows to set the local directory to the Windows directory.
FTP commands
Depending on the version of FTP and the operating system, each of the following commands may or may not work. Typing -help or a ? lists the commands available to you. Below is a general description of FTP commands available in the Windows command line FTP command.
MS-DOS Commands :: ftp
Overview:
Warning: This command is for advanced users only!
FTP (file transfer program) to transfer files to/from server.
Tip: We recommend that you use a FTP program rather than using the ftp command. Personally, we use .
Commands:
Type ftp to start the FTP program. The FTP command prompt will appear. You can then type the following commands.
Tip: When done, type bye (or quite ) to exit the FTP program and return to the prompt.
Command | Meaning |
! | Escape to the shell |
? | Prints list of available commands |
append | Append to a file |
ascii | Set ascii transfer type |
bell | Beep when command completed |
binary | Set binary transfer type |
bye | Terminate ftp session and exit |
cd | Change remote working directory |
close | Terminate ftp session |
delete | Delete remote file |
debug | Toggle debugging mode |
dir | List contents of remote directory |
disconnect | Terminate ftp session |
get | Receive file |
glob | Toggle metacharacter expansion of local file names |
hash | Toggle printing `#’ for each buffer transferred |
help | Prints list of available commands |
lcd | Change local working directory |
literal | Send arbitrary ftp command |
ls | List contents of remote directory |
mdelete | Delete multiple files |
mdir | List contents of multiple remote directories |
mget | Get multiple files |
mkdir | Make directory on the remote machine |
mls | List contents of multiple remote directories |
mput | Send multiple files |
open | Connect to remote tftp |
prompt | Force interactive prompting on multiple commands |
put | Send one file |
pwd | Print working directory on remote machine |
quit | Terminate ftp session and exit |
quote | Send arbitrary ftp command |
recv | Receive file |
remotehelp | Get help from remote server |
rename | Rename file |
rmdir | Remove directory on the remote machine |
send | Send one file |
status | Show current status |
trace | Toggle packet tracing |
type | Set file transfer type |
user | Send user login information |
verbose | Toggle verbose mode |
Automation:
If you want to automate the downloading/uploading of a file or files, you can do that by creating a text file that contains the FTP commands to be performed. For example, to download a specific file, create a text file that has the following content: