【问题标题】:Using sed to replace line in perl使用 sed 替换 perl 中的行
【发布时间】:2013-06-25 16:40:28
【问题描述】:

我想在 etter.conf 文件中取消注释第 168 行。该命令在终端中运行正常,但在 perl 中尝试时出现错误。

system ("sed -i '168s/.*/redir_command_on = "iptables -t nat -A PREROUTING -i %iface -p tcp --dport %port -j REDIRECT --to-port %rport"/' /etc/etter.conf");

错误是:

Bareword found where operator expected at ./attack.pl line 135, near 
""sed -i '168s'/.*'/redir_command_on = "iptables"

我认为这与特殊字符和转义有关。

【问题讨论】:

  • 您需要转义嵌套引号。 Perl 认为 iptables 应该是可变的。
  • 命令中的双引号终止了 perl 字符串。
  • 您向sed 发起攻击有什么原因吗? Perl 完全能够自行更新文件。
  • 您甚至可以在 Perl 中进行“就地”编辑,完全没有必要使用 sed。

标签: perl sed system


【解决方案1】:

所以 Perl 正在解析,它找到一个字符串文字

system ("sed -i '168s/.*/redir_command_on = "
        ^                                   ^
        |                                   |
        +-----------------------------------+

接下来应该是) 或运算符,但它是iptables。你没有正确地形成你的字符串文字。切换分隔符可以解决问题:

system(q{sed -i '168s/.*/redir_command_on = "..."/' /etc/etter.conf})

q{...}'...' 相同。)

顺便说一句,system 使用“列表形式”会更好,因为它可以避免不必要地启动和使用 shell,

system('sed', '-i', '168s/.*/redir_command_on = "..."/', '/etc/etter.conf')

【讨论】:

  • 不错,还可以将system(q{...替换为system(qw{...,自动获取列表形式。
  • @steabert,不。你会得到一个列表,但它不是正确的命令。
  • 啊,因为有空格?
  • @steabert,是的。 qw 在空白处拆分。它对 shell 字面量一无所知。
【解决方案2】:

您不能在双引号字符串中嵌套裸双引号。 Perl 有更多的quoting operators 你可以使用。

# Instead of
system ("sed -i '168s/.*/redir_command_on = "iptables -t nat -A PREROUTING -i %iface -p tcp --dport %port -j REDIRECT --to-port %rport"/' /etc/etter.conf");

# use
system (q{sed -i '168s/.*/redir_command_on = "iptables -t nat -A PREROUTING -i %iface -p tcp --dport %port -j REDIRECT --to-port %rport"/' /etc/etter.conf});
#-------^^------------------------------------------------------------------------------------------------------------------------------------------------^

【讨论】:

    猜你喜欢
    • 2017-06-16
    • 2014-01-24
    • 2020-11-22
    • 2015-11-18
    • 2019-07-03
    • 2011-03-22
    • 2022-01-19
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多