Linux Command Doesn't work from .NET execution when using SharpSSH library

倾然丶 夕夏残阳落幕 提交于 2020-01-03 05:07:20

问题


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.)



来源:https://stackoverflow.com/questions/9672698/linux-command-doesnt-work-from-net-execution-when-using-sharpssh-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!