【问题标题】:Add new user and password to debian via SSH with PHP使用 PHP 通过 SSH 将新用户和密码添加到 debian
【发布时间】:2017-02-17 22:32:45
【问题描述】:

我无法将通过 ssh 和 php 生成的新用户的密码输入到 Debian 服务器。 要添加新用户,我只需简单地编写“useradd $username”。但是,如果我想为该用户设置密码,它应该类似于“passwd $username”,然后我应该插入密码。但是如何在 PHP 中做到这一点呢?

这是我的完整代码:

<?php
$username = "abcd";
$password = "456789";
$expired = "5";
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in at server1.example.com on port 22
if(!($con = ssh2_connect("128.199.xxx.xx", 22))){
echo "fail: unable to establish connection\n";
} else {
// try to authenticate with username root, password secretpassword
if(!ssh2_auth_password($con, "root", "xxxxxx")) {
    echo "fail: unable to authenticate\n";
} else {
    // allright, we're in!
    echo "okay: logged in...\n";

    // execute a command
    if (!($stream = ssh2_exec($con, "passwd 'haha'"))){
        echo "fail: unable to execute command\n";
    } else {
        // collect returning data from command
        stream_set_blocking($stream, true);
        $data = "";
        while ($buf = fread($stream,4096)) {
            $data .= $buf;
        }
        echo "Username berhasil dibuat";
        echo $data;
        fclose($stream);
}
}
}
?>

【问题讨论】:

    标签: php ssh debian


    【解决方案1】:

    您似乎正在寻找更改用户密码的非交互式方式。

    试试这个

    echo "username:newpass"|chpasswd

    这里是chpasswd 手册页。

    此方法也适用于大量用户更改密码。

    UPD:

    要知道当前登录的用户名whoami可以使用。

    【讨论】:

    • 对不起,我还是不明白,我可以把我的代码改成这样吗:'if (!($st​​ream = ssh2_exec($con, '"username:newpass"|chpasswd')) ){' @保罗
    • 您需要替换当前活动的用户名来实现您想要的。为此,您可以使用我添加到答案中的whoami。首先,您阅读当前用户名,而不是将其替换为 : 之前,然后将您的新密码作为纯文本而不是 newpass
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 2012-02-23
    • 2019-11-16
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多