php - 使用 PHP 动态更改 arduino yun 上的 httpd SSH 端口

标签 php linux ssh arduino

我已使用终端成功更改了/etc/config/uhttpd 文件中的 SSH 端口。但我似乎无法找到一种从 PHP 动态执行此操作的方法。解释一下,我需要我的服务器自动设置Yun上linux系统的端口。所以基本上我需要它来自动更改 uhttpd 文件中的端口号。提前致谢。

最佳答案

Setup SSH keys用于无密码访问远程服务器。

如果用户不是root,请通过sudo命令配置远程/etc/sudoers以进行无密码命令执行。例如,您可以将远程用户添加到 uhttpd 组(远程):

sudo gpasswd -a user uhttpd

然后列出允许在没有密码的情况下运行的命令

%uhttpd ALL=(ALL) NOPASSWD: ALL

为了简单起见,我们允许ALL命令。您可以改为列出特定命令。请参阅man sudoers

编写类似于以下内容的脚本:

#!/usr/bin/env php
<?php
namespace Tools\Uhttpd\ChangePort;

$ssh_user = 'user'; // Change this
$ssh_host = 'remote.host'; // Change this
$remote_config = '/etc/config/uhttpd';

//////////////////////////////////////////////////////

if (false === ($o = getopt('p:', ['port:']))) {
  fprintf(STDERR, "Failed to parse CLI options\n");
  exit(1);
}

// Using PHP7 Null coalescing operator
$port = $o['p'] ?? $o['port'] ?? 0;
$port = intval($port);
if ($port <= 0 || $port > 65535) {
  fprintf(STDERR, "Invalid port\n");
  exit(1);
}

$sudo = $ssh_user == 'root' ? '' : 'sudo';

$sed = <<<EOS
"s/option\s*'listen_http'\s*'[0-9]+'/option 'listen_http' '$port'/"
EOS;

// Replace port in remote config file
execute(sprintf("ssh %s -- $sudo sed -i -r %s %s",
  "{$ssh_user}@{$ssh_host}", $sed,
  escapeshellarg($remote_config)));

// Restart remote daemon
execute("$sudo /etc/init.d/uhttpd restart");

//////////////////////////////////////////////////////

/**
 * @param string $cmd Command
 * @return int Commands exit code
 */
function execute($cmd) {
  echo ">> Running $cmd\n";

  $desc = [
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
  ];

  $proc = proc_open($cmd, $desc, $pipes);
  if (! is_resource($proc)) {
    fprintf(STDERR, "Failed to open process for cmd: $cmd\n");
    exit(1);
  }

  if ($output = stream_get_contents($pipes[1])) {
    echo $output, PHP_EOL;
  }

  if ($error = stream_get_contents($pipes[2])) {
    fprintf(STDERR, "Error: %s\n", $error);
  }

  fclose($pipes[1]);
  fclose($pipes[2]);

  if (0 != proc_close($proc)) {
    fprintf(STDERR, "Command failed(%d): %s\n", $exit_code, $cmd);
    exit(1);
  }
}

将其保存到chport.php并使其可执行:

chmod +x chport.php

然后你可以像这样使用它:

./chport.php --port=10000

您可能希望将脚本中使用的命令包装在 shell 脚本中,然后将它们列在 /etc/sudoers 中。

关于php - 使用 PHP 动态更改 arduino yun 上的 httpd SSH 端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37017603/

相关文章:

php - 处理 900,000 条记录数据库和邮政编码的最佳方法?

linux - 在 Linux RHEL 6 上的重启后坚持 ifconfig lo 多播

node.js - 尝试在 MariaDB shell 中重置 Root 密码时出现语法错误

ssh - 如何在从 VS 代码 ssh-ing 时以 root 用户身份从远程服务器编辑文件?

php - 多维数组到 MySQL

php - Wordpress PHP警告: A non-numeric value encountered

linux - 如何将 ctrl+d 插入到我的 linux 脚本中?

ssh - 为什么即使端点出现故障,转发的 SSH 端口似乎仍然打开?

尝试在远程桌面上运行应用程序时出现 Python 错误

php - 是否可以加载外部页面?