Linux tar to ftp

Linux | Upload a .tar.gz file to a FTP-Server with encryption enabled and port changed

First forward I gotta say that I’m a scripting noob and just’ve started to learn Linux. I need your help with the integrated ftp-client on Linux. I want to write a script that automaticly packs a folder (in my case the /home dir on my server) to a .tar.gz file and sends it to my ftp-server at home. Problem here is that I have changed the default ftp-port to another one. The backup script itself is working fine but now I got stuck with using the ftp-client in Linux. Lets say my ftp-port is 12345 and my adress for the ftp is ftp.example.com, so I would use the command like this: scp -P 12345 /backupdir/backup1.tar.gz backupuser@ftp.example.com:/ But somehow nothing happens. Thank your for your help.

1 Answer 1

tar cvz /home | ncftpput -P 12345 -r 5 -F -c -u ftpUsername -p ftpPassword ftpHost $FILE 

should do the trick. ncftpput is in the ncftp package. The line should be self-explanatory; the r switch is the number of attempts to connect (redials), F is for passive mode.

$FILE is the variable with the desired filename. You could also specify the name manually.

You must log in to answer this question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.13.43530

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Как делать резервную копию сразу на FTP

Обычно tgz-архив сначала создают в локальной файловой системе, а потом передают на FTP -сервер, но такая практика требует дополнительного места на диске, которое не всегда доступно в нужном объёме. К счастью, tar умеет писать выходной файл в stdout, а ncftpput считывать из stdin. Воспользуемся этим:

tar -czf - -C /var/www/example.tld/web . | ncftpput -c -m -S .tmp -u ftpuser -p ****** ftp.server.ru /backup/example.tar.gz

Как делать резервную копию сразу в хранилище S3

apt install awscli aws configure aws s3 ls --endpoint-url=https://1cloud.store --debug --no-sign-request printenv | grep AWS echo dfgdfgdf | aws s3 cp - s3://mybucket/stream.txt

Как делать резервную копию сразу в хранилище OpenStack Swift

echo "Some text" | swift --verbose --os-auth-url https://1cloud.store/v2.0/ --os-username 123_user --os-password ****** --os-tenant-name 123 upload --object-name test.tar.gz thisIsAContainer.txt -

Имейте в виду, что обязанность контроля целостности архива лежит на вашем скрипте бекапа — проверяйте код возврата tar. Если он отличен от «0», архив необходимо создать заново.

Читайте также:  Show mysql users linux

Как делать резервную копию сразу на Яндекс.Диск

Никак. Их реализация метода HTTP PUT подразумевает, что на начало передачи тела файла уже известен его полный размер.

Источник

How to make tar save the archive on a remote machine using sftp or ftp?

