简体   繁体   中英

Allow the use of SUDO when connecting to ssh through Net_SSH2

I have a problem doing Sudo command through SSH when connecting from php, but not connection from regular terminal

if i'm connecting on SSH to an AWS machine with Net_SSH2

            $ssh = new Net_SSH2($instanceIp);
            if ( ! $ssh->login('ec2-user', $key)) {
                $logger->error('Login Failed');
            }

I'll get this error: sudo: sorry, you must have a tty to run sudo

If I'm connecting directly from terminal ssh -i ~/Path/to-file-key.pem ec2-user@111.111.11.111 So I can run any sudo command without problems.

I don't want to remove from /etc/sudoers (I don't want to have something to do on the server, I want it to be done by the connection)

Defaults    requiretty

Is there a way to do it without that ?

Thanks for your help

If i may quote this article,

Red Hat systems (RHEL, Fedora...) have been known to require a TTY in default sudoers file. That provides no real security benefit and can be safely removed.

Red Hat have acknowledged the problem and it will be removed in future releases.

Therefore, it's safe to remove the "requiretty", that way you won't have a problem to execute sudo commands via SSH.

You may also try running ssh with the -t option(the repercussions of which you can find in the aforementioned article), it forces pseudo-tty allocation, so it might work. I don't know if there's a way to add that option to Net_SSH, but it should be OpenSSH based, so normally, you should. Worst case scenario, you can allways run the ssh command via exec, but removing require tty seems to be the best option.

The phpseclib docs give an example of how to use sudo:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->read('username@username:~$');
$ssh->write("sudo ls -la\n");
$output = $ssh->read('#[pP]assword[^:]*:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#[pP]assword[^:]*:#', $output)) {
    $ssh->write("password\n");
    echo $ssh->read('username@username:~$');
}

http://phpseclib.sourceforge.net/ssh/examples.html#sudo

If you want to try to do it with $ssh->exec (it's not clear what you're doing since you didn't provide the full code in your post) you can do sudo visudo and then add an entry for the username / script that you're wanting to run. eg.

username ALL=(ALL) NOPASSWD: /path/to/script

Alternatively, you could do this:

echo "PASSWORD" | sudo -S /path/to/script

For more information google "sudo in a bash script"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM