V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
sandtears
V2EX  ›  Python

使用subprocess.Popen时如何正确的重定向所有输入输出?

  •  
  •   sandtears · 2013-07-31 23:34:54 +08:00 · 7124 次点击
    这是一个创建于 3923 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我使用了
    subprcess.Popen("ssh -qTfNg -D 8999 user@hostname", shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)

    但是还是没有办法得到获取到ssh命令要求password的那个提示,也没法输入密码orz,现在用pexpect模块实现了我想要的功能,但是还是很好奇为什么subprocess不可以。
    7 条回复    1970-01-01 08:00:00 +08:00
    cloverstd
        1
    cloverstd  
       2013-08-01 12:50:43 +08:00 via Android
    要用 ssh 的标准输入读取
    我之前是用 sudo,sudo 有一个参数是从标准输入读取密码
    timonwong
        2
    timonwong  
       2013-08-01 13:04:33 +08:00
    ssh命令的password输入需要一个terminal, popen是用pty.fork()实现的,挂上一个pseudo terminal获取输入。
    lenciel
        3
    lenciel  
       2013-08-01 13:48:35 +08:00
    由于安全上的考虑,ssh (还有scp, sftp)这些命令是直接和console交互的,你平时敲在terminal的password是console直接给它们而不是它们从STDIN读取。想在pipe里面传password是不行的。你实在是要做有很多办法:

    1. 用Popen发命令 echo "password" | ssh user@hostname
    2. 用paramiko
    3. 用pexpect

    1最不安全因为密码在代码里面,2最简单。
    sandtears
        4
    sandtears  
    OP
       2013-08-01 14:14:12 +08:00
    @cloverstd 3Q 等我去看看sudo的Man page
    sandtears
        5
    sandtears  
    OP
       2013-08-01 14:14:37 +08:00
    @timonwong 结合3楼的差不多理解原理了,多谢回复
    sandtears
        6
    sandtears  
    OP
       2013-08-01 14:14:50 +08:00
    @lenciel 嗯嗯,谢谢我回去看看
    sandtears
        7
    sandtears  
    OP
       2013-08-01 14:21:13 +08:00
    @lenciel 第一个似乎也是无效的,第二三个可用,多谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5354 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 07:11 · PVG 15:11 · LAX 00:11 · JFK 03:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.