3

让ssh从stdin读取密码

 1 year ago
source link: https://www.lujun9972.win/blog/2016/11/15/%E8%AE%A9ssh%E4%BB%8Estdin%E8%AF%BB%E5%8F%96%E5%AF%86%E7%A0%81/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

让ssh从stdin读取密码

执行像ssh,scp这类secure command时,必须手工输入密码,而且它们是直接从/dev/tty而不是stdin中读取密码的,这也意味着无法通过重定向IO的方式传送密码給这些程序.

查了一下网上一般的解决方案是借助 paramikopexpect 这两个第三方库来解决的.

但安装第三方库对于不能随意访问互联网的环境来说是很麻烦的一件事情.

其实就这个应用场景来说,完全没必要用到第三方库. python自带一个名为 pty 的modual,它有一个 spawn 函数,manual中对它的描述是:

pty.spawn(argv[, master_read[, stdin_read]])

Spawn a process, and connect its controlling terminal with the current process’s standard io. This is often used to baffle programs which insist on reading from the controlling terminal.

这就好办了,我们只要创建一个名为”pty-process.py”脚本,在这个脚本中用pty.spawn调用secure command,然后再通过写入该脚本stdin的方式就可以变相地給这些secure command发送密码了.

pty-process.py脚本的实现如下:

#!/bin/env python3
import pty
import sys

pty.spawn(sys.argv[1:])

借助于这个pty-process.py我们可以这样执行secure command了

echo $passwd |pty-process.py ssh [email protected]$remote $command

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK