2011-05-07 82 views
2

这是否足以安全地防止未定义的变量进入我的脚本?正则表达式安全

# Find the name of the VMXF file 
$getfilelayout =~ /^ \s+ " (?<vmxf_file> .+\.vmxf) " /xm; 

if ("$+{vmxf_file}" eq '') { 
    $vmxf_file = 'undef'; 
} else { 
    $vmxf_file = "$+{vmxf_file}"; 
    $vmxf_file = $ssh_obj->capture("find -name $vmxf_file"); 
} 

如果不是,我还能做什么?

+1

@mu太短,这似乎是访问名为反向引用[Perlretut#命名的反向引用(http://perldoc.perl.org/perlretut.html#Named-backreferences) – stema 2011-05-07 20:35:10

+0

你不应该的方式假设匹配成功了,所以把它放在'if'中。此外,您不必引用您的命名捕获:'$ + {vmxf_file}'检索它就好了。 – tchrist 2011-05-07 23:04:37

+0

@ tchrist,我不必引用捕获?凉。我原本在if语句里面有过匹配,但似乎没有必要,但现在看着你的输入,我可以看到为什么会更好。 – ianc1215 2011-05-08 03:20:35

回答

4

你不应该假定匹配成功,所以把它放在if。此外,你不必引用你的命名捕获:$+{vmxf_file}检索它就好了。在这里,我假定文件名没有空格或引号的:

use 5.010; 

if ($getfilelayout =~ /^ \h+ " (?<vmxf_file> ["\s]+ \.vmxf) " /xm) { 
    $captcha = $+{vmxf_file}; 
    $found = $ssh_obj->capture("find -name $captcha"); 
} 

“安全”问题是,你不知道什么样的metachars都在拍摄。正确的方法是使用更多的东西

system("find", "-name", $captcha); 

但这不会捕获您的输出。我不认为SSH协议允许安全的炮击,但我不知道。你在用什么课?

+0

whats'h +'做什么?还没有见过那个。 – ianc1215 2011-05-08 03:16:34

+0

我必须使用SSH,因为正在匹配的数据不会驻留在我的网络上的VMware服务器上的本地主机上。 – ianc1215 2011-05-08 03:17:37

+0

他可能使用Net :: OpenSSH支持“安全炮击” – salva 2011-05-09 08:26:44

1
# An undefined variable might not be your only worry!?! 
my $getfilelayout = q{ " '*' | xargs rm ; echo .vmxf" }; 

# A regex in list context returns the captures. 
# IMHO, this seems cleaner than what you've got. 
my ($vmxf_file) = $getfilelayout =~ /^\s+ "(.+\.vmxf)"/xm; 

# Proceed accordingly. 
if (defined $vmxf_file){ 
    ... 
} 
+0

Oo我喜欢这样,所以变量只在匹配成功时才被定义。 – ianc1215 2011-05-08 03:15:12