---
# System prepended metadata

title: 異地備份筆記

---

## 被備份端
### 安裝SSH
![image](https://hackmd.io/_uploads/Syc9jBYrA.png)
![image](https://hackmd.io/_uploads/SymCiHFSA.png)

### 啟用SSH
安装完成后，打开PowerShell并启动OpenSSH服务器：
```powershell=
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
```
### 配置SSH
确保在sshd_config中允许SCP和SFTP：
编辑 C:\ProgramData\ssh\sshd_config 文件，确保以下行未被注释（即去掉前面的#号）：
```powershell=
Subsystem sftp sftp-server.exe
```
### 安裝7-zip

### 建立備份批次檔
```bat=
set TODAY=%DATE:/=%
set NOW=%TIME::=%
set NOW=%NOW:.=%
set NOW=%NOW: =0%
set BDATE=%TODAY:~0,8%%NOW%
set BACKUPDIR=C:\xampp\htdocs\myweb
set TEMPDIR=d:\backup\myweb.%BDATE%
robocopy %BACKUPDIR% %TEMPDIR% /MIR
"C:\Program Files\7-Zip\7z.exe" a -tzip %TEMPDIR%.zip %TEMPDIR%\*
rmdir /S /Q %TEMPDIR%
```

## 備份端
### 撰寫C#程式
```C#=
string host = "遠端主機的IP";
int port = 22;
string username = "Windows帳號";
string password = "Windows密碼";
string remoteDirectory = @"/d:/backup";
string localDirectory = @"d:\backup";
try
{
    // Create a connection info object with password authentication
    var connectionInfo = new ConnectionInfo(host, port, username,
        new PasswordAuthenticationMethod(username, password));

    // Use the SFTP client to list, download, and delete files
    using (var sftp = new SftpClient(connectionInfo))
    {
        sftp.Connect();
        Console.WriteLine("Connected to the server.");

        // List all files in the remote directory
        var files = sftp.ListDirectory(remoteDirectory);
        var backupFiles = new List<SftpFile>();

        // Filter files with the format backup_[yyyymmdd].zip
        foreach (var file in files)
        {
            if (!file.IsDirectory && file.Name.EndsWith(".zip"))
            {
                backupFiles.Add((SftpFile)file);
            }
        }

        Console.WriteLine($"Found {backupFiles.Count} backup files to transfer.");

        // Ensure the local directory exists
        if (!Directory.Exists(localDirectory))
        {
            Directory.CreateDirectory(localDirectory);
            Console.WriteLine($"Created local directory: {localDirectory}");
        }

        // Transfer each backup file and delete it after successful transfer
        foreach (var file in backupFiles)
        {
            string localFilePath = Path.Combine(localDirectory, file.Name);
            Console.WriteLine($"Transferring {file.Name} to {localFilePath}...");

            using (var fileStream = File.OpenWrite(localFilePath))
            {
                sftp.DownloadFile(file.FullName, fileStream);
            }

            Console.WriteLine($"File {file.Name} transferred successfully.");

            // Delete the remote file after successful transfer
            sftp.DeleteFile(file.FullName);
            Console.WriteLine($"File {file.Name} deleted from the server.");
        }

        sftp.Disconnect();
        Console.WriteLine("Disconnected from the server.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
```