Linux Command Doesn't work from .NET execution

2019-06-14 01:57发布

问题:

I'm trying to run a very simple command in Linux via .NET using the SharpSsh .NET library. The code doesn't throw any exceptions, and it's still not working. When I run the sudo php /www/data/{directory}/scripts/create_file.php command from the terminal it creates the file. And when I run the sudo php /www/data/{directory}/scripts/delete_file.php command from the terminal, it deletes the file. When calling this code from .NET, I don't see the file being created/deleted.

See this answer for setup:
SharpSSH .NET Library: unable to connect to Linux (Debian) from .NET

create_file.php:

<?php
$handle = fopen( 'test.txt', 'w' );
fwrite( $handle, 'Test Contents' );
fclose( $handle );

delete_file.php:

<?php
if( file_exists( 'test.txt' ) )
        unlink( 'test.txt' );

.NET code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tamir.SharpSsh;

namespace Testing
{
    public class Unix
    {
        public static void CreateFile()
        {
            SshExec ssh = new SshExec(Constants.LINUX_HOST, Constants.LINUX_USER, Constants.LINUX_PASSWORD);
            ssh.Connect();
            String result = ssh.RunCommand("sudo php " + Constants.PHP_SCRIPTS_DIR + "create_file.php");
        }

        public static void DeleteFile()
        {
            SshExec ssh = new SshExec(Constants.LINUX_HOST, Constants.LINUX_USER, Constants.LINUX_PASSWORD);
            ssh.Connect();
            String result = ssh.RunCommand("sudo php " + Constants.PHP_SCRIPTS_DIR + "delete_file.php");
        }
    }
}

回答1:

I assume that these toy php files are a reduced case of something larger.

If you need to actually create and delete a file, don't use php - you can just use a shell command directly.

If you want ot turn off the password prompt, there's syntax in the /etc/sudoers file for that - see "NOPASSWD" here.

PHP should not be run as root, especially with variables in the command line like that. If you're having permissions issues -- solve them! PHP should be run as a user with least privilege.

If you need a 'maintenance' account to ssh in and don't want to make the php user have extra capability, make it another user that shares a group with the php user - and you can use group permissions. (You may need to fiddle with the default permissions on file create.)