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=
延伸文章資訊
- 1How can I call a shell command in my Perl script?
How to run a shell script from a Perl program. 1. Using system system($command, @arguments);. For...
- 2How 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...
- 3Run bash script in Perl program - BOL
Run bash script in Perl program ! · 2. exec””. syntax: exec "command"; · 3. Backticks “ or qx//. ...
- 4Executing Commands Without Shell Escapes (Perl Cookbook ...
Because Perl was designed as a glue language, it's easy to use it to call other programs—too easy...
- 5An Easy Way to Access the OS System Command from Perl
Perl programs run on many different platforms such as Windows, Mac OS and the various UNIX ... Pe...