使用python的telnetlib在远程设备上执行sed命令

2024-04-23 14:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行telnetd守护进程的远程设备。我想执行一些sed命令来更新/etc/securetty文件,并通过telnet连接将pts/0, pts/1...pts/n添加到此设备上的文件。我使用telnetlib编写了以下python函数来执行sed命令:

def add_terminals(self):
    print "Adding enough terminals for telnet...."
    self.telnet.write("sed -i '/pts\/[0-9]/d' /etc/securetty")
    self.telnet.write("\n")
    time.sleep(1)
    self.telnet.write("sed -i '$a \ ' /etc/securetty")
    self.telnet.write("\n")
    time.sleep(1)
    self.telnet.write("sed -i '$a \# Local X displays added by me' /etc/securetty")
    self.telnet.write("\n")
    time.sleep(1)
    self.telnet.write("sed -i '$a pts/0\\npts/1\\npts/2\\npts/3\\npts/4\\npts/5\\npts/6\\npts/7\\npts/8\\npts/9' /etc/securetty")
    self.telnet.write("\n")
    time.sleep(1)

以上产生如下输出:

# Local X displays added by me                              
pts/0\npts/1\npts/2\npts/3\npts/4\npts/5\npts/6\npts/7\npts/8\npts/9

我想要的结果是:

# Local X displays added by me
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

我认为sed命令本身是错误的。如何获得所需的输出?你知道吗

PS:我正在使用来自yocto projectpoky linux,我的sed版本被称为This is not GNU sed version 4.0。你知道吗


Tags: 命令selfaddedbytimelocaletcsleep