繁体   English   中英

Bash + Python中的EoF / Ctrl + D命令

[英]EoF / Ctrl+D command in Bash + Python

我试图在python中做一些功能,以便可以连接到linux终端并做一些事情(例如在这种情况下,创建一个文件)。 我的代码部分起作用。 唯一不起作用的是如果您想在输入代码后做点什么。 例如,您创建文件,然后想要导航到其他地方(cd / tmp)。 无需执行下一个命令,它只会添加到创建的文件中。

    def create_file(self, name, contents, location):
        try:
            log.info("Creating a file...")
            self.device.execute("mkdir -p {}".format(location))
            self.cd_path(location)
            self.device.sendline("cat > {}".format(name))
            self.device.sendline("{}".format(contents))
            self.device.sendline("EOF")  # send the CTRL + D command to save and exit I tried here with ^D as well
        except:
            log.info("Failed to create the file!")

该文件的内容是:

cat test.txt
#!/bin/bash
echo "Fail Method Requested"
exit 1
EOF
ls -d /tmp/asdasd

执行的命令顺序为:

execute.create_file(test.txt, the_message, the_location)
execute.check_path("/tmp/adsasd") #this function just checks with ls -d if the directory exists.

我已尝试使用sendline进行以下组合: ^D, EOF, <<EOF

我不太了解如何实现这一目标。 我只想创建一个包含特定消息的文件。 (在研究如何使用VI做到这一点时,我遇到了同样的问题,但是我需要的命令是ESC的命令)

如果有人可以提供一些帮助,那就太好了!!

编辑:如下面的Rob所述,发送字符“ \\ x04”实际上有效。 对于遇到此问题的其他任何人,如果需要,也可以参考此图表以获取其他组合: http : //donsnotes.com/tech/charsets/ascii.html

您可能需要发送EOF字符,通常是CONTROL-D,而不是三个字符EOF

        self.device.sendline("\x04")

http://wiki.bash-hackers.org/syntax/redirection#here_documents

在此文档中,您可以使用任何您想代表文件结尾的文件输入终止字符串(例如您现在尝试使用的文字EOF)。 引用该字符串告诉外壳程序不要解释heredoc内容内的扩展,确保将所述内容视为文字。

在此处使用pipes.quote()可确保带有文字引号, $ s,空格或其他令人惊讶的字符的文件名不会破坏您的脚本。 (当然,您需要import pipes ;相比之下,在Python 3上,它已移至shlex.quote() )。

self.device.sendline("cat > {} <<'EOF'".format(pipes.quote(name)))

然后,您可以告诉bash将其解释为文件输入的结尾,从而按原样编写EOF。

暂无
暂无

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

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