Run Shell Command
Last modified by Raphaël Jakse on 2026/06/02 17:55
| Allows users with programming permission to run a command on the bash shell on the server |
| Type | Snippet |
| Category | |
| Developed by | xwiki:XWiki.cjdelisle |
| Rating | |
| License | GNU Lesser General Public License 2.1 |
Table of contents
Description
Security: None (no protection against cross site request forgery, this should be removed after use.)
{{groovy}}
if (xwiki.hasAccessLevel("programming", xcontext.getUser(), "XWiki.XWikiPreferences")) {
String shellcmd = request.getParameter("command");
println("{{html}}<form action='' method='POST'><input type='text' name='command' size=50 />");
println("<input type='submit' value='Run' /></form>{{/html}}\n\n")
if (shellcmd != null ) {
String[] cmd = ["sh", "-c", shellcmd];
stdout = new java.io.BufferedReader(
new java.io.InputStreamReader(Runtime.getRuntime().exec(cmd).getInputStream()));
println("{{code language=none}}")
while ((s = stdout.readLine()) != null) {
println(s);
}
println("{{/code}}")
}
}
{{/groovy}}Version that saves the stdout in an attachment in a sub page (for larger outputs):
{{groovy}}
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiAttachmentContent
def addAttachment(name, is, document)
{
XWikiAttachment a = new XWikiAttachment(document.getDocument(), name);
XWikiAttachmentContent content = new XWikiAttachmentContent(a);
content.setContent(is)
a.setAttachment_content(content);
document.getDocument().setAttachment(a);
}
if (xwiki.hasAccessLevel("programming", xcontext.getUser(), "XWiki.XWikiPreferences")) {
String shellcmd = request.getParameter("command");
println("{{html}}<form action='' method='POST'><input type='text' name='command' size=50 />");
println("<input type='submit' value='Run' /></form>{{/html}}\n\n")
if (shellcmd != null ) {
String[] cmd = ["sh", "-c", shellcmd];
def r = xwiki.getDocument("RunShell.ShellResult");
addAttachment("stdout", (Runtime.getRuntime().exec(cmd).getInputStream()), r);
r.save()
}
}
{{/groovy}}