【问题标题】:Why does paramiko returns \r\n as newline instead of \n?为什么 paramiko 返回 \r\n 作为换行符而不是 \n?
【发布时间】:2016-06-23 13:54:06
【问题描述】:

我正在使用一个名为“paramiko”的 python SSH 库。 它的用法是这样的:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user_name, password=password)
chan = ssh_pool[host].get_transport().open_session()
chan.exec_command(SOME_COMMAND)

因为我需要在sudo中执行一些命令,所以我需要在exec_command之前调用chan.get_pty()来确保有一个tty 可用。

我在调用 get_pty() 后发现,从远程服务器返回的标准输出使用 \r\n 作为换行符而不是 \n。

例如:

>>> chan = ssh.get_transport().open_session()
>>> chan.exec_command("echo hello world")
>>> chan.recv(1000)
b'hello world\n'

在调用 get_pty() 之后:

>>> chan = ssh.get_transport().open_session()
>>> chan.get_pty()
>>> chan.exec_command("echo hello world")
>>> chan.recv(1000)
b'hello world\r\n'

我做了一些网络搜索,但找不到任何连接到 pty / tty / newline / \r\n

我担心会导致这种变化的原因。

为什么 paramiko 返回 \r\n 作为换行符而不是 \n?

【问题讨论】:

  • 你为什么这么担心?它只是您正在运行的命令的返回值的字符串的换行符。当然,您需要以某种方式处理它,但是要么将其拆分为\n 上的列表并替换\r,要么同时替换\r 和\n:stackoverflow.com/questions/16566268/…
  • @JensHöpken 因为我正在处理一堆环境完全不同的服务器。我想只处理\r\n 和\n。但是我还是很担心,如果我不知道是什么原因造成的,总有一天会出现某种未知的问题。

标签: python paramiko openssh tty pty


【解决方案1】:

因为这是为(伪)终端翻译换行符的方式。 \r 是将光标移动到第 1 列的回车,\n 是将光标向下移动一格的换行符。

终端默认启用onlcr 转换标志。来自stty 手册页:

[-]onlcr

换行符执行回车

您还可以看到此标志已启用,即在 stty -a 的输出中前面(最后一行第 3 行)没有 -。

% stty -a
speed 38400 baud; rows 46; columns 79; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon ixoff
-iuclc -ixany -imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke

您可以使用stty -onlcr 禁用此设置,但它的存在通常不成问题;如果您怀疑某些二进制数据可能会损坏,则无论如何都不能使用 pty。


如果这只是一些单一的命令,那么通过 SSH 发送明文密码并不会增加安全性;如果现在有人可以访问您的远程帐户,他们不仅可以无限制地访问该计算机上的 root,而且还可以知道您的密码。 最好让 ssh 到 root,然后让 root 使用 "forced commands" 或 edit /etc/sudoers so that no password is required for this single command from this account 运行这 1 个命令。

【讨论】:

  • 感谢您的回答和建议!我会试试的。
猜你喜欢
  • 2012-09-05
  • 1970-01-01
  • 2010-12-20
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多