I would like to backup some of my very important data on a remote machine.
Currently I’m just saving it to my local machine by using this command: tar -cvjf ~/backups/Backup.tar.bz2 ~/importantfiles/* I would prefer not using another command to transger it to the remote machine, meaning I would like to just have this command being upgraded so it can transfer the data to the remote machine. This is designed to be in a script later that is suposed to run on its own, meaning any type of required user input would completly mess it up! Something like

tar -cvjf sftp://user:pwassword@host/Backup.tar.bz2 ~/importantfiles/* tar -cvjf ftp://user:pwassword@host/Backup.tar.bz2 ~/importantfiles/* 

I do not have ssh access to the machine. It’s just a backup server I rent. So yes it has to be ftp or sftp.

I know. But it is set up in a way that every ssh connection gets closed immediatley. SFTP works though. I know it is a wierd setup but that’s the way it is.

SFTP is available when SSH is not if they are using sftp internal server and your shell is set to /sbin/nologin.

3 Answers 3

tar czf - . | ssh remote "( cd /somewhere ; cat > file.tar.gz )" 
outfile=/tmp/test.tar.gz tar cvf $outfile . && echo "put $outfile" | sftp remote:/tmp/ Connecting to remote. Changing to: /tmp/ sftp> put /tmp/test.tar.gz Uploading /tmp/test.tar.gz to /tmp/test.tar.gz /tmp/test.tar.gz 
outfile=/tmp/test.tar.gz sftp -b /dev/stdin remote >/dev/null 2>&1  

So how exactly would I use this? I mean how can I set which files should be in the tar ball. And where would I put the password? And how do I set it up so that I do not have to accept the hosts fingerprint?

Please learn more about ssh, man ssh, man ssh-agent, man ssh_config answer all your doubts. Which files you define locally with tar arguments, then it is piped via ssh to remote host and output is redirected to file.

For ftp, see man lftp. If you need to have more complicated scenarios, use 'sftp -b' and have a file with commands or use 'here documents' (

Tar doesn't speak ftp or sftp. That's not its job. You cannot do this with tar alone. Using appropriate tools for each job and combining them with the shell is the normal way of doing things on unix systems.

The most obvious solution is to create the archive locally, then copy it to the remote machine.

If you don't want to create the archive locally because you don't have enough room, you can create a named pipe, make tar write to this pipe, and find an (s)ftp client that can read from pipes. Unfortunately, sftp refuses to put a pipe. Some FTP clients work, for example lftp:

mkfifo f tar -cvjf f ~/importantfiles/* & sleep 2 lftp -f -  

Alternatively, there is a way to make your tar command save to the remote server directly, but you need some prior setup. Mount the remote server over SSHFS or curlftpfs.

mkdir -p ~/net/host sshfs host: ~/net/host tar -cvjf ~/net/host/Backup.tar.bz2 ~/importantfiles/* fusermount -u ~/net/host 

Источник

Простой способ резервного копирования 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 quote USER $FTPU
quote PASS $FTPP
cd $FTPD
mput $DUMPFILE
quit
END_SCRIPT

Результатом работы данного скрипта будет созданный файл в директории /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)

### name Mysql ###
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do

### ###
mkdir $BACKUP/$NOW/$db
FILE=$BACKUP/$NOW/$db/$db.sql.gz
echo $i; $MYSQLDUMP --add-drop-table --allow-keywords -q -c -u $MUSER -h $MHOST -p$MPASS $db $i | $GZIP -9 > $FILE
done

$TAR -zcvf $ARCHIVE $ARCHIVED

### ftp ###
cd $BACKUP
DUMPFILE=mysql-$NOW.tar.gz
$FTP -n $FTPS quote USER $FTPU
quote PASS $FTPP
cd $FTPD
mput $DUMPFILE
quit
END_SCRIPT

Результат работы скрипта — файл в директории /root/backup/server вида mysql-ГГГГММДД.tar.gz содержащий в себе tar-архивы c дампами всех баз данных и его выгрузка на FTP-сервер.

Автоматизация

Сохраняем данные скрипты в директорию /etc/cron.daily, предварительно проверив в файле /etc/crontab, что именно из этой директории запускаются скрипты каждый день.

Заключение

Конечно, в каждом конкретном случае скрипты могут меняться и приведенные примеры лишь один из многочисленных вариантов организации резервного копирования.
Надеемся, что после прочтения этой статьи вы задумаетесь над собственным решением бэкапа, если по каким-то причинам еще не организовали этот важнейший процесс.

Источник

automate transfer of tar files over FTP

Every day I have a script making .tar files of aparticualr directory. Once every day, I would like to transfere the new tar file made that day to a remote server over FTP. I would like to make this process automated. What would be the best way of going about this? Can a bash script be written for this and scheduled it with cron? Is there a tool/app/software that can do this? Thanks very much!

1 Answer 1

Usually these kind of things are best done from the command line

put the example below in a new file under /etc/cron.daily/ and chmod +x filename , for it to be executable so that it can be automatically run on on a daily basis.

lftp -e 'put /home/path/yourfile.tar; bye' -u user,password ftp.theserver.com 

the -e command is to allow you to enter a series of commands. The commands to be run are declared within the ' ' signs, in this example two commands are run in succession each command is separated by the ; sign. The first command uploads a file, the second command disconnects from the ftp server once the upload is complete.

If one would want to add an additional command, for example to browse to a another folder simply add the change directory command , "cd folder1/folder2;" in our example the new command would look like this:

lftp -e 'cd folder1/folder2; put /home/path/yourfile.tar; bye' -u user,password ftp.theserver.com 

lftp can take script files as input allowing you to create separate files with commands for it to execute when using the -f option if you feel like having the commands run my lftp separated into a specific file.

if you want to see what commands are available this can be help for generic ftp commands. Commands specific for lftp can be found in the lftp man page

Источник

Оцените статью
Adblock
detector