public function unlink($path) { try { return $this->client->delete($this->absPath($path), true); } catch (\Exception $e) { return false; } }
/** * Delete the file * * @param String $file name or file path * * @return bool * @throws CMbException */ private function _delFile($file) { if (!$this->connexion) { throw new CMbException("CSourceSFTP-connexion-failed", $this->hostname); } // Download the file if (!$this->connexion->delete($file)) { throw new CMbException("CSourceSFTP-delete-file-failed", $file); } return true; }
/** * Deletes a file or directory on the SFTP/FTP server. * * @param string $path * @param bool $recursive if $path is a directory, it will delete also its content * * @return bool */ public function delete($path, $recursive = true) { switch ($this->_connType) { case SftpHelper::TYPE_SFTP: default: $res = $this->_connection->delete($path, $recursive); break; case SftpHelper::TYPE_FTP: $res = @ftp_delete($this->_connection, $path); if (!$res && $recursive) { $list = @ftp_nlist($this->_connection, $path); // if $path exists and it is a directory: if (!empty($list)) { foreach ($list as $file) { $this->delete($file, true); } // deleting the parent path after the recursion $res = $this->delete($path, false); } } break; } return $res; }
} else { echo "Message sent!"; } //unlink('/tmp/kontakti.txt'); $sftp = new Net_SFTP('podrska.bbtrade.rs'); if (!$sftp->login('root', 'bbsb100$')) { echo "Login Failed"; exit('Login Failed'); } // outputs the contents of filename.remote to the screen //echo $sftp->get('/tmp/kontakti.txt'); // copies filename.remote to filename.local from the SFTP server //$sftp->get('/tmp/kontakti.txt', '\\C$\Users\%username%\Desktop\kontakti.txt'); $sftp->get('/tmp/izvestaj.csv', '/cygdrive/c/storno/izvestaj.txt'); //ssh2.sftp://{$resSFTP}/cygdrive/c/to/path if ($sftp->delete('/tmp/izvestaj.csv')) { // doesn't delete directories echo "File /tmp/izvestaj.csv je obrisan!"; } else { echo "File /tmp/izvestaj.csv nije obrisan!"; } echo '<br />'; /*echo "Izvrsen je sledeci upit:"; echo '<br />'; echo $sql;*/ echo '<br />'; echo "Ako ste upisali ispravnu email adresu, fajl ce Vam biti isporucen putem email-a."; } } } else { //if (file_exists('/dbf/proveradir/proverafile.txt')){
public static function test($settings) { self::_init(); // Connect to server. $server = $settings['address']; $port = '22'; // Default sFTP port. if (strstr($server, ':')) { // Handle custom sFTP port. $server_params = explode(':', $server); $server = $server_params[0]; $port = $server_params[1]; } pb_backupbuddy::status('details', 'Connecting to sFTP server...'); $sftp = new Net_SFTP($server, $port); if (!$sftp->login($settings['username'], $settings['password'])) { pb_backupbuddy::status('error', 'Connection to sFTP server FAILED.'); pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.'); return __('Unable to connect to server using host, username, and password combination provided.', 'it-l10n-backupbuddy'); } else { pb_backupbuddy::status('details', 'Success connecting to sFTP server.'); } pb_backupbuddy::status('details', 'Attempting to create path (if it does not exist)...'); if (true === $sftp->mkdir($settings['path'])) { // Try to make directory. pb_backupbuddy::status('details', 'Directory created.'); } else { pb_backupbuddy::status('details', 'Directory not created.'); } $destination_file = $settings['path'] . '/backupbuddy_test.txt'; pb_backupbuddy::status('details', 'About to put to sFTP test file `backupbuddy_test.txt` to remote location `' . $destination_file . '`.'); $send_time = -microtime(true); if (true !== $sftp->put($destination_file, 'Upload test for BackupBuddy destination. Delete me.')) { pb_backupbuddy::status('details', 'sFTP test: Failure uploading test file.'); $sftp->delete($destination_file); // Just in case it partionally made file. This has happened oddly. pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.'); return __('Failure uploading. Check path & permissions.', 'it-l10n-backupbuddy'); } else { // File uploaded. pb_backupbuddy::status('details', 'File uploaded.'); if ($settings['url'] != '') { $response = wp_remote_get(rtrim($settings['url'], '/\\') . '/backupbuddy_test.txt', array('method' => 'GET', 'timeout' => 20, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array())); if (is_wp_error($response)) { return __('Failure. Unable to connect to the provided optional URL.', 'it-l10n-backupbuddy'); } if (stristr($response['body'], 'backupbuddy') === false) { return __('Failure. The path appears valid but the URL does not correspond to it. Leave the URL blank if not using this destination for migrations.', 'it-l10n-backupbuddy'); } } pb_backupbuddy::status('details', 'sFTP test: Deleting temp test file.'); $sftp->delete($destination_file); } return true; // Success if we got this far. }
/** * Poll all eligible labs for new results and store them in the database. * * @param array &$messages Receives messages of interest. * @return string Error text, or empty if no errors. */ function poll_hl7_results(&$messages) { global $srcdir; $messages = array(); $filecount = 0; $badcount = 0; $ppres = sqlStatement("SELECT * FROM procedure_providers ORDER BY name"); while ($pprow = sqlFetchArray($ppres)) { $protocol = $pprow['protocol']; $remote_host = $pprow['remote_host']; $hl7 = ''; if ($protocol == 'SFTP') { ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "{$srcdir}/phpseclib"); require_once "{$srcdir}/phpseclib/Net/SFTP.php"; // Compute the target path name. $pathname = '.'; if ($pprow['results_path']) { $pathname = $pprow['results_path'] . '/' . $pathname; } // Connect to the server and enumerate files to process. $sftp = new Net_SFTP($remote_host); if (!$sftp->login($pprow['login'], $pprow['password'])) { return xl('Login to remote host') . " '{$remote_host}' " . xl('failed'); } $files = $sftp->nlist($pathname); foreach ($files as $file) { if (substr($file, 0, 1) == '.') { continue; } ++$filecount; $hl7 = $sftp->get("{$pathname}/{$file}"); // Archive the results file. $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results"; if (!file_exists($prpath)) { mkdir($prpath); } $prpath .= '/' . $pprow['ppid']; if (!file_exists($prpath)) { mkdir($prpath); } $fh = fopen("{$prpath}/{$file}", 'w'); if ($fh) { fwrite($fh, $hl7); fclose($fh); } else { $messages[] = xl('File') . " '{$file}' " . xl('cannot be archived, ignored'); ++$badcount; continue; } // Now delete it from its ftp directory. if (!$sftp->delete("{$pathname}/{$file}")) { $messages[] = xl('File') . " '{$file}' " . xl('cannot be deleted, ignored'); ++$badcount; continue; } // Parse and process its contents. $msg = receive_hl7_results($hl7); if ($msg) { $messages[] = xl('Error processing file') . " '{$file}':" . $msg; ++$badcount; continue; } $messages[] = xl('New file') . " '{$file}' " . xl('processed successfully'); } } // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols. } if ($badcount) { return "{$badcount} " . xl('error(s) encountered from new results'); } return ''; }
function remove_ftp_backup($args) { extract($args); //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder if (isset($use_sftp) && $use_sftp == 1) { $port = $ftp_port ? $ftp_port : 22; //default port is 22 /* * SFTP section start here phpseclib library is used for this functionality */ $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__)); $path = $iwp_mmb_plugin_dir . '/lib/phpseclib'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); include_once 'Net/SFTP.php'; $sftp = new Net_SFTP($ftp_hostname, $port); if (!$sftp) { return array('error' => 'Failed to connect to ' . $ftp_hostname, 'partial' => 1); } if (!$sftp->login($ftp_username, $ftp_password)) { return array('error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password, 'partial' => 1); } else { if ($ftp_site_folder) { $ftp_remote_folder .= '/' . $this->site_name; } $remote_loation = basename($backup_file); $local_location = $backup_file; $sftp->chdir($ftp_remote_folder); $sftp->delete(basename($backup_file)); } //SFTP library has automatic connection closed. So no need to call seperate connection close function } else { $port = $ftp_port ? $ftp_port : 21; //default port is 21 if ($ftp_ssl && function_exists('ftp_ssl_connect')) { $conn_id = ftp_ssl_connect($ftp_hostname, $port); } else { if (function_exists('ftp_connect')) { $conn_id = ftp_connect($ftp_hostname, $port); } } if ($conn_id) { $login = @ftp_login($conn_id, $ftp_username, $ftp_password); if ($ftp_site_folder) { $ftp_remote_folder .= '/' . $this->site_name; } if ($ftp_passive) { @ftp_pasv($conn_id, true); } if (!is_array($backup_file)) { $temp_backup_file = $backup_file; $backup_file = array(); $backup_file[] = $temp_backup_file; } foreach ($backup_file as $key => $value) { $delete = ftp_delete($conn_id, $ftp_remote_folder . '/' . $value); } ftp_close($conn_id); } } }
/** * Delete a file * */ public function rm($filename) { return $this->_connection->delete($filename); }
return false; } else { pb_backupbuddy::status('details', 'Success connecting to sFTP server.'); } // Change to directory. pb_backupbuddy::status('details', 'Attempting to change into directory...'); if (true === $sftp->chdir($destination['path'])) { pb_backupbuddy::status('details', 'Changed into directory.'); } else { pb_backupbuddy::status('error', 'Unable to change into specified path. Verify the path is correct with valid permissions.'); return false; } // loop through and delete ftp backup files foreach ((array) pb_backupbuddy::_POST('items') as $backup) { // try to delete backup if (true === $sftp->delete($backup)) { $delete_count++; } else { pb_backupbuddy::alert('Unable to delete file `' . $destination['path'] . '/' . $backup . '`.'); } } if ($delete_count > 0) { pb_backupbuddy::alert(sprintf(_n('Deleted %d file.', 'Deleted %d files.', $delete_count, 'it-l10n-backupbuddy'), $delete_count)); } else { pb_backupbuddy::alert(__('No backups were deleted.', 'it-l10n-backupbuddy')); } echo '<br>'; } // Connect to server. $server = $destination['address']; $port = '22';
/** * Poll all eligible labs for new results and store them in the database. * * @param array &$info Conveys information to and from the caller: * FROM THE CALLER: * $info["$ppid/$filename"]['delete'] = a non-empty value if file deletion is requested. * $info['select'] = array of patient matching responses where key is serialized patient * attributes and value is selected pid for this patient, or 0 to create the patient. * TO THE CALLER: * $info["$ppid/$filename"]['mssgs'] = array of messages from this function. * $info['match'] = array of patient matching requests where key is serialized patient * attributes (ss, fname, lname, DOB) and value is TRUE (irrelevant). * * @return string Error text, or empty if no errors. */ function poll_hl7_results(&$info) { global $srcdir; // echo "<!-- post: "; print_r($_POST); echo " -->\n"; // debugging // echo "<!-- in: "; print_r($info); echo " -->\n"; // debugging $filecount = 0; $badcount = 0; if (!isset($info['match'])) { $info['match'] = array(); } // match requests if (!isset($info['select'])) { $info['select'] = array(); } // match request responses $ppres = sqlStatement("SELECT * FROM procedure_providers ORDER BY name"); while ($pprow = sqlFetchArray($ppres)) { $ppid = $pprow['ppid']; $protocol = $pprow['protocol']; $remote_host = $pprow['remote_host']; $hl7 = ''; if ($protocol == 'SFTP') { $remote_port = 22; // Hostname may have ":port" appended to specify a nonstandard port number. if ($i = strrpos($remote_host, ':')) { $remote_port = 0 + substr($remote_host, $i + 1); $remote_host = substr($remote_host, 0, $i); } ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "{$srcdir}/phpseclib"); require_once "{$srcdir}/phpseclib/Net/SFTP.php"; // Compute the target path name. $pathname = '.'; if ($pprow['results_path']) { $pathname = $pprow['results_path'] . '/' . $pathname; } // Connect to the server and enumerate files to process. $sftp = new Net_SFTP($remote_host, $remote_port); if (!$sftp->login($pprow['login'], $pprow['password'])) { return xl('Login to remote host') . " '{$remote_host}' " . xl('failed'); } $files = $sftp->nlist($pathname); foreach ($files as $file) { if (substr($file, 0, 1) == '.') { continue; } ++$filecount; if (!isset($info["{$ppid}/{$file}"])) { $info["{$ppid}/{$file}"] = array(); } // Ensure that archive directory exists. $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results"; if (!file_exists($prpath)) { mkdir($prpath); } $prpath .= '/' . $pprow['ppid']; if (!file_exists($prpath)) { mkdir($prpath); } // Get file contents. $hl7 = $sftp->get("{$pathname}/{$file}"); // If user requested reject and delete, do that. if (!empty($info["{$ppid}/{$file}"]['delete'])) { $fh = fopen("{$prpath}/{$file}.rejected", 'w'); if ($fh) { fwrite($fh, $hl7); fclose($fh); } else { return xl('Cannot create file') . ' "' . "{$prpath}/{$file}.rejected" . '"'; } if (!$sftp->delete("{$pathname}/{$file}")) { return xl('Cannot delete (from SFTP server) file') . ' "' . "{$pathname}/{$file}" . '"'; } continue; } // Do a dry run of its contents and check for errors and match requests. $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']); $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs']; // $info["$ppid/$file"]['match'] = $tmp['match']; if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) { // There are errors or matching requests so skip this file. continue; } // Now the money shot - not a dry run. $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']); $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs']; // $info["$ppid/$file"]['match'] = $tmp['match']; if (empty($tmp['fatal']) && empty($tmp['needmatch'])) { // It worked, archive and delete the file. $fh = fopen("{$prpath}/{$file}", 'w'); if ($fh) { fwrite($fh, $hl7); fclose($fh); } else { return xl('Cannot create file') . ' "' . "{$prpath}/{$file}" . '"'; } if (!$sftp->delete("{$pathname}/{$file}")) { return xl('Cannot delete (from SFTP server) file') . ' "' . "{$pathname}/{$file}" . '"'; } } } // end of this file } else { if ($protocol == 'FS') { // Filesystem directory containing results files. $pathname = $pprow['results_path']; if (!($dh = opendir($pathname))) { return xl('Unable to access directory') . " '{$pathname}'"; } // Sort by filename just because. $files = array(); while (false !== ($file = readdir($dh))) { if (substr($file, 0, 1) == '.') { continue; } $files[$file] = $file; } closedir($dh); ksort($files); // For each file... foreach ($files as $file) { ++$filecount; if (!isset($info["{$ppid}/{$file}"])) { $info["{$ppid}/{$file}"] = array(); } // Ensure that archive directory exists. $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results"; if (!file_exists($prpath)) { mkdir($prpath); } $prpath .= '/' . $pprow['ppid']; if (!file_exists($prpath)) { mkdir($prpath); } // Get file contents. $hl7 = file_get_contents("{$pathname}/{$file}"); // If user requested reject and delete, do that. if (!empty($info["{$ppid}/{$file}"]['delete'])) { $fh = fopen("{$prpath}/{$file}.rejected", 'w'); if ($fh) { fwrite($fh, $hl7); fclose($fh); } else { return xl('Cannot create file') . ' "' . "{$prpath}/{$file}.rejected" . '"'; } if (!unlink("{$pathname}/{$file}")) { return xl('Cannot delete file') . ' "' . "{$pathname}/{$file}" . '"'; } continue; } // Do a dry run of its contents and check for errors and match requests. $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']); $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs']; // $info["$ppid/$file"]['match'] = $tmp['match']; if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) { // There are errors or matching requests so skip this file. continue; } // Now the money shot - not a dry run. $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']); $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs']; // $info["$ppid/$file"]['match'] = $tmp['match']; if (empty($tmp['fatal']) && empty($tmp['needmatch'])) { // It worked, archive and delete the file. $fh = fopen("{$prpath}/{$file}", 'w'); if ($fh) { fwrite($fh, $hl7); fclose($fh); } else { return xl('Cannot create file') . ' "' . "{$prpath}/{$file}" . '"'; } if (!unlink("{$pathname}/{$file}")) { return xl('Cannot delete file') . ' "' . "{$pathname}/{$file}" . '"'; } } } // end of this file } } // end FS protocol // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols. } // end procedure provider // echo "<!-- out: "; print_r($info); echo " -->\n"; // debugging return ''; }
<?php session_start(); include 'header.php'; include 'Net/SFTP.php'; $file = $_GET['file']; $sftp = new Net_SFTP(SSH_HOST); if ($sftp->login($_SESSION['id'], $_SESSION['passwd'])) { $sftp->delete('/scratch/' . $_SESSION['id'] . '/meshslicer/' . $file); $reply = json_encode(array('Error' => '0', 'Message' => "")); unset($_SESSION['fileList'][array_search($file, $_SESSION['fileList'])]); } else { $reply = json_encode(array('Error' => '1', 'Message' => 'Astral problem. Please try again.')); } echo $reply;
/** * Deletes filename specified by the path * * Deletes a file * * @param String $path * @return bool * @access public */ public function unlink($path) { $connection = $this->stream_open($path, NULL, NULL, $opened_path); if ($connection === false) { return FALSE; } $del = $this->sftp->delete($this->path); $this->stream_close(); return $del; }
public function delete($filename) { return $this->conn->delete($filename); }
/** * Deletes backup file from remote sftp server. * * @param array $args arguments passed to the function * [sftp_username] -> sftp username on remote server * [sftp_password] -> sftp password on remote server * [sftp_hostname] -> sftp hostname of remote host * [sftp_remote_folder] -> folder on remote site which backup file should be deleted from * [sftp_site_folder] -> subfolder with site name in ftp_remote_folder which backup file should be deleted from * [backup_file] -> absolute path of backup file on local server * @return void */ function remove_sftp_backup($args) { extract($args); file_put_contents("sftp_log.txt", "sftp remove_sftp_backup", FILE_APPEND); $port = $sftp_port ? $sftp_port : 22; //default port is 21 $sftp_hostname = $sftp_hostname ? $sftp_hostname : ""; $sftp_username = $sftp_username ? $sftp_username : ""; $sftp_password = $sftp_password ? $sftp_password : ""; $sftp = new Net_SFTP($sftp_hostname); if (!$sftp->login($sftp_username, $sftp_password)) { file_put_contents("sftp_log.txt", "sftp login failed in remove_sftp_backup", FILE_APPEND); return false; } $remote = $sftp_remote_folder ? trim($sftp_remote_folder, "/") . "/" : ''; // copies filename.local to filename.remote on the SFTP server if (isset($backup_file) && isset($remote) && $backup_file !== "") { $upload = $sftp->delete($remote . '/' . $backup_file); } $sftp->disconnect(); }
public function PXEFiles() { $removeArray = array(); foreach ($this->PXEData as $k => $v) { $privateKey = EASYWIDIR . '/keys/' . removePub($v['keyname']); $sftpObject = new Net_SFTP($v['ip'], $v['port']); if ($sftpObject->error === false) { if ($v['publickey'] == 'Y' and file_exists($privateKey)) { $ssh2Pass = new Crypt_RSA(); if ($v['publickey'] == 'B') { $ssh2Pass->setPassword($v['pass']); } $ssh2Pass->loadKey(file_get_contents($privateKey)); } else { $ssh2Pass = $v['pass']; } if ($sftpObject->login($v['user'], $ssh2Pass)) { foreach ($v['actions'] as $a) { $extraSlash = (substr($v['PXEFolder'], -1) != '/' and strlen($v['PXEFolder']) > 0) ? '/' : ''; $pathWithPXEMac = $v['PXEFolder'] . $extraSlash . '01-' . str_replace(':', '-', $this->ID[$a['type']][$a['id']]['mac']); $fileWithPath = substr($v['PXEFolder'], 0, 1) == '/' ? $pathWithPXEMac : '/home/' . $v['user'] . '/' . $pathWithPXEMac; if (in_array($a['action'], array('dl', 'md', 'rp', 'rt'))) { $sftpObject->delete($pathWithPXEMac); } else { if (in_array($a['action'], array('ad', 'ri', 'rc'))) { $removeArray[] = array('type' => $a['type'] == 'dedicated' ? 'de' : 'vs', 'affectedID' => $a['id'], 'name' => $this->ID[$a['type']][$a['id']]['ip'], 'imageID' => $a['imageID'], 'hostID' => $a['hostID'], 'userID' => $a['userID'], 'resellerID' => $a['resellerID'], 'extraData' => array('runAt' => strtotime("+5 minutes"))); $query = $this->sql->prepare("SELECT `pxelinux` FROM `resellerimages` WHERE `id`=? AND `active`='Y' LIMIT 1"); $query->execute(array($a['imageID'])); $pxeconfig = $query->fetchColumn(); if (strlen($pxeconfig) > 0) { $newPass = passwordgenerate(12); $pxeconfig = str_replace('%rescuepass%', $newPass, $pxeconfig); if ($a['type'] == 'dedicated') { $query = $this->sql->prepare("UPDATE `rootsDedicated` SET `initialPass`=AES_ENCRYPT(?,?),`pxeID`=? WHERE `dedicatedID`=? LIMIT 1"); $query->execute(array($newPass, $this->aeskey, $k, $a['id'])); } else { $query = $this->sql->prepare("UPDATE `virtualcontainer` SET `pass`=AES_ENCRYPT(?,?),`pxeID`=? WHERE `id`=? LIMIT 1"); $query->execute(array($newPass, $this->aeskey, $k, $a['id'])); } $sftpObject->put($fileWithPath, $pxeconfig); } else { $tempBad[] = 'pxefile template empty for imageID: ' . $a['imageID']; } } } } } else { $tempBad[] = 'Could login to PXE server: ' . $v['ip'] . ':' . $v['port']; } } else { $tempBad[] = 'Could not connect to PXE server: ' . $v['ip'] . ':' . $v['port']; } if (isset($tempBad) and isset($bad)) { $bad = array_merge($bad, $tempBad); } else { if (isset($tempBad) and !isset($bad)) { $bad = $tempBad; } } } if (isset($bad)) { print_r(implode(' ', $bad)); } return $removeArray; }