同步文件到远程服务器

2023-04-08 15:53:20 浏览数 (1)

代码语言:php复制
/**
 * @param string $source 当前文件路径 如:/admin/images/2023/03/06/admin.png
 * @param string $target 远程文件夹路径 如:/home/web/public
 * @param string $host 远程服务器主机
 * @param string $port 远程服务器端口号
 * @param string $username 远程服务器用户名
 * @param string $password 远程服务器密码
 * @return bool|string
 */
protected function ssh2ScpSend($source, $target, $host = '127.0.0.1', $port = '22', $username = 'username', $password = 'password')
{
    try {
        $source = ltrim($source, DIRECTORY_SEPARATOR);

        $target = rtrim($target, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

        //建立ssh2连接
        $connection = ssh2_connect($host, $port);

        //验证ssh2密码
        ssh2_auth_password($connection, $username, $password);

        $sftp = ssh2_sftp($connection);

        ssh2_sftp_mkdir($sftp, $target . dirname($source), 0777);

        $result = ssh2_scp_send($connection, realpath($source), $target . $source, 0777);
    } catch (Exception $e) {
        $result = $e->getMessage();
    }

    return $result;
}

0 人点赞