简体   繁体   English

在python脚本中perl one liner

[英]perl one liner inside python script

I have a perl one liner that appends a string at the end of a particular line and it works when I run the one liner on the host. 我有一个perl one衬里,在特定行的末尾添加一个字符串,当我在主机上运行一个衬里时它就可以工作。 For instance, I'm looking to append 'boy857sr xxxxxxx' at the end of a line that starts with 'AllowUsers' 例如,我希望在以'AllowUsers'开头的行末尾添加'boy857sr xxxxxxx'

perl -pi.bak -e 's/^(AllowUsers.*)/\1 boy857sr xxxxxxx/g;' /etc/ssh/sshd_config

Works perfectly! 完美的工作!

AllowUsers boy857bt soladmin svc-Orion_SAM solarw boy857lj boy806nk boy806sk   boy857sr xxxxxxx

But when I run it inside a python script, it wipes out the 'AllowUsers' line and add another line, look below: 但是当我在python脚本中运行它时,它会清除'AllowUsers'行并添加另一行,如下所示:

#RSAAuthentication yes
^A kn857sr xxxxxxx

Here is the python script. 这是python脚本。

import pxssh

my_list=[
"server121"
]


for i in my_list:
    s = pxssh.pxssh(timeout=15, maxread=2000000)
    s.SSH_OPTS += "-o StrictHostKeyChecking=no"
    s.SSH_OPTS += "-o UserKnownHostsFile=/dev/null"
    s.login(i,'username','password')
    print (i)

    s.sendline('/usr/local/bin/sudo su -')
    s.expect('Password: ')
    s.sendline('xxxxxxx')

    s.prompt()
    print s.before
    s.sendline('perl -pi.bak -e \'s/^(AllowUsers.*)/\1 boy857sr xxxxxxx/g;\' 
/etc/ssh/sshd_config')
    s.prompt()
    print s.before

    s.sendline('exit')
    s.logout()

Python interprets the \\1 in your replacement string as the character 0x01 (which often renders as ^A ). Python将替换字符串中的\\1解释为字符0x01(通常呈现为^A )。

Moreover, using \\1 , \\2 etc. in Perl regexes is reserved to the left hand side of the s/// operator, ie to the pattern . 此外,在Perl正则表达式中使用\\1\\2等保留在s///运算符的左侧,即保留给模式 On the right hand side (the replacement string) you should use $1 , $2 etc. instead. 在右侧(替换字符串),您应该使用$1$2等。

From the docs 来自文档

... It is at this step that \\1 is begrudgingly converted to $1 in the replacement text of s/// , in order to correct the incorrigible sed hackers who haven't picked up the saner idiom yet. ......正是在这一步, \\1s///的替换文本中不情愿地转换$1 ,以便纠正那些尚未获得成熟习惯的不可救药的黑客。 A warning is emitted if the use warnings pragma or the -w command-line flag (that is, the $^W variable) was set. 如果设置了use warnings pragma或-w命令行标志(即$^W变量),则会发出use warnings

So: 所以:

s.sendline('perl -pi.bak -e \'s/^(AllowUsers.*)/$1 boy857sr xxxxxxx/g;\' /etc/ssh/sshd_config')

should do the trick. 应该做的伎俩。


Update : Eventually I found the reference page for \\1 vs. $1 (thanks to this post ). 更新 :最终我找到了\\1$1参考页面 (感谢这篇文章 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM