Executing Commands Without Shell Escapes (Perl Cookbook ...
文章推薦指數: 80 %
Because Perl was designed as a glue language, it's easy to use it to call other programs—too easy, in some cases. If you're merely trying to run a shell command ...
home|
O'Reilly'sCDbookshelfs|
FreeBSD|
Linux|
Cisco|
CiscoExam
19.5.ExecutingCommandsWithoutShellEscapes
19.5.1.Problem
Youneedtousea
user'sinputaspartofacommand,butyoudon'twanttoallowthe
usertotricktheshellintorunningothercommandsorlookingat
otherfiles.Ifyoujustblindlycallthesystem
functionorbackticksonasinglestringcontainingacommandline
derivedfromuntesteduserinput,theshellmightbeusedtorunthe
command.Thiswouldbeunsafe.
19.5.2.Solution
Unlikeitssingle-argumentversion,thelistformofthe
systemfunctionissafefromshellescapes.When
thecommand'sargumentsinvolveuserinputfromaform,neveruse
this:
system("command$input@files");#UNSAFE
Writeitthiswayinstead:
system("command",$input,@files);#safer
19.5.3.Discussion
BecausePerlwasdesignedasagluelanguage,it'seasytouseitto
callotherprograms—tooeasy,insomecases.
Ifyou'remerelytryingtorunashellcommandbutdon'tneedto
captureitsoutput,it'seasyenoughtocall
systemusingitsmultipleargumentform.Butwhat
happensifyou'reusingthecommandinbackticksoraspartofa
pipedopen?Nowyouhavearealproblem,becausethosedon'tpermit
themultipleargumentformthatsystemdoes.The
solution(priortov5.8;seelaterinthisDiscussion)istomanually
forkandexecthechild
processesonyourown.It'smorework,butatleaststrayshell
escapeswon'tberuiningyour
day.
It'ssafetousebackticksinaCGIscriptonlyiftheargumentsyou
givetheprogramareinternallygenerated,asin:
chomp($now=`date`);
Butifthecommandwithinthebacktickscontainsuser-suppliedinput,
perhapslikethis:
@output=`grep$input@files`;
youhavetobemuchmorecareful.
die"cannotfork:$!"unlessdefined($pid=open(SAFE_KID,"-|"));
if($pid==0){
exec('grep',$input,@files)ordie"can'texecgrep:$!";
}else{
@output=
延伸文章資訊
- 1Running external programs from Perl with system
Shell expansion. Let's say you have a program called checkfiles that can check the files listed o...
- 2Recipe 19.6. Executing Commands Without Shell Escapes
You need to use a user's input as part of a command, but you don't want to allow the user to make...
- 3How to execute Unix/shell commands in a Perl script?
How to execute Unix/shell commands in a Perl script? · 1. exec”” · 2. system() · 3. Backticks “ o...
- 4How to call a shell command in our Perl script - Educative.io
There are two ways to call a shell command from the Perl script. Syntax. We use the backticks ( `...
- 5How to execute shell command in a perl script? - 博客园
https://stackoverflow.com/questions/3200801/how-can-i-call-a-shell-command-in-my-perl-script/2115...