"\r" 是什么意思?在下面的脚本中做什么? [英] What does "\r" do in the following script?

查看:149
本文介绍了"\r" 是什么意思?在下面的脚本中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本通过 Telnet 重新启动我的路由器:

#!/usr/bin/env python导入操作系统导入 telnetlib从时间导入睡眠主机 = "192.168.1.1"用户 = "用户"密码 = "密码"cmd = "系统重启"tn = telnetlib.Telnet(主机)睡觉(1)tn.read_until("登录:")tn.write(用户 + "\n\r")睡觉(1)tn.read_until("密码:")tn.write(密码 + "\n\r")睡觉(1)tn.write(cmd + "\n\r")

我不知道为什么但是从上面的代码中删除\r"会使脚本无法工作.那么\r"在这个脚本中的作用是什么,一般什么时候使用\r"?

注意:我知道回车",但仍然无法弄清楚它在我的脚本中的用途.我在 Linux 中运行这个脚本.

解决方案

'\r' 字符是回车符,在网络中换行需要回车-换行符对虚拟终端会话.

<小时>

来自旧的 telnet 规范 (RFC 854)(第 11 页):

<块引用>

定义的序列CR LF"将导致 NVT位于下一个打印行的左边距(就像,例如,序列LF CR").

但是,来自最新规范 (RFC5198)(第 13 页):

<块引用>

  1. ...

  2. 在 Net-ASCII 中,CR 不得出现,除非紧随其后通过 NUL 或 LF,后者 (CR LF) 指定新line" 函数.今天和如上所述,CR 应该一般只出现在后面跟着 LF 的时候.因为页面布局用其他方式更好,因为 NUL 有一个特殊的某些编程语言中的解释,并避免其他类型的混淆,最好避免 CR NUL,因为如上所述.

  3. LF CR 不应出现,除非作为多个 CR LF 的副作用序列(例如,CR LF CR LF).

所以 Telnet 中的换行符应该总是 '\r\n' 但大多数实现要么没有更新,要么保留旧的 '\n\r'向后兼容.

I am using following script to reboot my router using Telnet:

#!/usr/bin/env python

import os
import telnetlib
from time import sleep

host = "192.168.1.1"
user = "USER"
password = "PASSWORD"
cmd = "system restart"

tn = telnetlib.Telnet(host)
sleep(1)

tn.read_until("Login: ")
tn.write(user + "\n\r")
sleep(1)

tn.read_until("Password: ")
tn.write(password + "\n\r")
sleep(1)

tn.write(cmd + "\n\r")

I don't know why but removing "\r" from above code make the script non-working. So what does "\r" do in this script and when to use "\r" in general?

Note: I know about "Carriage Return" but still could not figure out its use in my script. I am running this script in Linux.

解决方案

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.

这篇关于"\r" 是什么意思?在下面的脚本中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