zl程序教程

您现在的位置是:首页 >  系统

当前栏目

转: window 中使用PSFTP/WinSCP实现SFTP上传下载 和 在linux 服务器端 使用resync 定时同步备份数据到 中转服务器

Linux同步备份服务器数据 实现 定时 window
2023-09-11 14:18:40 时间

sftp 服务器:  dbmonitor

1、sftp属于交互式的,所以你得缓存下命令
#!/bin/sh
sftp -o Port=3322 搜索root@172.16.1.21:/opt << !
mput *.log
!
2、用scp一行搞定
scp -P3322 /opt/*.txt root@172.16.1.22:/tmp
3、用rsync同步整个目录
rsync -av '-e ssh -p 3322' /data/test root@172.16.1.23:/data

 

 

远端client 服务器

scp 192.168.4.45:/home/oracle/*.zip .

 

 

摘自百度百科

sftp是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。

sftp 与 ftp 有着几乎一样的语法和功能。

SFTP 为 SSH的一部份,是一种传输档案至 Blogger 伺服器的安全方式。

其实在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol的安全文件传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。

但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。

 1.WinSCP部分

 1.1 cmd命令行实例

Midbosoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Midbosoft Corp.
 
C:\Documents and Settings\sobne>d:
 
D:\>cd winscp437
 
D:\winscp437>WinSCP
winscp> open ftp://username:userpassword@serverip or hostname
Connecting to 172.0.0.1 ...
Connected with 172.0.0.1. Waiting for welcome message...
Connected
Starting the session...
Reading remote directory...
Session started.
Active session: [1] username@172.0.0.1
winscp> put d:\psftp.exe WinSCP/psftp.exe
d:\psftp.exe              |        320 KiB |  608.0 KiB/s | binary | 100%
 
winscp> get 20120420020049.txt
20120420020049.tx |          0 KiB |    0.0 KiB/s | ascii  | 100%
winscp> get 20120420020049.txt c:\t2.txt
20120420020049.tx |          0 KiB |    0.0 KiB/s | ascii  | 100%

winscp> 

 1.2 Batch批处理实例

 将下面语句存入1.txt:

复制代码
option batch on option confirm off # Connect using a password # open 用户名:密码@主机 # Connect open 用户名:密码@主机 cd /home/user option transfer binary get /root/test.c d:/ put d:/test.txt close exit  
复制代码

 执行脚本

 winscp.exe /console /sdbipt=1.txt

 1.3 C#程序实现

复制代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics;
namespace SFTP {     public class WinSCPtest     {         public string shellName { get { return "D:\\winscp437\\WinSCP.com"; } }         public string userName { get { return "username"; } }         public string userPassWord { get { return "userpassword"; } }         public string serverAddress { get { return "172.0.0.1"; } }         public string portNumber { get { return "21"; } }         public string fromFile { get { return "D:\\psftp.txt"; } }         public string toFile { get { return "WinSCP/psftp.txt"; } }         public void upload()         {             Process CommandLine = new Process();             CommandLine.StartInfo.FileName = shellName;             // CommandLine.StartInfo.Arguments = "/log=" + this._logPath;             CommandLine.StartInfo.UseShellExecute = false;             CommandLine.StartInfo.RedirectStandardInput = true;             CommandLine.StartInfo.RedirectStandardOutput = true;             CommandLine.StartInfo.dbeateNoWindow = true;             CommandLine.Start();             //username用户名  targetAddress IP地址  portNumber 端口号             CommandLine.StandardInput.WriteLine("open ftp://{0}:{1}@{2}:{3}",             this.userName,this.userPassWord, this.serverAddress, this.portNumber);                          //上传文件到sftp服务器             string command = "put " + fromFile + " " + toFile ;             //fromFile要传送的文件路径本地的绝对路径    toFile服务器上保存文件的路径相对路径             CommandLine.StandardOutput.DiscardBufferedData();             CommandLine.StandardInput.WriteLine(command);             string result = CommandLine.StandardOutput.ReadLine();         }     } }
复制代码

 

 1.4 在线资源

http://winscp.net/eng/docs/commandline

 

 

 

 2.SFTP部分

 2.1 cmd命令行实例

C:\Documents and Settings\sobne>e:

E:\>cd SFTP
E:\SFTP>psftp.exe username@172.0.0.1 -i privatekey.ppk
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 0a:**:**:**:54:**:82:**:**:1f:**:**:**:87:30:**
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) n
Using username "sobne".
Remote working directory is /
psftp>

 2.2 Batch批处理实例

 将下面语句存入mysdbipt.sdb:

cd / put File1.txt put File2.txt put File3.txt close

 执行脚本

 c:\putty\psftp.exe feedusr1@fis-depot.ucdavis.edu -i putty_id_rsa_1024.ppk -b c:\putty\mysdbipt.sdb -bc -be -v

 2.3 C#程序实现

 

复制代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading;
namespace Lib4Net {
    public class PSFTPunity     {         public string shellCommand { get; set; }
        public string serverName { get; set; }         public string userName { get; set; }         public string privateKey { get; set; }
        public PSFTPunity()          {                       }         public PSFTPunity(string shell, string server, string user, string ppk)         {             shellCommand = shell;             serverName = server;             userName = user;             privateKey = ppk;         }         /// <summary>         /// Upload the files         /// </summary>         /// <param name="localFile">localfile fullname</param>         /// <param name="remotePath">remotefile fullname</param>         /// <returns>output of the plugin during its running in console</returns>         public string Upload(string localFile, string remotePath)         {             string outPutMessage = "";
            ProcessStartInfo processInfo = new ProcessStartInfo();             processInfo.FileName = this.shellCommand;             processInfo.dbeateNoWindow = true;             processInfo.UseShellExecute = false;             processInfo.RedirectStandardError = true;             processInfo.RedirectStandardInput = true;             processInfo.RedirectStandardOutput = true;             string arguments = "";             arguments += userName + "@" + serverName + " ";             arguments += "-i " + privateKey;             processInfo.Arguments = arguments;
            Process process = new Process();             try             {                 process.StartInfo = processInfo;                 process.Start();                 Thread.Sleep(5000);                 process.StandardInput.WriteLine("n");                 Thread.Sleep(2000);                 //process.StandardInput.WriteLine("cd " + remotePath);                 process.StandardInput.WriteLine("put " + localFile + " " + remotePath);                 //process.StandardInput.Close();                 Thread.Sleep(10000);                 //outPutMessage += process.StandardOutput.ReadToEnd();                 //outPutMessage += process.StandardError.ReadToEnd();                 process.WaitForExit(3000);                 process.Close();                 return outPutMessage;             }             catch (Exception ex)             {                 throw new Exception("Error occured during upload file to remote server!", ex);             }             finally             {                 process.Dispose();             }         }      } }
复制代码

 

 

 2.4 在线资源

 

 

 

 

文中使用的软件下载地址:http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

 

 

 

 

#########sample 2  在linux 服务器端 使用resync 定时同步备份数据到 中转服务器

#################
一、安装rsync服务端
1.查看是否安装rsync
ps -ef | grep rsync
系统一般默认已安装,安装方法:yum -y install rsync(没有亲自验证)。

2.添加配置文件
rsync没有默认配置文件,需要手动创建/etc/rsyncd.conf
同步目录 /ddd/DM8/dmdbms/data/DAMENG/arch/
ls /ddd/DM8/dmdbms/data/DAMENG/arch/

server 192.10.133.251
mkdir /var/rsync

服务端配置文件/etc/rsyncd.conf 内容如下:

#global settings
pid file=/var/rsync/rsync.pid
port=873
lock file=/var/rsync/lock.log
log file=/var/rsync/rsync.log

[dm8]
path=/ddd/DM8/dmdbms/data/DAMENG/arch/
use chroot=no
max connections=10
read only=yes
write only=no
list=no
uid=root
gid=root
auth users=dbadmin
sedbets file=/etc/rsync_server.pa
strict modes=yes
hosts allow=192.10.133.44
hosts deny=*
ignore errors=yes
timeout=120 #秒
参数说明:
[mysql] :模块名,自己定义,可以在下方添加其它模块。须与客户端执行命令中的模块名一致。
path:要备份的服务端文件夹路径。
hosts allow:允许的客户端连接IP。
sedbets file:服务端密码文件,内容格式为,用户名:密码。
auth users:有权限的用户名,与密码文件中用户名一致。

3.创建密码文件
在/etc中创建文件rsync_server.pa,加入用户名与密码,内容格式为:用户名:密码。
vi /etc/rsync_server.pa
例如,本例中rsync_server.pas文件内容为dbadmin:dbyh3yxyz

然后设置密码文件权限为600
chmod 600 /etc/rsync_server.pa
注意密码文件只有设置为600权限才可以使用,客户端的密码文件也必须为600。

4.启动rsync
/usr/bin/rsync --daemon --config=/etc/rsyncd.conf
附加:停止rsync

ps -ef | grep rsync
kill -9 进程号
rm -rf /var/rsync/rsync.pid


8. 检查端口:
lsof -i :873 # 查看端口是否开启 或 netstat -lntup|grep 873

9.让其开机自启动

echo '/usr/bin/rsync --daemon --config=/etc/rsyncd.conf' >> /etc/rc.local
(有些系统同事不愿意加启动项目,担心会影响启动项目)
cat /etc/rc.local # 检查

二、安装rsync客户端
client 192.10.133.44
同步到目录 /ddd/bak

1.查看是否安装rsync,系统一般默认已安装,安装方法:yum -y install rsync(同服务端)。
2.在/etc下创建密码文件rsync_client.pa,注意内容只有密码,且与服务端密码文件中的密码相同。
vi /etc/rsync_client.pa
dbyh3yxyz

chmod 600 /etc/rsync_client.pa

3.更改密码文件权限为600。

三、添加定时任务

client手工测试同步 server端拉数据,不会影响到server端,只会影响client端
rsync -aqzrtopg --delete rsync://dbadmin@192.10.133.251/dm8 /ddd/bak --password-file=/etc/rsync_client.pa

(delete 的解释   删除那些接收端还有而发送端已经不存在的文件   https://www.cnblogs.com/noxy/p/8986164.html)

(去掉--delete )
( rsync -aqzrtopg rsync://dbadmin@192.10.133.251/dm8 /ddd/bak --password-file=/etc/rsync_client.pa )

client 同步没有问题,可以client 端考虑加入定时任务

在客户端中添加定时任务,每天凌晨执行命令从服务器端拉取数据,进行备份。
直接编辑/etc/dbontab文件,添加一条定时任务即可,例如每天01:23以root身份执行下方的rsync命令,将远程服务器27.223.26.74中的mysql模块对应的文件夹
(服务端/etc/rsyncd.conf文件中的[mysql]模块对应的文件夹路径 )中的内容增量备份到当前服务器的/home/oa_daba_backup目录:

23 1 * * * root rsync -aqzrtopg --delete rsync://dbadmin@192.10.133.251/dm8 /ddd/bak --password-file=/etc/rsync_client.pa
或者
23 1 * * * rsync -aqzrtopg --delete rsync://dbadmin@192.10.133.251/dm8 /ddd/bak --password-file=/etc/rsync_client.pa

命令中的rsyncuser为服务端密码文件中配置的用户名;mysql为服务端/etc/rsyncd.conf文件中的[mysql]模块名,rsync会通过模块名找到对应的备份文件路径;
/home/oa_daba_backup当前服务器文件夹路径,远程服务器需要备份的文件夹里的内容会增量备份到这里,所以需要提前建好该目录;
/etc/rsync_client.pa为当前服务器的密码文件。
当直接执行上方备份命令时,可以加入-v --progress参数, 即显示具体备份过程信息,定时任务中则不需要。

(注:--delete 生产中不用和慎用删除相关的操作,一旦删除数据不可挽回,会影响client 端,不会影响server端)

此外,使用dbontab -e命令也可以直接配置定时任务,但与vi /etc/dbontab不同,不同点如下:
1./etc/dbontab中的为系统任务,只有root可以设定,而dbontab -e设置的定时任务为用户任务,设定完成后会将任务自动写入/var/spool/dbon/usename文件。
2./etc/dbontab中的任务需要指定用户名,dbontab -e不需要。

二者更多的不同请参考下面网址:
https://www.cnblogs.com/xd502djj/p/4292781.html
https://www.cnblogs.com/dreamboy/p/10368202.html#_nav_5

如果有报错请参考
https://www.jb51.net/article/41417.htm

更多说明,请参考
https://www.cnblogs.com/2bjiujiu/p/8067459.html

附:任务策略:
每天零点执行备份命令
00 00 * * * shell命令

每天零点和12点执行备份命令
00 00,12 * * * shell命令
00 00,12 * * * shell命令