public function __construct($config = array()) { $this->initConfig($config); $this->conn = new Net_SFTP($this->server, $this->port, $this->timeout); if (!$this->conn->login($this->user, $this->pwd)) { throw new WindFtpException($this->user, WindFtpException::LOGIN_FAILED); } $this->initRootPath(); }
function sftp_printer($xml_file) { if (strrpos(get_include_path(), "phpseclib0.3.0") === false) { set_include_path(get_include_path() . PATH_SEPARATOR . './phpseclib0.3.0'); // Staging requires the ../ to be ./ } include 'Net/SFTP.php'; $rtn = false; $sftp = new Net_SFTP('ftp.tginc.com', 2222); if (isset($_GET['tID'])) { echo $sftp->login('flatterbox', 'T&!Fl@!!er'); } //if ( isset($_GET['tID']) ) : print_r( $sftp->getSupportedVersions() ); endif; if (!$sftp->login('flatterbox', 'T&!Fl@!!er') || true) { $rtn = 'Login Failed'; } $local_directory = './orderlist/'; // Set in previous function -- orderlist/'; $remote_directory = '/incoming/'; //echo $local_directory.'<br/>'; //echo $remote_directory.'<br/>'; $files_to_upload = array(); if ($xml_file != "." && $xml_file != "..") { $files_to_upload[] = $xml_file; } if (!empty($files_to_upload) && $rtn == false) { foreach ($files_to_upload as $file) { /* echo dirname(__FILE__).'<br/>'; echo $file.'<br/>'; echo $local_directory . $file.'<br/>'; */ //$rtn = $sftp->put($remote_directory . $file, $local_directory . $file, NET_SFTP_LOCAL_FILE); $data = file_get_contents($local_directory . $file); if (isset($_GET['tID'])) { echo $data; } $rtn = $sftp->put($remote_directory . $file, $data); } } return $rtn; /* $conn = ssh2_connect('ftp.tginc.com', 2222); ssh2_auth_password($conn, 'flatterbox', 'T&!Fl@!!er'); // send a file return ssh2_scp_send($conn, $local_directory.$xml_file, $remote_directory.$xml_file, 0644); */ }
function escribe_archivo_via_sftp($cadena, $nombre_archivo_remoto = "", $factura_id, $fe_folio) { $sql_update = "update vta_p_facturas set \n\tFE_SERIE='A', FE_FOLIO={$fe_folio}\n\twhere (FE_SERIE = '' OR FE_SERIE IS NULL or FE_SERIE=0) AND (FE_FOLIO = '' OR FE_FOLIO IS NULL or FE_FOLIO =0) \n\tAND FACTURA_ID=" . $factura_id; $result_update = mysql_db_query(DB_NAME, $sql_update); // echo $sql_update; define("TEPath", "../TableEditor/"); include '../TableEditor/Net/SFTP.php'; // $ftp_sitio="demo-partners.xsa.com.mx"; // $ftp_usuario="testftpfacciisa"; // $ftp_pass="******"; $ftp_sitio = "173.205.255.84"; $ftp_usuario = "ftpciisa"; $ftp_pass = "******"; $sftp = new Net_SFTP($ftp_sitio); if (!$sftp->login($ftp_usuario, $ftp_pass)) { exit('Acceso incorrecto..'); } $sftp->put($nombre_archivo_remoto, utf8_encode($cadena)); $sftp->chdir("1"); $sftp->put($nombre_archivo_remoto, utf8_encode($cadena)); $folio_fiscal = consulta("select FOLIO_FISCAL from vta_p_facturas WHERE FACTURA_ID=" . $factura_id); $folio_fiscal = $folio_fiscal["FOLIO_FISCAL"]; //echo $fe_serie["FE_FOLIO"]."+"; echo "Envio exitoso... Factura " . $folio_fiscal; }
/** * Open a SFTP connection to a remote site. * * @param array $args Connection arguments * @param string $args[host] Remote hostname * @param string $args[username] Remote username * @param string $args[password] Connection password * @param int $args[timeout] Connection timeout [=10] * */ public function open(array $args = array()) { if (!isset($args['timeout'])) { $args['timeout'] = self::REMOTE_TIMEOUT; } if (strpos($args['host'], ':') !== false) { list($host, $port) = explode(':', $args['host'], 2); } else { $host = $args['host']; $port = self::SSH2_PORT; } $this->_connection = new Net_SFTP($host, $port, $args['timeout']); if (!$this->_connection->login($args['username'], $args['password'])) { throw new Exception(sprintf(__("Unable to open SFTP connection as %s@%s", $args['username'], $args['host']))); } }
public function __construct($params) { // The sftp:// scheme has to be manually registered via inclusion of // the 'Net/SFTP/Stream.php' file which registers the Net_SFTP_Stream // stream wrapper as a side effect. // A slightly better way to register the stream wrapper is available // since phpseclib 0.3.7 in the form of a static call to // Net_SFTP_Stream::register() which will trigger autoloading if // necessary. // TODO: Call Net_SFTP_Stream::register() instead when phpseclib is // updated to 0.3.7 or higher. require_once 'Net/SFTP/Stream.php'; $this->host = $params['host']; $proto = strpos($this->host, '://'); if ($proto != false) { $this->host = substr($this->host, $proto + 3); } $this->user = $params['user']; $this->password = $params['password']; $this->root = isset($params['root']) ? $this->cleanPath($params['root']) : '/'; if ($this->root[0] != '/') { $this->root = '/' . $this->root; } if (substr($this->root, -1, 1) != '/') { $this->root .= '/'; } $hostKeys = $this->readHostKeys(); $this->client = new \Net_SFTP($this->host); // The SSH Host Key MUST be verified before login(). $currentHostKey = $this->client->getServerPublicHostKey(); if (array_key_exists($this->host, $hostKeys)) { if ($hostKeys[$this->host] != $currentHostKey) { throw new \Exception('Host public key does not match known key'); } } else { $hostKeys[$this->host] = $currentHostKey; $this->writeHostKeys($hostKeys); } if (!$this->client->login($this->user, $this->password)) { throw new \Exception('Login failed'); } }
/** * Login to the SFTP service. * * @throws ServiceException * Whe we can't login to the SFTP server. */ protected function login() { if ($this->loggedIn) { return true; } $result = $this->sftp->login($this->getUsername(), $this->getPassword()); if (!$result) { throw new ServiceException(sprintf('Can\'t login with user "%s".', $this->getUsername())); } $this->loggedIn = true; }
/** * copy a file from the remote server to the local install * @param $source string * @param $destination string * @return bool */ public function scpRemoteLocal($source, $destination) { $sftp = new \Net_SFTP(Setting::getSetting('remote:host')); $key = new Crypt_RSA(); $key->loadKey(file_get_contents(Setting::getSetting('ssh:priv_key'))); if (!$sftp->login(Setting::getSetting('remote:user'), $key)) { $cli = new CLImate(); $cli->error("Could not connect to server"); return false; } $sftp->get($source, $destination); }
/** * Returns the connection. * * @return \Net_SFTP connected client instance * @throws \Exception when the connection failed */ public function getConnection() { if (!is_null($this->client)) { return $this->client; } $hostKeys = $this->readHostKeys(); $this->client = new \Net_SFTP($this->host); // The SSH Host Key MUST be verified before login(). $currentHostKey = $this->client->getServerPublicHostKey(); if (array_key_exists($this->host, $hostKeys)) { if ($hostKeys[$this->host] != $currentHostKey) { throw new \Exception('Host public key does not match known key'); } } else { $hostKeys[$this->host] = $currentHostKey; $this->writeHostKeys($hostKeys); } if (!$this->client->login($this->user, $this->password)) { throw new \Exception('Login failed'); } return $this->client; }
public function connect() { // we have to mangle the include path a little to find our plugins $oldIncludePath = get_include_path(); set_include_path($oldIncludePath . ':' . TL_ROOT . '/plugins/phpseclib/:' . TL_ROOT . '/plugins/phpseclib/Net:' . TL_ROOT . '/plugins/phpseclib/Crypt'); include 'SFTP.php'; if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) { include 'RSA.php'; } set_include_path($oldIncludePath); $this->ftpHost = $GLOBALS['TL_CONFIG']['ftpHost']; $this->ftpPort = $GLOBALS['TL_CONFIG']['ftpPort']; $this->ftpUser = $GLOBALS['TL_CONFIG']['ftpUser']; if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) { $key = new Crypt_RSA(); if ($GLOBALS['TL_CONFIG']['sftpKeyPass']) { $key->setPassword($GLOBALS['TL_CONFIG']['sftpKeyPass']); } $key->loadKey(file_get_contents($GLOBALS['TL_CONFIG']['sftpKeyFile'])); $this->ftpPass = $key; } else { $this->ftpPass = $GLOBALS['TL_CONFIG']['ftpPass']; } $this->ftpPath = $GLOBALS['TL_CONFIG']['ftpPath']; // Connect to FTP server if (!is_numeric($this->ftpPort) || $this->ftpPort == 0) { $this->ftpPort = 22; } if ($GLOBALS['TL_CONFIG']['debugSmhExtended']) { define('NET_SSH2_LOGGING', true); define('NET_SFTP_LOGGING', true); } if (($resConnection = new Net_SFTP($this->ftpHost, $this->ftpPort, 5)) != false) { // Login if (!$resConnection->login($this->ftpUser, $this->ftpPass)) { throw new Exception('Could not login to sftp: ' . $resConnection->getLastError() . (defined('NET_SSH2_LOGGING') ? implode("\n", $resConnection->message_number_log) : '')); } // security, clean user id and password as we won't need them anymore. $this->ftpUser = NULL; $this->ftpPass = NULL; // change to root directory to ensure we can really work. $resConnection->chdir($this->ftpPath); $this->resConnection = $resConnection; return $resConnection; } else { throw new Exception('Could not connect to sftp: ' . $resConnection->getLastError()); } }
/** * @param array $config * * @throws Mageplace_Backup_Exception|Mage_Core_Exception * @return Net_SFTP */ public function getSftp(array $config = array()) { if ($this->_getData('sftp') === null) { $host = $this->getConfigValue(self::HOST); $port = (int) $this->getConfigValue(self::PORT); if ($port <= 0) { $port = self::DEFAULT_PORT; } $sftp = new Net_SFTP($host, $port, $this->getTimeOut()); if (!$sftp->login($this->getConfigValue(self::USERNAME), $this->getConfigValue(self::PASSWORD))) { $this->_throwExeption($this->_helper->__("SFTP connection error: unable to open connection as %s@%s:%d", $this->getConfigValue(self::USERNAME), $host, $port)); } if ($path = rtrim($this->getConfigValue(self::PATH), '/')) { if (!$sftp->chdir($path)) { $this->_throwExeption($this->_helper->__('SFTP connection error: invalid path')); } } $this->setData('sftp', $sftp); } return $this->_getData('sftp'); }
/** * @param \Cogeco\Build\Entity\Host $host * @return \Net_SFTP * @throws \Cogeco\Build\Exception */ public static function connect(Host $host) { // Throw an exception if no host is provided if (empty($host)) { throw new Exception(__METHOD__ . "() No host specified"); } // If the connection doesn't already exist, create it if (empty(self::$handles[$host->hostname])) { self::log("- Starting an SSH session on {$host->hostname} for user {$host->account->username}\n\n"); self::$handles[$host->hostname] = $handle = new \Net_SFTP($host->hostname); if (!$handle->login($host->account->username, $host->account->password)) { throw new Exception(__METHOD__ . '() SSH connection failed'); } // Set the home folder, if it isn't explicitly set already $homeDirPath = $handle->pwd(); if (empty($host->homeDirPath) && !empty($homeDirPath)) { $host->homeDirPath = $homeDirPath; } } return self::$handles[$host->hostname]; }
public function file_list($srvid, $dir, $tpl_browse = false) { if (empty($srvid)) { return 'No server ID given'; } // Get network ID (if browsing for template, use given ID as it's already a network ID if ($tpl_browse) { $this_netid = $srvid; } else { $result_nid = @mysql_query("SELECT netid FROM servers WHERE id = '{$srvid}' LIMIT 1"); $row_nid = mysql_fetch_row($result_nid); $this_netid = $row_nid[0]; } if (empty($this_netid)) { return 'Failed to get network ID!'; } require DOCROOT . '/includes/classes/network.php'; $Network = new Network(); $netinfo = $Network->netinfo($this_netid); $net_local = $netinfo['is_local']; #$net_game_ip = $netinfo['game_ip']; $ssh_ip = $netinfo['ssh_ip']; $ssh_port = $netinfo['ssh_port']; $ssh_user = $netinfo['ssh_user']; $ssh_pass = $netinfo['ssh_pass']; $ssh_homedir = $netinfo['ssh_homedir']; $net_local = $netinfo['is_local']; // Get real server info if (!class_exists('Servers')) { require DOCROOT . '/includes/classes/servers.php'; } $Servers = new Servers(); $srvinfo = $Servers->getinfo($srvid); $net_game_ip = $srvinfo[0]['ip']; $net_gameuser = $srvinfo[0]['username']; $net_game_port = $srvinfo[0]['port']; // Cant read any files with . in them (includes .filename and ../) if (preg_match('/^\\./', $dir)) { $dir = stripslashes($dir); $dir = strip_tags($dir); return 'Invalid directory provided (' . $dir . ')!'; } ################################################################ // Local Listing if ($net_local) { $local_dir = DOCROOT . '/_SERVERS/'; // Browsing for templates. Start at homedir if ($tpl_browse) { $game_dir = $local_dir; } else { $game_dir = $local_dir . '/accounts/' . $net_gameuser . '/' . $net_game_ip . '.' . $net_game_port; } // Append new directory to basedir if ($dir) { $game_dir .= '/' . $dir; } ########################################################################################## // File Contents if (preg_match('/\\.(txt|cfg|rc|log|ini|inf|vdf|yml|properties|json|conf)$/i', $dir)) { if (!file_exists($game_dir)) { return 'That file doesnt exist or the webserver cannot view it.'; } // Read file $fh = fopen($game_dir, "rb"); $file_content = fread($fh, filesize($game_dir)); fclose($fh); // Return remote file content return $file_content; } ########################################################################################## // Continue with directory listing if (GPXDEBUG) { $add_path = '(' . $game_dir . ') '; } else { $add_path = ''; } if (!is_dir($game_dir)) { die('Sorry, that game directory ' . $add_path . 'does not exist!'); } $dir = dir($game_dir); $dir_arr = array(); $count_dir = 0; // Permission errors etc if (!opendir($game_dir)) { return 'err_opendir'; } // Loop over files, no . or .. dirs while (($file = $dir->read()) !== false) { if (!preg_match('/^\\.+/', $file)) { $full_path = $game_dir . '/' . $file; if (is_dir($full_path)) { $thetype = '2'; } else { $thetype = '1'; } #$dir_arr[$count_dir]['name'] = $file; #$dir_arr[$count_dir]['size'] = filesize($full_path); #$dir_arr[$count_dir]['mtime'] = filemtime($full_path); #$dir_arr[$count_dir]['atime'] = fileatime($full_path); #$dir_arr[$count_dir]['perms'] = fileperms($full_path); #$dir_arr[$count_dir]['type'] = $thetype; $dir_arr[$file]['size'] = filesize($full_path); $dir_arr[$file]['mtime'] = filemtime($full_path); $dir_arr[$file]['atime'] = fileatime($full_path); $dir_arr[$file]['uid'] = fileowner($full_path); $dir_arr[$file]['gid'] = filegroup($full_path); $dir_arr[$file]['permissions'] = fileperms($full_path); $dir_arr[$file]['type'] = $thetype; } $count_dir++; } $dir->close(); return $dir_arr; } else { // Not browsing for templates if (!$tpl_browse) { // Use real SSO user's login, not gpx login $sso_info = $Network->sso_info($srvid); $ssh_user = $sso_info['sso_user']; $ssh_pass = $sso_info['sso_pass']; $sso_username = $sso_info['username']; $sso_gamedir = $sso_info['game_path']; // Set game dir $game_dir = $sso_gamedir; if (GPXDEBUG) { echo "DEBUG: Gamedir: {$sso_gamedir}, SSO User: {$ssh_user}, Username: {$sso_username}<br>"; } // File Contents if (preg_match('/\\.(txt|cfg|rc|log|ini|inf|vdf|yml|properties|json|conf)$/i', $dir)) { if ($tpl_browse) { return 'Sorry, you cannot edit files while browsing for templates!'; } $net_cmd = 'FileContent -f ' . $game_dir . '/' . $dir; $file_content = $Network->runcmd($this_netid, $netinfo, $net_cmd, true, $srvid); // Return remote file content return $file_content; } } else { // Use normal SSH homedir $game_dir = $ssh_homedir; } ########################################################################################## // PHPSecLib (Pure-PHP SSH Implementation) require DOCROOT . '/includes/SSH/Net/SFTP.php'; // Setup Connection $sftp = new Net_SFTP($ssh_ip, $ssh_port, 12); // Test login if (!$sftp->login($ssh_user, $ssh_pass)) { return 'ERROR: Failed to login to the remote server'; } // Append new directory to basedir if ($dir) { $game_dir .= '/' . $dir; } // Get raw file list $file_list = $sftp->rawlist($game_dir); return $file_list; } }
} echo '<br>'; } // Connect to server. $server = $destination['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($destination['username'], $destination['password'])) { pb_backupbuddy::status('error', 'Connection to sFTP server FAILED.'); return false; } 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($destination['path'])) { // Try to make directory. pb_backupbuddy::status('details', 'Directory created.'); } else { pb_backupbuddy::status('details', 'Directory not created.'); } // List files. $files = $sftp->rawlist($destination['path']); $backups = array();
/** * 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 ''; }
mail($to,$subject,$msg); exit(0); }*/ //if(file_exists($encryptedFileName)) if (file_exists($localfilename)) { include "Net/SFTP.php"; $ftp_server = 'PDCFTP.cvty.com'; $ftp_user = '******'; $ftp_password = '******'; $ftp_port = '21000'; $ftp_directory = '/Incoming/'; //'/Test/Incoming/' $sftp = new Net_SFTP($ftp_server, $ftp_port); // FTP Login if ($sftp->login($ftp_user, $ftp_password)) { // Change directory if ($sftp->chdir($ftp_directory)) { if ($sftp->put($remoteFileName, $localfilename, NET_SFTP_LOCAL_FILE)) { $destFileName = str_replace('C:\\Inetpub\\wwwroot\\plexis\\php\\', 'D:\\Documents\\Misc\\' . $clientName . "_", $savePathAndFileName); //echo "destFileName: ".$destFileName."\n"; //echo "localfilename: ".$localfilename."\n"; //echo "remoteFileName: ".$remoteFileName."\n"; if (file_exists($destFileName)) { unlink($destFileName); } rename($localfilename, $destFileName); } else { $msg = "Unable to put " . $localfilename . " file to [" . $ftp_server . "] /" . $ftp_directory . "/" . $remoteFileName . "<br/>"; } } else {
public function createSFTPSession() { $sftp_url = $this->config['batch_url']; $sftp_username = $this->config['sftp_username']; $sftp_password = $this->config['sftp_password']; $session = new \Net_SFTP($sftp_url); if (!$session->login($sftp_username, $sftp_password)) { throw new \RuntimeException("Failed to SFTP with the username {$sftp_username} and the password {$sftp_password} to the host {$sftp_url}. Check your credentials!"); } return $session; }
//HTML Body $mail->AltBody = "AltBody - U prilogu je izvestaj o storno stavkama u txt formatu"; // optional, comment out and test $mail->WordWrap = 50; // set word wrap //$mail->MsgHTML($body); // send email //$mail = mail($to,$subject,$message,$header); if (!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } 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!"; }
public function downloadFromFulfillment() { $arrayCsvFiles = array(); $arrayCsvFilesClear = array(); $sql = "SELECT *\n FROM `fulfillment_files`\n WHERE `fulfillment_id`=?i"; $result = self::$_msql->getInd('filename', $sql, $this->fulfillment_id); if ($this->ssl) { $sftp = new Net_SFTP($this->server); if (!$sftp->login($this->username, $this->password)) { exit('Login Failed'); } //$contents = $sftp->nlist("{$this->download_path}"); $dPath = trim($this->download_path, '/'); $contents = $sftp->nlist("{$dPath}"); if (!$contents) { return; } foreach ($contents as $file) { if (substr($file, -4, 4) == '.csv') { $arrayCsvFiles[] = $arrayCsvFilesClear[] = $file; } } foreach ($arrayCsvFiles as $file) { $tF = explode('/', $file); $fName = array_pop($tF); if (isset($result["{$fName}"])) { continue; } $downloadFilePath = AF::path(time() . rand(1, 1000), array('files', 'csv', 'temp'), 'csv'); if ($sftp->get($dPath . '/' . $file, $downloadFilePath)) { self::parserCsvFiles($downloadFilePath); $sql = "INSERT INTO `fulfillment_files` (`fulfillment_id`, `filename`, `time`) VALUES (?i, ?s, NOW())"; self::$_msql->query($sql, $this->fulfillment_id, $fName); } } $sftp->_disconnect(0); } else { $ftp = ftp_connect($this->server, $this->port, 300); if (!$ftp) { return; } if ($this->username && $this->password) { ftp_login($ftp, $this->username, $this->password); } ftp_pasv($ftp, true); // Passive mode $contents = ftp_nlist($ftp, "{$this->download_path}"); if (!$contents) { return; } foreach ($contents as $file) { if (substr($file, -4, 4) == '.csv') { $file = str_replace('\\', '/', $file); $arrayCsvFiles[] = $file; $tF = explode('/', $file); $arrayCsvFilesClear[] = (string) trim(array_pop($tF)); } } foreach ($arrayCsvFiles as $file) { $tF = explode('/', $file); $fName = (string) trim(array_pop($tF)); if (isset($result["{$fName}"])) { continue; } $downloadFilePath = AF::path(time() . rand(1, 1000), array('files', 'csv', 'temp'), 'csv'); if (ftp_get($ftp, $downloadFilePath, $file, FTP_ASCII)) { self::parserCsvFiles($downloadFilePath); $sql = "INSERT INTO `fulfillment_files` (`fulfillment_id`, `filename`, `time`) VALUES (?i, ?s, NOW())"; self::$_msql->query($sql, $this->fulfillment_id, $fName); } } ftp_close($ftp); } $sql = "DELETE FROM `fulfillment_files`\n WHERE `fulfillment_id` = ?i\n AND `filename` NOT IN (?a)"; self::$_msql->query($sql, $this->fulfillment_id, $arrayCsvFilesClear); }
public function dataPush($date = '2014-12-14 00:00:00') { $res = array(); $dstFile = "iff_data_production/test_data.json"; $fileContents = "test content"; // set up basic connection $domain = "sftp.tiger.jba-processing.com"; try { $sftp = new Net_SFTP($domain); if ($sftp->login('tiger_mccann', 'fsJcBsuepHMVrYrY')) { $sftp->put($dstFile, $fileContents); var_dump($sftp->size($dstFile)); var_dump($sftp->size('nonexistant.json')); } } catch (Exception $e) { var_dump($e); } echo $sftp->getSFTPLog(); return; }
function get_ftp_backup($args, $current_file_num = 0) { extract($args); 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)); $temp = wp_tempnam('iwp_temp_backup.zip'); $get = $sftp->get(basename($backup_file), $temp); if ($get === false) { return false; } else { return $temp; } //SFTP library has automatic connection closed. So no need to call seperate connection close function } } else { //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder $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 === false) { return false; } } } $login = @ftp_login($conn_id, $ftp_username, $ftp_password); if ($login === false) { return false; } if ($ftp_site_folder) { $ftp_remote_folder .= '/' . $this->site_name; } if ($ftp_passive) { @ftp_pasv($conn_id, true); } //$temp = ABSPATH . 'iwp_temp_backup.zip'; $temp = wp_tempnam('iwp_temp_backup.zip'); $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY); if ($get === false) { return false; } else { } ftp_close($conn_id); return $temp; } }
private function downloadJob($result, $silverpop, $type, $listId = array()) { if (empty($result['JOB_ID'])) { $this->logMessage("WARNING: Last job was not successfully created. Check the source in Silverpop."); return; } $file = str_replace('/download/', '', $result['FILE_PATH']); // Wait till its done $counter = 0; do { sleep(2); $status = $silverpop->getJobStatus($result['JOB_ID']); $counter++; } while (!in_array($status['JOB_STATUS'], array('COMPLETE', 'CANCELLED', 'ERROR')) && $counter < 3600); // Check if everything happend OK if ($status['JOB_STATUS'] != 'COMPLETE') { throw new SilverpopException('An error occured while creating report in Silverpop. Last job status: ' . $status['JOB_STATUS'] . '. Last job status response: ' . json_encode($status)); } $this->logMessage('Job finished for ID ' . $result['JOB_ID']); // ================== Download data from SFTP ================== $sftp = new Net_SFTP('transfer' . $this->config['engage_server'] . '.silverpop.com'); if (!$sftp->login($this->config['username'], $this->config['#password'])) { exit('Login Failed'); } $sftp->get("{$this->remoteDir}{$file}", $this->localDir . $file); if ($type == 'contact_lists') { $this->loadFile($this->localDir . $file, $this->config['bucket'], $type, false, array('LIST_NAME', 'LIST_ID'), $listId); } else { if ($type == 'events') { $this->extractAndLoad($this->localDir . $file, $this->config['bucket'], array('Raw Recipient Data Export' => 'events'), array('LIST_NAME', 'LIST_ID'), $listId); } else { $this->extractAndLoad($this->localDir . $file, $this->config['bucket']); } } $this->logMessage('Data downloaded for job ' . $result['JOB_ID']); }
/** * This method is called immediately after the wrapper is initialized * * Connects to an SFTP server * * NOTE: This method is not get called by default for the following functions: * dir_opendir(), mkdir(), rename(), rmdir(), stream_metadata(), unlink() and url_stat() * So I implemented a call to stream_open() at the beginning of the functions and stream_close() at the end * * The wrapper will also reuse open connections * * @param String $path * @param String $mode * @param Integer $options * @param String &$opened_path * @return bool * @access public */ public function stream_open($path, $mode, $options, &$opened_path) { $url = parse_url($path); $host = $url["host"]; $port = $url["port"]; $user = $url["user"]; $pass = $url["pass"]; $this->path = $url["path"]; $connection_uuid = md5($host . $port . $user); // Generate a unique ID for the current connection if (isset(self::$instances[$connection_uuid])) { // Get previously established connection $this->sftp = self::$instances[$connection_uuid]; } else { //$context = stream_context_get_options($this->context); if (!isset($user) || !isset($pass)) { return FALSE; } // Connection $sftp = new Net_SFTP($host, isset($port) ? $port : 22); if (!$sftp->login($user, $pass)) { return FALSE; } // Store connection instance self::$instances[$connection_uuid] = $sftp; // Get current connection $this->sftp = $sftp; } $filesize = $this->sftp->size($this->path); if (isset($mode)) { $this->mode = preg_replace('#[bt]$#', '', $mode); } else { $this->mode = 'r'; } switch ($this->mode[0]) { case 'r': $this->position = 0; break; case 'w': $this->position = 0; if ($filesize === FALSE) { $this->sftp->touch($this->path); } else { $this->sftp->truncate($this->path, 0); } break; case 'a': if ($filesize === FALSE) { $this->position = 0; $this->sftp->touch($this->path); } else { $this->position = $filesize; } break; case 'c': $this->position = 0; if ($filesize === FALSE) { $this->sftp->touch($this->path); } break; default: return FALSE; } if ($options == STREAM_USE_PATH) { $opened_path = $this->sftp->pwd(); } return TRUE; }
/** * 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 ''; }
$remoteSolutionsFile = "/code/spopt-stable/tests/" . $session . "/input.txt.solutions"; $remoteDiscardedFile = "/code/spopt-stable/tests/" . $session . "/input.txt.discarded"; //ssh2 and sftp used to remotely connect set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib'); include 'Net/SSH2.php'; include 'Net/SFTP.php'; //ssh connect to cr2g server $ssh = new Net_SSH2('cr2g01.cs.utep.edu', 22); if (!$ssh->login('rlgruver', 'utep$2015')) { exit('ssh Login Failed'); } //attempted to set an ssh timeout, not allowed on UTEP server $ssh->setTimeout(7200); //sftp connect to cr2g server $sftp = new Net_SFTP('cr2g01.cs.utep.edu', 22); if (!$sftp->login('rlgruver', 'utep$2015')) { exit('sftp Login Failed'); } //send input file to cr2g server $sftp->mkdir('/code/spopt-stable/tests/' . $session); $sftp->put($remoteInputFile, $localInputFile, NET_SFTP_LOCAL_FILE); $sftp->chmod(0777, $remoteInputFile); //execute python script in this order to run the Solver: //1. change to directory where solver script is located $ssh->write("cd /code/spopt-stable\n"); //2. 'read' command to ensure script is called from the proper directory $ssh->read('rlgruver@cr2g01:/code/spopt-stable$'); //3. run the solver script with the test from the current session $ssh->write("python SpOpt.py tests/" . $session . "/input.txt\n"); //start timerin case anything gets stuck, will break within 120 minutes (7200 sec) $starttime = time();
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. }
<?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;
/** * Transmit HL7 for the specified lab. * * @param integer $ppid Procedure provider ID. * @param string $out The HL7 text to be sent. * @return string Error text, or empty if no errors. */ function send_hl7_order($ppid, $out) { global $srcdir; $d0 = "\r"; $pprow = sqlQuery("SELECT * FROM procedure_providers " . "WHERE ppid = ?", array($ppid)); if (empty($pprow)) { return xl('Procedure provider') . " {$ppid} " . xl('not found'); } $protocol = $pprow['protocol']; $remote_host = $pprow['remote_host']; // Extract MSH-10 which is the message control ID. $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0))); $msgid = $segmsh[9]; if (empty($msgid)) { return xl('Internal error: Cannot find MSH-10'); } if ($protocol == 'DL' || $pprow['orders_path'] === '') { header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Disposition: attachment; filename=order_{$msgid}.hl7"); header("Content-Description: File Transfer"); echo $out; exit; } else { 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/file name. $filename = $msgid . '.txt'; if ($pprow['orders_path']) { $filename = $pprow['orders_path'] . '/' . $filename; } // Connect to the server and write the file. $sftp = new Net_SFTP($remote_host); if (!$sftp->login($pprow['login'], $pprow['password'])) { return xl('Login to this remote host failed') . ": '{$remote_host}'"; } if (!$sftp->put($filename, $out)) { return xl('Creating this file on remote host failed') . ": '{$filename}'"; } } else { if ($protocol == 'FS') { // Compute the target path/file name. $filename = $msgid . '.txt'; if ($pprow['orders_path']) { $filename = $pprow['orders_path'] . '/' . $filename; } $fh = fopen("{$filename}", 'w'); if ($fh) { fwrite($fh, $out); fclose($fh); } else { return xl('Cannot create file') . ' "' . "{$filename}" . '"'; } } else { return xl('This protocol is not implemented') . ": '{$protocol}'"; } } } // Falling through to here indicates success. newEvent("proc_order_xmit", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "ID: {$msgid} Protocol: {$protocol} Host: {$remote_host}"); return ''; }
// Rights $checkGroup = checkClientGroup($server['groupid'], $_SESSION['clientid']); if ($checkGroup == FALSE) { $_SESSION['msg1'] = T_('Error!'); $_SESSION['msg2'] = T_('This is not your server!'); $_SESSION['msg-type'] = 'error'; header('Location: index.php'); die; } ### $aes = new Crypt_AES(); $aes->setKeyLength(256); $aes->setKey(CRYPT_KEY); // Get SFTP $sftp = new Net_SFTP($box['ip'], $box['sshport']); if (!$sftp->login($box['login'], $aes->decrypt($box['password']))) { $_SESSION['msg1'] = T_('Connection Error!'); $_SESSION['msg2'] = ''; $_SESSION['msg-type'] = 'error'; header("Location: server.php?id=" . urlencode($serverid)); die; } $log = $sftp->get(dirname($server['path']) . '/screenlog.0'); $sftp->disconnect(); //Adding event to the database $message = mysql_real_escape_string($server['name']) . ' : screenlog downloaded'; query_basic("INSERT INTO `" . DBPREFIX . "log` SET `serverid` = '" . $serverid . "', `message` = '" . $message . "', `name` = '" . $_SESSION['clientfirstname'] . " " . $_SESSION['clientlastname'] . "', `ip` = '" . $_SERVER['REMOTE_ADDR'] . "'"); ### header('Content-type: text/plain'); header('Content-Disposition: attachment; filename="' . $server['screen'] . '_' . date('Y-m-d') . '.screenlog"'); echo $log;
public function connect() { $this->ftp = new Net_SFTP($this->getHost(), $this->getPort()); if (!$this->ftp->login($this->options['user'], $this->options['pass'])) { return false; } return true; }
function tsdns($action, $sship, $sshport, $sshuser, $keyuse, $sshkey, $sshpw, $notified, $path, $bitversion, $tsip, $tsport, $tsdns, $reseller_id, $maxnotified = 2) { global $sql; $sshSftpObject = new Net_SFTP($sship, $sshport); if ($keyuse != 'N') { $privateKey = EASYWIDIR . '/keys/' . removePub($sshkey); $sshpw = new Crypt_RSA(); if ($keyuse == 'B') { $sshpw->setPassword($sshpw); } $keyContent = @file_get_contents($privateKey); if ($keyContent) { $sshpw->loadKey($keyContent); } } if ($sshSftpObject->login($sshuser, $sshpw)) { $split_config = preg_split('/\\//', $path, -1, PREG_SPLIT_NO_EMPTY); $folderfilecount = count($split_config) - 1; $i = 0; $folders = substr($path, 0, 1) == '/' ? '/' : ''; $lastFolder = ''; while ($i <= $folderfilecount) { $folders .= $split_config[$i] . '/'; $lastFolder = $split_config[$i]; $i++; } if ($lastFolder != 'tsdns' or substr($path, 0, 1) != '/') { $folders .= 'tsdns/'; } if ($action == 'md' or $action == 'dl') { $newip = $tsip[0]; $oldip = isset($tsip[1]) ? $tsip[1] : ''; $newport = $tsport[0]; $oldport = isset($tsport[1]) ? $tsport[1] : ''; $newdns = $tsdns[0]; $olddns = isset($tsdns[1]) ? $tsdns[1] : ''; } else { $dnsarray = array(); } $file = substr($path, 0, 1) == '/' ? $folders . 'tsdns_settings.ini' : '/home/' . $sshuser . '/' . $folders . 'tsdns_settings.ini'; if ($action != 'rs') { $data = $sshSftpObject->get($file); $data = str_replace(array("", "\\b", "\r", "\\Z"), '', $data); } if ($action != 'rs' and $action != 'mw') { $edited = false; $ca = array(); foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) { if ($action != 'li' and $configLine != $olddns . '=' . $oldip . ':' . $oldport and $configLine != $newdns . '=' . $newip . ':' . $newport) { $ca[] = $configLine . "\r\n"; } else { if ($action == 'md' and $edited == false and ($configLine == $olddns . '=' . $oldip . ':' . $oldport or $configLine == $newdns . '=' . $newip . ':' . $newport)) { $edited = true; $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n"; } } if ($action == 'li' and $configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) { $dnsconfig = explode('=', $configLine); if (isset($dnsconfig[1])) { $linedns = $dnsconfig[0]; $lineserver = $dnsconfig[1]; $dnsarray[$lineserver] = $linedns; } } } if ($action == 'md' and $edited == false) { $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n"; } if ($action != 'li') { $ca = array_unique($ca); sort($ca); $newcfg = ''; foreach ($ca as $line) { $newcfg .= $line; } if ($newcfg == '') { $newcfg = '# No TSDNS data entered'; } $sshSftpObject->put($file, $newcfg); } } if ($action == 'mw' and isset($data)) { $usedIPs = array(); foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) { if ($configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) { $splittedLine = preg_split('/\\=/', $configLine, -1, PREG_SPLIT_NO_EMPTY); $usedIPs[] = isset($splittedLine[1]) ? array('dns' => $splittedLine[0], 'address' => $splittedLine[1]) : $configLine; } else { $usedIPs[] = $configLine; } } foreach ($tsip as $newLine) { $splittedLine = preg_split('/\\=/', strtolower($newLine), -1, PREG_SPLIT_NO_EMPTY); if (isset($splittedLine[1]) and !array_key_exists($splittedLine[1], $usedIPs)) { $usedIPs[] = array('dns' => $splittedLine[0], 'address' => $splittedLine[1]); } } function array_multi_dimensional_unique($multi) { $unique = array(); foreach ($multi as $sub) { if (!in_array($sub, $unique)) { $unique[] = $sub; } } return $unique; } $newCfg = ''; $usedIPs = array_multi_dimensional_unique($usedIPs); sort($usedIPs); foreach ($usedIPs as $value) { $newCfg .= (isset($value['dns']) and isset($value['address']) and !preg_match('/^#(|\\s+)(.*)$/', $value['dns'])) ? $value['dns'] . '=' . $value['address'] . "\r\n" : $value . "\r\n"; } if ($newCfg == '') { $bad = 'Nothing to write'; } else { $sshSftpObject->put($file, $newCfg); } } if (!isset($bad) and $action != 'li') { $sshObject = new Net_SSH2($sship, $sshport); if ($sshObject->error === false) { if ($sshObject->login($sshuser, $sshpw)) { $bin = $bitversion == 32 ? 'tsdnsserver_linux_x86' : 'tsdnsserver_linux_amd64'; $ssh2cmd = 'cd ' . $folders . ' && function restart () { if [ "`ps fx | grep ' . $bin . ' | grep -v grep`" == "" ]; then ./' . $bin . ' > /dev/null & else ./' . $bin . ' --update > /dev/null & fi }; restart& '; $sshObject->exec($ssh2cmd); if ($notified > 0) { $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=0 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1"); $query->execute(array($sship, $reseller_id)); } } else { $bad = 'The login data does not work'; $notified++; } } else { $bad = 'Could not connect to Server'; $notified++; } } } else { $bad = 'Could not connect to Server'; } if (isset($bad) and $notified == $maxnotified) { if ($reseller_id == 0) { $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE `resellerid`=0 AND `accounttype`='a'"); $query->execute(); } else { $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE (`id`=? AND `id`=`resellerid`) OR (`resellerid`=0 AND `accounttype`='a')"); $query->execute(array($reseller_id)); } while ($row = $query->fetch(PDO::FETCH_ASSOC)) { if ($row['mail_serverdown'] == 'Y') { sendmail('emaildown', $row['id'], 'TS3 Master ' . $sship . ' ( ' . $bad . ' )', ''); } } $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=`notified`+1 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1"); $query->execute(array($sship, $reseller_id)); return $bad; } else { if (isset($bad)) { return $bad; } else { if ($action == 'li' and isset($dnsarray)) { return $dnsarray; } } } return 'ok'; }