- [bash] как залить файл на фтп скриптом?
- Как загрузить (FTP) файлы на сервер в bash-скрипт?
- 11 ответов
- безопасное решение:
- решение FTP, если вам это действительно нужно:
- Скрипт для удаленного копирования файлов через FTP
- Простой способ резервного копирования Linux-сервера с выгрузкой файлов по FTP
- Хозяйство
- Задача
- Решение
- How to Automate FTP transfers in Linux Shell Scripting
- What is FTP?
- How FTP Works?
- Working with files
- Automating the process
- What are we trying to do?
- The FTP command switches
- The heredocs
- But do you see any problem in this code?
[bash] как залить файл на фтп скриптом?
находил буржуские баш-скрипты для заливки файлов на фтп, но что-то всё не работает
подскажите, как это сделать?
в идеале хочу так:
#upload.sh test.txt
#Complete! http://ftp/folder/test.txt
как сделать это в баше?
man curl насчёт опции -T
или man ncftpput
Только примонтировать ftp не забудь
$ echo ‘put test.txt’ | lftp 192.168.1.2
Таким образом можно делать сколь угодно сложные вещи с ftp
Вот пример заливки бэкапа на серв
wput и прочие curl
Там для нормального логина нужно вроде так
PASS он спрашивает интерактивно если не указан. А явно прописывать его как сам понимаешь глупо.
Учитесь юзать поиск, такой простой вопрос наверняка задавали 1000 раз.
о, прямо мёд. обожаю линукс. всем спасибо
написал скрипт, теперь все предельно просто
upl test1.txt test2.zip test3.mp3 — все заливает по фтп без проблем
пришлось лишь установить curlftpfs
Источник
Как загрузить (FTP) файлы на сервер в bash-скрипт?
Я пытаюсь написать bash-скрипт, который загружает файл на сервер. Как я могу достичь этого? Является ли сценарий bash правильным для этого?
11 ответов
Ниже приведены два ответа. Во-первых, это предложение использовать более безопасное/гибкое решение, такое как ssh/scp/sftp. Второе объяснение, как запустить FTP в пакетном режиме.
безопасное решение:
вы действительно должны использовать SSH/SCP / SFTP для этого, а не FTP. SSH / SCP имеют преимущества быть более безопасными и работать с открытыми/закрытыми ключами, что позволяет ему работать без имени пользователя или пароля.
вы можете отправить один файл:
или весь каталог:
для получения более подробной информации о настройке ключей и перемещении файлов на сервер с помощью RSYNC, что полезно, если у вас есть много файлов для перемещения, или если вы иногда получаете только один новый файл среди набора случайных файлов, посмотрите на:
вы также можете выполнить одну команду после sshing на сервер:
ssh [. резавшую. ] имя хоста [команда] если команда указана, это выполняется на удаленном хосте вместо оболочки входа в систему.
Итак, пример команды:
если вы можете использовать SFTP с ключами, чтобы получить преимущество защищенного соединения, есть два трюка, которые я использовал для выполнения команд.
во-первых, вы можете передавать команды с помощью echo и pipe
вы также можете использовать пакетник с :
решение FTP, если вам это действительно нужно:
если вы понимаете, что FTP небезопасен и более ограничен, и вы действительно хотите написать его.
» — n » на ftp гарантирует, что команда не будет пытаться получить пароль от текущего терминала. Другая причудливая часть — использование heredoc: the запускает heredoc, а затем то же самое END_SCRIPT в начале строки сам по себе заканчивается heredoc. The binary команда установит его в двоичный режим, который поможет, если вы передаете что-то другое, чем текстовый файл.
можно использовать heredoc для этого, например,
таким образом, процесс ftp подается на stdin со всем до End-Of-Session . Полезный совет для нереста любого процесса, а не только ftp! Обратите внимание, что это экономит нерест отдельного процесса (echo, cat и т. д.). Не самая большая экономия ресурсов, но стоит иметь в виду.
установите ncftpput и ncftpget. Обычно они часть одного пакета.
Источник
Скрипт для удаленного копирования файлов через FTP
Уважаемые пользователи! Нужно перенести бэкапи из одного сервера на другой сервак
Вот протестировал данный скрипт, работает, вот только нужно чтобы он не все перенес а только новые бэкапи, а те которые уже есть на другом не переносил. Прошу помочь с данной задачой
#!/bin/bash HOST=IP USER=user PASSWORD=password
д смотрел этот rsync, просто интересно нельзя ли только скриптом обойтись
Winscp для винды умеет синхронизацию, надо искать под линукс подобное
Также есть rsync через ssh
д смотрел этот rsync, просто интересно нельзя ли только скриптом обойтись
Можно, конечно! Только скрипт надо поправить — заменить «ftp» на «rsync».
wget —no-clobber , но лучше таки rsync.
Нормальный gui синхронизации есть только в winscp
ftp очень старая и примитивная программа, и для скриптов не предназначенная. Используй луче lftp .
Файлы, которые уже есть не будут закачаны повторно.
Если сервер ругается, то set ftp:use-mdtm-overloaded on можно убрать — оно заставляет сохранять время изменения файла на получателе такое же как на источнике. Почитай man lftp там куча всего полезного, например, можно автоматически удалять файлы на источнике или наоборот удалять на получателе файлы, которых нет на источнике, обходить директории рекурсивно и многое другое.
Источник
Простой способ резервного копирования Linux-сервера с выгрузкой файлов по FTP
Здравствуйте.
О важности регулярного резервного копирования уже сказано очень много слов. В этой статье мы предлагаем вниманию читателей примеры простых скриптов для бэкапа файлов и баз данных MySQL с последующей выгрузкой архивов на удаленный FTP-сервер.
Несмотря на то что мы в NQhost предлагаем решения по сохранению snapshot’ов VPS-контейнеров, процесс бэкапа собственными силами — безусловно важнейшая вещь.
Хозяйство
Виртуальный или физический сервер с установленной Linux-ОС, веб-сервером и базами данных MySQL.
Файлы веб-сервера располагаются в директориях
/home/site1
/home/site2
/home/site3
Задача
Создание скрипта для резервного копирования файлов и баз данных с сохранением на удаленном FTP-сервере и запуск его каждый день.
Решение
Для простоты примера работать мы будем из-под root`а, директория для хранения бэкапов файлов — /root/backup/server, а для дампов MySQL — /root/backup/mysql
Backup файлов
Здесь приводится пример скрипта для бэкапа файлов, для наглядности пояснения даны в квадратных скобках на русском языке.
#!/bin/sh
### System Setup ###
BACKUP=/root/backup/server
### FTP ###
FTPD=»/»
FTPU=»username» [имя пользавателя (логин) удаленного ftp-cервера]
FTPP=»megapassword» [пароль доступа к удаленному ftp-серверу]
FTPS=»my_remote_backup.ru» [собственно, адрес ftp-сервера или его IP]
### Binaries ###
TAR=»$(which tar)»
GZIP=»$(which gzip)»
FTP=»$(which ftp)»
## Today + hour in 24h format ###
NOW=$(date +%Y%m%d) [задаем текущую дату и время, чтобы итоговый файл выглядел в виде server-YYYYMMDD.tar.gz]
mkdir $BACKUP/$NOW
$TAR -cf $BACKUP/$NOW/etc.tar /etc [c целью сохранения настроек для простоты копируем весь /etc ]
$TAR -cf $BACKUP/$NOW/site1.tar /home/site1/
$TAR -cf $BACKUP/$NOW/site2.tar /home/site2/
$TAR -cf $BACKUP/$NOW/site2.tar /home/site3/
$TAR -zcvf $ARCHIVE $ARCHIVED
### ftp ###
cd $BACKUP
DUMPFILE=server-$NOW.tar.gz
$FTP -n $FTPS
Результатом работы данного скрипта будет созданный файл в директории /root/backup/server вида server-ГГГГММДД.tar.gz содержащий в себе tar-архивы директорий /etc, /home/site1, /home/site2 и /home/site3
Этот же файл будет загружен на FTP-сервер, который мы указали в начале скрипта.
Backup баз MySQL
Этим скриптом мы выгружаем базы данных MySQL (делаем т.н. «дампы). Каждая база выгружается в отдельный файл.
#!/bin/sh
# System + MySQL backup script
### System Setup ###
BACKUP=/root/backup/mysql
### Mysql ### [параметры доступа к нашим базам MySQL]
MUSER=»root»
MPASS=»megapassword»
MHOST=»localhost»
### FTP ###
FTPD=»/»
FTPU=»username» [имя пользавателя (логин) удаленного ftp-cервера]
FTPP=»megapassword» [пароль доступа к удаленному ftp-серверу]
FTPS=»my_remote_backup.ru» [собственно, адрес ftp-сервера или его IP]
### Binaries ###
TAR=»$(which tar)»
GZIP=»$(which gzip)»
FTP=»$(which ftp)»
MYSQL=»$(which mysql)»
MYSQLDUMP=»$(which mysqldump)»
## Today + hour in 24h format ###
NOW=$(date +%Y%m%d)
### Create temp dir ###
### name Mysql ###
DBS=»$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse ‘show databases’)»
for db in $DBS
do
Источник
How to Automate FTP transfers in Linux Shell Scripting
Whether you are responsible for uploading files regularly to a remote web server, or syncing configuration files among a number of machines, most of the time you’ll find yourself using the FTP protocol.
But what about automating the process?
Could you simply add a shell script to a Crontab job and let it take care of all the FTP login process, file transfers, and essentially has the job done for you while you’re away from your desk?
If this sounds interesting, read along. Here, you will learn how to automate FTP transfers in Linux Shell Scripting.
What is FTP?
FTP stands for File Transfer Protocol. The protocol specifications were written by Abhay Bhushan. In April 1971, the Request for Comments (RFC) 114 was published to describe the newly developed protocol.
How FTP Works?
Using interactive mode
OK, so before we delve in, let’s have a quick refresher on FTP commands and usage for those who are accustomed to using GUI applications like FileZilla. In its simplest form, you can connect to a remote server using FTP using one of the following ways:
1. Type FTP then type open hostname, where hostname is the IP address or the hostname of the remote server you’re connecting to. You’ll be asked to enter your username and password. An example of this is in the following figure:
2. Type ftp hostname to avoid having to type open after starting the FTP session
3. Type ftp [email protected] where username is the username used to connect to the server. This will let you jump right into the password prompt.
Working with files
So now we’re connected to the remote server, what’s next? The following is a list of most common commands you’ll need in your FTP session:
Command | Usage |
ls | List files on the remote server |
get file | Download file |
mget file* | Download multiple files. You can use wildcards (*) to download all files with specific filename pattern. For example mget *.log to will download all files with extension .log |
put file | Upload file |
mput file* | Upload multiple files. You can use wildcards (*) the same way they’re used with mget |
cd | Navigate to a path on the remote server. Example: cd /tmp/uploads |
lcd | Navigate to a path on the local server (your machine). Example: lcd /home/myuser |
bin | Choose binary mode for file transfer |
ascii | Choose ascii mode for file transfer |
bye | Exits the current session |
Tip: You can always execute a command on your local machine while in an FTP session with the remote server by prefixing it with an exclamation mark (!). Example: !ls will list the files and directories on your local machine’s current path.
Automating the process
So now you have a basic idea about how to connect to a remote server using FTP and execute basic commands. Let’s see how you can automate the process.
What are we trying to do?
The rest of the article describes how to automate logging into a remote server using FTP and working with files. To accomplish this, you’ll log in to the FTP server in a slightly different manner than the previous methods. We are trying to automate the following example:
The FTP command switches
In the previous example, we used a long way to connect to FTP. First, we specified the -n switch to disable the auto-login feature (FTP expects the login user to be the current user), we manually specified the hostname using the open command, then we specified the username and password using the user command. A couple of additional important switches can be used in this task:
-i: Turns off interactive prompting during multiple file transfers. (The normal FTP behavior is to ask you before uploading or downloading files if they are multiple, a behavior you definitely don’t want in a background job)
-v: for verbose mode. This is not strictly needed, but it’s good for debugging purposes and troubleshooting.
The heredocs
We are going to use a bash feature called “here documents” or heredocs. The main use of this feature is to enable entering multiple lines of input into an interactive prompt. It starts with any string preceded by Automate FTP transfers script
Ok, now you have all the tools you need to automate an FTP job under your belt, let’s start writing the script.
Pretty simple right?
1. You start by specifying that you are going to use bash as your shell language.
2. Assign the hostname to variable HOST.
3. Assign the username to variable USER.
4. Assign the password to variable PASSWORD.
5. Issue the FTP command in non-interactive, verbose mode, instructing the program not to use auto-login. Also, you start a heredocs block to start feeding the FTP program your command block.
6. Enter the user and password.
7. Navigate to the destination directory.
8. Upload all files with extension .html to the destination directory
9. End the FTP session
10. Mark the end of the heredocs
Now save this script as ftpScript.sh for example, and add the appropriate permissions by issuing chmod 700 ftpScript.sh. Put this script in a crontab job and you’re done.
If you are not familiar with Shell Scripting, You can have a look at this blog to get the fundamentals of Shell Scripting clear. You can use Shell Scripting for a variety of things such as generating random numbers and generate random data or passwords.
But do you see any problem in this code?
Yes, you guessed right: the password is stored in clear text! Of course, you can set very strict permissions on the script so that only you have read access. But imagine you want to change the files you want to upload/download from .html to .php, and while doing so, your new colleague is sitting beside you to learn FTP automation. In such a case, your password will be accidentally visible to your colleague and to anyone who happens to have your screen in his/her sight.
A not very secure way to encrypt your password
Ok, let’s agree first that the following method is NOT by any means a cryptographically secure way of string encryption. This is just a way to “obfuscate” your password so that it is not visible in cleartext.
Having said that, let’s get to know the base64 command. Basically, this command converts the string you supply to and from base64 format. So assuming that you have [email protected] as your FTP password, you can encrypt it as follows:
As you can see the base64 representation of your password is UEBzc3cwcmQK. So how can we decrypt it to get back our text?
Now let’s make a slight modification to our script:
The changed part here is line 4. We used the base64 decryption method to get the password string and assign it to the password variable. To make it work, we enclosed the command in “ to instruct bash to execute the command and not treat it as literal text.
This way, if somebody had an accidental look at your file, the base64-encoded password will be much more difficult to memorize than the clear text one.
Conclusion
In this article, we had a quick overview of the FTP command and how to use it in the bash shell instead of using GUI applications. Then we explained how to use command-line switches and heredocs to automate FTP file transfer operations. Finally, we showed a very basic way to encrypt clear text passwords. Although not considered “secure enough” by any security standard, it is much better than letting the password stay in cleartext.
Meanwhile, If you are a beginner and want to gain in-depth knowledge about the subject, try the “Linux Shell Programming for Beginners” course. The course comes with 9.5 hours of video that covers 12 sections such as command lines and tips, customizing your shell, conditions and loops, command-line options, and much more.
Also, Try out the Learn Linux from Scratch online tutorial for FREE! It comes with 4 hours of video that covers 12 sections including an introduction to Linux Systems, installation, hardware, file management and much more.
I hope I saved somebody’s time and effort through this post. Thanks for reading and see you in later posts.
Источник