Search code examples
phpfilesshrm

How to delete a remote file using ssh?


I am working on a project where we are using 2 VM's one is used as local and can be accessible and from this local VM, we need to access the remote VM. While working on this I am struck on a problem.There is a file in the remote in a directory.Every time a script gets executed the file gets loaded with new data and but I don't need that.I want the file to be deleted everytime before my script executed.

I have given the code below.

if($ssh = ssh2_connect('192.168.150.85', 22)) {
     if(ssh2_auth_password($ssh, 'someUserName', 'somePassword')) {
         $stream = ssh2_exec($ssh, "python file_scanner.py /home/nsadmin/$file_name");
         $stream = ssh2_exec($ssh, 'rm /home/nsadmin/file_scanned');
         stream_set_blocking($stream, true);
         $data = '';
         while($buffer = fread($stream, 4096)) {
             $data .= $buffer;
         }
         fclose($stream);
         echo $data; // user
     }
 }

Here we can see that after ssh connection,Iam ecxecuting some script and the result of this file gets appended in the file file_scanned.But when ever I execute the ssh connection I previous results are also coming.So I did $stream = ssh2_exec($ssh, 'rm /home/nsadmin/file_scanned'); . But it is not working.

Any suggestions on how to change or modify my script so I can remove the file after execution of previous command.


Solution

  • There may be issue with permission I can say,

    But this is solution you can give a try.

    $connection = ssh2_connect('shell.example.com', 22);
    ssh2_auth_password($connection, 'username', 'password');
    $sftp = ssh2_sftp($connection);
    $stream = ssh2_sftp_unlink($sftp, '/home/nsadmin/file_scanned');
    

    This is frequent thing, which we used for removing remote files.