public function stat($path) { $path = $this->path($path); $stat = @ssh2_sftp_stat($this->getSftpResource(), $path); // Missing if (!$stat) { return array('name' => basename($path), 'path' => $path, 'exists' => false); } // Get extra $type = filetype('ssh2.sftp://' . $this->getSftpResource() . $path); $rights = substr(sprintf('%o', fileperms('ssh2.sftp://' . $this->getSftpResource() . $path)), -4); // Process stat $info = array('name' => basename($path), 'path' => $path, 'exists' => true, 'type' => $type, 'uid' => $stat['uid'], 'gid' => $stat['gid'], 'size' => $stat['size'], 'atime' => isset($stat['atime']) ? $stat['atime'] : null, 'mtime' => isset($stat['mtime']) ? $stat['mtime'] : null, 'ctime' => isset($stat['ctime']) ? $stat['ctime'] : null, 'rights' => $rights, 'readable' => $this->checkPerms(0x4, $rights, $stat['uid'], $stat['gid']), 'writable' => $this->checkPerms(0x2, $rights, $stat['uid'], $stat['gid']), 'executable' => $this->checkPerms(0x1, $rights, $stat['uid'], $stat['gid'])); return $info; }
/** * Remote stat. * * @param string $path * * @return array */ public function stat($path) { ssh2_sftp_stat($this->resource, $path); }
/** * Stats a file on the remote filesystem * * @param string $path The path of the file * * @return array */ public function stat($path) { return ssh2_sftp_stat($this->getResource(), $path); }
/** * Attempts to open a connection to the SSH2 server. * * @throws Horde_Vfs_Exception */ protected function _connect() { if ($this->_stream !== false) { return; } if (!extension_loaded('ssh2')) { throw new Horde_Vfs_Exception('The SSH2 PECL extension is not available.'); } if (!is_array($this->_params)) { throw new Horde_Vfs_Exception('No configuration information specified for SSH2 VFS.'); } $required = array('hostspec', 'username', 'password'); foreach ($required as $val) { if (!isset($this->_params[$val])) { throw new Horde_Vfs_Exception(sprintf('Required "%s" not specified in VFS configuration.', $val)); } } /* Connect to the ssh2 server using the supplied parameters. */ if (empty($this->_params['port'])) { $this->_stream = @ssh2_connect($this->_params['hostspec']); } else { $this->_stream = @ssh2_connect($this->_params['hostspec'], $this->_params['port']); } if (!$this->_stream) { $this->_stream = false; throw new Horde_Vfs_Exception('Connection to SSH2 server failed.'); } if (!@ssh2_auth_password($this->_stream, $this->_params['username'], $this->_params['password'])) { $this->_stream = false; throw new Horde_Vfs_Exception('Authentication to SSH2 server failed.'); } /* Create sftp resource. */ $this->_sftp = @ssh2_sftp($this->_stream); if (!empty($this->_params['vfsroot']) && !@ssh2_sftp_stat($this->_sftp, $this->_params['vfsroot']) && !@ssh2_sftp_mkdir($this->_sftp, $this->_params['vfsroot'])) { throw new Horde_Vfs_Exception(sprintf('Unable to create VFS root directory "%s".', $this->_params['vfsroot'])); } }
/** * @{inheritDoc} */ public function stat($path = '') { return $this->doRun(__METHOD__, func_get_args(), ssh2_sftp_stat($this->sftp, $path)); }
/** * Gets the files list * * @param string $remotePath Remote directory path * @return array List of files * @throws Exception Invalid connection resource! due to use of validateSshResource. * @throws Exception Folder does not exist or no permissions to read! * @throws Exception Unable to open remote directory! */ public function getFileList($remotePath) { $this->validateSshResource(); if (ssh2_sftp_stat($this->getSftpResource(), $remotePath) === false) { throw new Exception("Folder does not exist or no permissions to read!"); } $sftp = $this->getSftpResource(); $handle = opendir("ssh2.sftp://{$sftp}/{$remotePath}"); if ($handle === false) { throw new Exception("Unable to open remote directory!"); } $files = array(); while (false != ($entry = readdir($handle))) { $files[] = $entry; } return $files; }
/** * Renames a remote file. * * @param string $old_name * @param string $new_name * * @return boolean Returns TRUE on success or FALSE on error * * @throws \BackBee\Util\Transport\Exception\TransportException Occures if SSH connection is invalid */ public function rename($old_name, $new_name) { if (null === $this->_sftp_resource) { throw new TransportException(sprintf('None SSH connection available.')); } $old_name = $this->_getAbsoluteRemotePath($old_name); $new_name = $this->_getAbsoluteRemotePath($new_name); if (false === @ssh2_sftp_stat($this->_sftp_resource, $old_name)) { return $this->_trigger_error(sprintf('Could not open remote file: %s.', $old_name)); } if (false !== @ssh2_sftp_stat($this->_sftp_resource, $new_name)) { return $this->_trigger_error(sprintf('Remote file already exists: %s.', $new_name)); } if (false === @ssh2_sftp_rename($this->_sftp_resource, $old_name, $new_name)) { return $this->_trigger_error(sprintf('Unable to rename %s to %s', $old_name, $new_name)); } return true; }
/** * Creates a nested directory structure on the remote SFTP server * * @param string $dir * @param resource $sftphandle * * @return boolean */ private function _makeDirectory($dir, &$sftphandle) { $alldirs = explode('/', $dir); $previousDir = ''; foreach ($alldirs as $curdir) { $check = $previousDir . '/' . $curdir; if (!@ssh2_sftp_stat($sftphandle, $check)) { if (ssh2_sftp_mkdir($sftphandle, $check, 0755, true) === false) { $this->setWarning('Could not create SFTP directory ' . $check); return false; } } $previousDir = $check; } return true; }
/** * Checks if the given directory exists * * @param string $path The full path of the remote directory to check * * @return boolean True if the directory exists */ public function isDir($path) { return @ssh2_sftp_stat($this->sftpHandle, $path); }
/** * newDirectory - Create new directory using the SFTP subsystem from an already connected SSH2 server. * * @param string $local * @param string $remote * @param int $mod * * @throws exception */ public function newDirectory($remote) { $statinfo = @ssh2_sftp_stat($this->sftp, $remote); if (empty($statinfo['size'])) { if (!ssh2_sftp_mkdir($this->sftp, $remote)) { throw new Exception("Could not create directory {$remote}"); } } }
function remote_file_size($file_path) { $stat = @ssh2_sftp_stat($this->sftp_connection, $file_path); return @$stat["size"]; }
public function statinfo($file) { $sftp = ssh2_sftp($this->conn); return ssh2_sftp_stat($sftp, $file); }
public function __call($name, $arguments) { //无需转换的函数 $list = array('pathinfo', 'basename', 'mb_basename', 'dirname', 'fwrite', 'fclose', 'feof', 'fflush', 'fgetc', 'fgetcsv', 'fgets', 'fgetss', 'flock', 'fpassthru', 'fputcsv', 'fputs', 'fwirte', 'fread', 'fscanf', 'fseek', 'fstat', 'ftell', 'ftruncate', 'rewind'); if (in_array($name, $list)) { return call_user_func_array($name, $arguments); } //没有开启协议 if (!ini_get('allow_url_fopen')) { $list = array('filesize' => 'size', 'fileowner' => 'uid', 'filegroup' => 'gid', 'fileperms' => 'mode', 'fileatime' => 'atime', 'filemtime' => 'mtime', 'file_exists' => 'file_exists', 'is_dir' => 'is_dir', 'is_file' => 'is_file', 'is_link' => 'is_link', 'is_executable' => 'is_executable', 'is_readable' => 'is_readable', 'is_writable' => 'is_writable', 'is_writeable' => 'is_writable', 'filetype' => 'filetype'); if (!array_key_exists($name, $list)) { throw new Kohana_Exception('"allow_url_fopen" is off!'); } $data = @ssh2_sftp_stat($arguments[0]); $data['file_exists'] = $data !== FALSE; $data['is_dir'] = ($data['mode'] & 0x4000) == 0x4000; $data['is_file'] = ($data['mode'] & 0x8000) == 0x8000; $data['is_link'] = ($data['mode'] & 0xa000) == 0xa000; $data['is_executable'] = ($data['mode'] & 0x40) == 0x40; $data['is_readable'] = ($data['mode'] & 0x100) == 0x100; $data['is_writable'] = ($data['mode'] & 0x80) == 0x80; if (($perms & 0xc000) == 0xc000) { // Socket $data['filetype'] = 'socket'; } elseif (($perms & 0xa000) == 0xa000) { // Symbolic Link $data['filetype'] = 'link'; } elseif (($perms & 0x8000) == 0x8000) { // Regular $data['filetype'] = 'file'; } elseif (($perms & 0x6000) == 0x6000) { // Block special $data['filetype'] = 'block'; } elseif (($perms & 0x4000) == 0x4000) { // Directory $data['filetype'] = 'dir'; } elseif (($perms & 0x2000) == 0x2000) { // Character special $data['filetype'] = 'char'; } elseif (($perms & 0x1000) == 0x1000) { // FIFO pipe $data['filetype'] = 'fifo'; } else { // Unknown $data['filetype'] = 'unknown'; } return $data[$list[$name]]; } //需要转换路径的的函数 $list = array('file_exists', 'is_dir', 'is_executable', 'is_file', 'is_link', 'is_readable', 'is_writable', 'is_writeable', 'lchgrp', 'lchown', 'linkinfo', 'tempnam', 'file_get_contents', 'file_put_contents', 'file', 'readfile', 'parse_ini_file', 'fopen', 'disk_free_space', 'diskfreespace', 'disk_total_space', 'chown', 'chgrp', 'fileatime', 'filectime', 'filegroup', 'fileinode', 'filemtime', 'fileowner', 'fileperms', 'filesize', 'filetype', 'touch'); if (!in_array($name, $list)) { throw new Kohana_Exception('Call to undefined function: :class:::function()', array(':class' => __CLASS__, ':function' => $name)); } //将路径变为SFTP路径 $arguments[0] = $this->format_sftp_path($arguments[0]); return call_user_func_array($name, $arguments); }
protected function doFileExists($remote_file) { $sftp = $this->getSftpConnection(); $stats = @ssh2_sftp_stat($sftp, $remote_file); return $stats !== false; }
public function stat($remote) { $sftp = @ssh2_sftp($this->conn_); return ssh2_sftp_stat($sftp, $remote); }
function stat($filename) { $filename = $this->getLocalPath($filename); return ssh2_sftp_stat($this->sftp, $filename); }
/** * Stats a file on the remote filesystem * * @param string $path The path of the file * * @return array */ public function stat($path) { // This function creates a undocumented warning on missing files. return @ssh2_sftp_stat($this->getResource(), $path); }
$file = fopen($sFilePath, 'a'); foreach ($arrData as $row) { fputcsv($file, $row, '|'); } fclose($file); /*--------------------------------------------------------------------------------------------------*\ grab the contents of our flat file, replace our bogus characters, and then get outta there \*--------------------------------------------------------------------------------------------------*/ $contents = file_get_contents($sFilePath); $contents = str_replace('#@ @#', '', $contents); file_put_contents($sFilePath, $contents); // upload the source file to the destination if (!@ssh2_scp_send($ssh2_connect, $sFilePath, $dFilePath)) { throw new Exception('Sending file to remote server failed...', 0); } if (!@ssh2_sftp_stat($ssh2_sftp, $dFilePath)) { throw new Exception('Could not find file on remote server after uploading...', 0); } unlink($sFilePath); // response output echo json_encode(array('status' => 1, 'message' => count($arrData) . ' vetted Service Partners batched to remote server...')); while ($objSPs->have_posts()) { $objSPs->the_post(); update_post_meta($objSPs->post->ID, 'sp_batched', '1'); } // close the ssh2 connection if (!@ssh2_exec($ssh2_connect, 'exit')) { throw new Exception('Closing session with remote server failed...', 0); } } catch (Exception $e) { error_log('Exception: ' . $e->getMessage());
if (empty($test['password'])) { $test['password'] = $log['password']; } $ssh = @ssh2_connect($test['host'], $test['port'] ? $test['port'] : 22); $finger = @ssh2_fingerprint($ssh); // in order for this to work PasswordAuthentication must be set to 'yes' in // the remote server's sshd_config file. I think a lot of distros might disable it. $res = @ssh2_auth_password($ssh, $test['username'], $test['password']); $result = 'failure'; if (!$res) { $msg = $cms->trans("Unable to connect to ssh://%s@%s" . "<br/>\n", $test['username'], $test['host']); $msg .= !$ssh ? $cms->trans("Verify the host and port are correct") : $cms->trans("Authentication Failed! Note: the remote server must have PasswordAuthentication set to 'yes' in the sshd_config file."); $msg .= "<br/>" . $cms->trans("Note: This test mechanism does not support public key authentication."); } else { $sftp = ssh2_sftp($ssh); $stat = @ssh2_sftp_stat($sftp, $test['path']); if (!$stat) { $msg = $cms->trans("Connected to SFTP server, however the path entered does not exist"); } else { $result = 'success'; $msg = $cms->trans("Successfully connected to the SSH server and verified the path exists!"); $msg .= "<br/>" . $cms->trans("Note: If a new password was entered you will have to re-enter it and save the log source now."); } } } } elseif ($test['type'] == 'stream') { // We can't test streams $msg = $cms->trans("Testing 'stream' sources is not possible."); } $message = $cms->message($result, array('message_title' => $cms->trans("Testing Results"), 'message' => $msg)); // don't let the form be submitted
/** * Change directory * * The second parameter lets us momentarily turn off debugging so that * this function can be used to test for the existence of a folder * without throwing an error. There's no FTP equivalent to is_dir() * so we do it by trying to change to a particular directory. * Internally, this parameter is only used by the "mirror" function below. * * @access public * @param string * @param bool * @return bool */ public function changedir($path = '', $supress_debug = FALSE) { if ($path == '' or !$this->_is_conn()) { return FALSE; } $result = @ssh2_sftp_stat($this->sftp, $path); if ($result === FALSE) { if ($this->debug == TRUE && $supress_debug == FALSE) { $this->_error('sftp_unable_to_changedir'); /// change this error } return FALSE; } return TRUE; }
private function _makeDirectory($dir) { $alldirs = explode('/', $dir); $previousDir = substr($this->_initdir, -1) == '/' ? substr($this->_initdir, 0, strlen($this->_initdir) - 1) : $this->_initdir; $previousDir = substr($previousDir, 0, 1) == '/' ? $previousDir : '/' . $previousDir; foreach ($alldirs as $curdir) { $check = $previousDir . '/' . $curdir; if (!@ssh2_sftp_stat($this->_sftphandle, $check)) { if (ssh2_sftp_mkdir($this->_sftphandle, $check, 0755, true) === false) { $this->setError('Could not create directory ' . $check); return false; } } $previousDir = $check; } return true; }
public function checkSize() { //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "----------------STREAM {$this->id} is INACTIVE.... CHECKING SIZE...."; } //--------------------------------------------------------------------------------------------------------------- if ($statinfo = @ssh2_sftp_stat($this->connection_data->sftp_handle, $this->remote_file)) { //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "------GOT SOME....{$statinfo['size']}>={$this->chunk_size}"; } //--------------------------------------------------------------------------------------------------------------- if ($statinfo['size'] >= $this->chunk_size) { //REALLY F****D UP .... //PHP version 5.3 ... - size is always exact ... //ALL PHP VERSIONS ABOVE 5.3......chunks are padded with random junk ... up to 64kb long...it seams that dudes read beyond specified size ..and f*****g up the local stream pointer.... //last stream will fail on all 5.4+ versions ...if only size is specified....(no offset) //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "------FILE SIZE IS OK..........."; } //--------------------------------------------------------------------------------------------------------------- //Yo ... got the size ....and its OK... $this->active = 0; //disable this stream ... $this->TerminateStreams(); //and terminate all handlers... //but check if we have to truncate it later... $this->oversized = $statinfo['size'] - $this->chunk_size; return 0; //done ... } else { //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "------FAILED ...WRONG SIZE..(Needed {$this->chunk_size}.... GOT {$statinfo['size']}...."; } //--------------------------------------------------------------------------------------------------------------- //nop....we've got the size...and its smaller...PHP dropped the ball . //Whole transfer has failed $this->parent->transfer_status = PHP_SSH2MST_TRANSFER_STATUS_FAILED; $this->active = 0; $this->failed = 1; $this->TerminateStreams(); return 0; //done ... } } else { //cannot get anything yet....just count iterations... $this->size_check_iterations--; if (!$this->size_check_iterations) { //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "------NO MORE ITERATIONS..........."; } //--------------------------------------------------------------------------------------------------------------- //Done ... no size ..no nothing... //Whole transfer has failed $this->parent->transfer_status = PHP_SSH2MST_TRANSFER_STATUS_FAILED; $this->active = 0; $this->failed = 1; $this->TerminateStreams(); return 0; //done ... } else { //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "------NO INFO YET..........."; } //--------------------------------------------------------------------------------------------------------------- } } return 1; //indicate that we still active ....no size available yet... //--------------------------------------------------------------------------------------------------------------- if (PHP_SSH2MST_DEBUG) { echo "\n"; } //--------------------------------------------------------------------------------------------------------------- }
/** * Changes to the requested directory in the remote server. You give only the * path relative to the initial directory and it does all the rest by itself, * including doing nothing if the remote directory is the one we want. * * @param string $dir The (realtive) remote directory * * @return bool True if successful, false otherwise. */ private function sftp_chdir($dir) { // Strip absolute filesystem path to website's root $removePath = AKFactory::get('kickstart.setup.destdir', ''); if (!empty($removePath)) { // UNIXize the paths $removePath = str_replace('\\', '/', $removePath); $dir = str_replace('\\', '/', $dir); // Make sure they both end in a slash $removePath = rtrim($removePath, '/\\') . '/'; $dir = rtrim($dir, '/\\') . '/'; // Process the path removal $left = substr($dir, 0, strlen($removePath)); if ($left == $removePath) { $dir = substr($dir, strlen($removePath)); } } if (empty($dir)) { // Because the substr() above may return FALSE. $dir = ''; } // Calculate "real" (absolute) SFTP path $realdir = substr($this->dir, -1) == '/' ? substr($this->dir, 0, strlen($this->dir) - 1) : $this->dir; $realdir .= '/' . $dir; $realdir = substr($realdir, 0, 1) == '/' ? $realdir : '/' . $realdir; if ($this->_currentdir == $realdir) { // Already there, do nothing return true; } $result = @ssh2_sftp_stat($this->handle, $realdir); if ($result === false) { return false; } else { // Update the private "current remote directory" variable $this->_currentdir = $realdir; return true; } }
protected function doModificationTime($remote_file) { $remote_file = ltrim($remote_file, '/'); $statinfo = ssh2_sftp_stat($this->getSftpConnection(), $remote_file); $modificationTime = isset($statinfo['mtime']) ? $statinfo['mtime'] : null; return $modificationTime; }
/** * Update FTP configuration. */ function procAdminUpdateFTPInfo() { $vars = Context::getRequestVars(); $vars->ftp_path = str_replace('\\', '/', rtrim(trim($vars->ftp_path), '/\\')) . '/'; if (strlen($vars->ftp_pass) === 0) { $vars->ftp_pass = Rhymix\Framework\Config::get('ftp.pass'); } // Test FTP connection. if ($vars->ftp_sftp !== 'Y') { if (!($conn = @ftp_connect($vars->ftp_host, $vars->ftp_port, 3))) { return new Object(-1, 'msg_ftp_not_connected'); } if (!@ftp_login($conn, $vars->ftp_user, $vars->ftp_pass)) { return new Object(-1, 'msg_ftp_invalid_auth_info'); } if (!@ftp_pasv($conn, $vars->ftp_pasv === 'Y')) { return new Object(-1, 'msg_ftp_cannot_set_passive_mode'); } if (!@ftp_chdir($conn, $vars->ftp_path)) { return new Object(-1, 'msg_ftp_invalid_path'); } ftp_close($conn); } else { if (!function_exists('ssh2_connect')) { return new Object(-1, 'disable_sftp_support'); } if (!($conn = ssh2_connect($vars->ftp_host, $vars->ftp_port))) { return new Object(-1, 'msg_ftp_not_connected'); } if (!@ssh2_auth_password($conn, $vars->ftp_user, $vars->ftp_pass)) { return new Object(-1, 'msg_ftp_invalid_auth_info'); } if (!@($sftp = ssh2_sftp($conn))) { return new Object(-1, 'msg_ftp_sftp_error'); } if (!@ssh2_sftp_stat($sftp, $vars->ftp_path . 'common/defaults/config.php')) { return new Object(-1, 'msg_ftp_invalid_path'); } unset($sftp, $conn); } // Save settings. Rhymix\Framework\Config::set('ftp.host', $vars->ftp_host); Rhymix\Framework\Config::set('ftp.port', $vars->ftp_port); Rhymix\Framework\Config::set('ftp.user', $vars->ftp_user); Rhymix\Framework\Config::set('ftp.pass', $vars->ftp_pass); Rhymix\Framework\Config::set('ftp.path', $vars->ftp_path); Rhymix\Framework\Config::set('ftp.pasv', $vars->ftp_pasv === 'Y'); Rhymix\Framework\Config::set('ftp.sftp', $vars->ftp_sftp === 'Y'); Rhymix\Framework\Config::save(); $this->setMessage('success_updated'); $this->setRedirectUrl(Context::get('success_return_url') ?: getNotEncodedUrl('', 'module', 'admin', 'act', 'dispAdminConfigFtp')); }
/** * Connect to the FTP server * * @throws \RuntimeException */ public function connect() { // Try to connect to the SSH server if (!function_exists('ssh2_connect')) { throw new \RuntimeException('Your web server does not have the SSH2 PHP module, therefore can not connect to SFTP servers.', 500); } $this->connection = ssh2_connect($this->host, $this->port); if ($this->connection === false) { $this->connection = null; throw new \RuntimeException(sprintf('Cannot connect to SFTP server [host:port] = %s:%s', $this->host, $this->port), 500); } // Attempt to authenticate if (!empty($this->publicKey) && !empty($this->privateKey)) { if (!ssh2_auth_pubkey_file($this->connection, $this->username, $this->publicKey, $this->privateKey, $this->password)) { $this->connection = null; throw new \RuntimeException(sprintf('Cannot log in to SFTP server using key files [username:private_key_file:public_key_file:password] = %s:%s:%s:%s', $this->username, $this->privateKey, $this->publicKey, $this->password), 500); } } else { if (!ssh2_auth_password($this->connection, $this->username, $this->password)) { $this->connection = null; throw new \RuntimeException(sprintf('Cannot log in to SFTP server [username:password] = %s:%s', $this->username, $this->password), 500); } } // Get an SFTP handle $this->sftpHandle = ssh2_sftp($this->connection); if ($this->sftpHandle === false) { throw new \RuntimeException('Cannot start an SFTP session with the server', 500); } // Attempt to change to the initial directory if (!@($result = @ssh2_sftp_stat($this->sftpHandle, $this->directory))) { $this->connection = null; $this->sftpHandle = null; if (!empty($this->directory)) { throw new \RuntimeException(sprintf('Cannot change to initial SFTP directory "%s" – make sure the folder exists and that you have adequate permissions to it', $this->directory), 500); } } }
/** * Return the last modified file time as an UNIX timestamp * * @param string $path The path to the directory / file * * @return int The last modified time as an UNIX timestamp */ public function lastModified(string $path) : int { return ssh2_sftp_stat($this->sftp, $path)['mtime']; }
/** * Verify that a file does not exist in the current remote folder * * @param string $filename * * @return void */ public function dontSeeRemoteFile($filename) { $sftp = ssh2_sftp($this->connection); try { $res = (bool) ssh2_sftp_stat($sftp, $filename); } catch (Exception $e) { $res = false; } \PHPUnit_Framework_Assert::assertFalse($res); }