【问题标题】:Convert shell script to C code using wrapper [closed]使用包装器将 shell 脚本转换为 C 代码 [关闭]
【发布时间】:2015-08-08 18:06:27
【问题描述】:

我正在尝试在网络服务器中加载 .php 时执行 shell 脚本,我已经为此苦苦挣扎了一段时间,所以我会寻求帮助。

到目前为止,我尝试的是按照这篇文章中的说明制作一个包装器:Execute root commands via PHP

但我无法让包装器执行 shell 脚本,即使脚本在以 root 权限从控制台执行时也能正常工作。

所以我能找到的唯一解决方案是使用 "system ("") 将 shell 代码转换为 C 代码,就像使用 system(" ") 一样

真不知道有没有可能,以前shell脚本做的就是检查12321端口运行的进程的PID,然后kill掉。

shell脚本单独工作,所以我问是否有人知道是否可以转换为C,这是我要转换的shell脚本:

#!/bin/sh

pid=$(/bin/fuser -n tcp 12321 | /usr/bin/awk '{print $1}');
/bin/kill -9 $pid;

这是正在使用的 wrapper.c,它用于执行上面在我的机器中调用的代码 (testversion.sh),但我不知道为什么,它不起作用。

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

    int main (int argc, char *argv[]) {
        setuid (0);
        system ("/bin/bash /var/www/html/scrip/debugport/testversion.sh");
        return 0;
    }

由于这似乎不起作用,有人有办法在 C 代码中执行它吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow。请尽快阅读About 页面。请注意,您的问题可以作为“离题”合法地关闭,因为 寻求调试帮助的问题(“为什么此代码不起作用?”)必须包含所需的行为、特定问题或错误以及最短的必要代码在问题本身中重现它。没有明确问题陈述的问题对其他读者没有用处。请参阅如何创建 MCVE (How to create a Minimal, Complete, and Verifiable Example?)。
  • 请注意,由于您的main() 忽略了它的参数,您应该将其定义为int main(void)setuid(0); 只有在程序已经以 root 权限运行时才会执行任何操作;目前尚不清楚是否有必要。您忽略system() 返回的状态。您还没有解释它,但大概您使用fuserawkkill 显示的脚本是您/var/www/html/scrip/debugport/testversion.sh 文件中的脚本?并且使用scrip 而不是script 是故意的吗? shebang 是 #!/bin/bash 似乎很奇怪,但你明确地使用 /bin/sh 运行命令。
  • "因为执行 shell 脚本似乎不起作用"...不起作用怎么办?你得到什么错误?你真正想解决什么问题?你的 C 代码怎么不工作?
  • 我改进了帖子,试图明确我想要做什么。

标签: c shell ubuntu


【解决方案1】:

试试这个。除非以 root 身份运行,否则此代码只能杀死同一用户拥有的进程。

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

#define PORT_TO_LOOK_FOR  "12321"
#define DO_NOT_KILL_BELOW  2 /* I am just putting 2 here, you can increase this */

int main(void) {

  FILE *fp;
  char buf[11] = {0};
  pid_t pid;

  /* Open the command for reading. */
  fp = popen("lsof -t -i tcp:" PORT_TO_LOOK_FOR, "r");
  if (fp == NULL) {
    printf("Could not run lsof.\n");
    exit(1);
  }
  else {
    fgets(buf, sizeof(buf)-1, fp);
    pclose(fp);

    pid = (pid_t)atoi(buf);
    if( pid < 1) {
      printf("Either no one is listening on port " 
        PORT_TO_LOOK_FOR " or u don't have the "
        "necessary permission.\n" );
      exit(1);
    }
    else if( pid < DO_NOT_KILL_BELOW ) {
      printf("The PID we got was not safe to kill.\n");
      exit(1);
    }

    if( kill(pid, SIGKILL) != 0 ) {
      perror("kill");
    }
  }

  return 0;
}

【讨论】:

  • 感激不尽,这太棒了,谢谢! PD:有人帮忙而不是投反对票真是太好了……
  • 有人知道我怎么能把它转换成 C 代码? screen -S teamspeak -X stuff "stop" 我正在尝试这个:system ("/usr/bin/screen -S teamspeak -X stuff "stop ""); PD:在停止后有一个 ENTER 很重要,这样才能正常工作。
猜你喜欢
  • 2020-06-13
  • 2012-05-14
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 2020-01-18
相关资源
最近更新 更多