用Popen控制腻子 [英] controlling puttygen with Popen

查看:79
本文介绍了用Popen控制腻子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python脚本来为用户生成SSH密钥.使用ssh-keygen生成它们之后,我想使用puttygen创建一个.ppk文件.不幸的是,puttygen不允许在命令行上提供密码短语-因此,我试图使用popen将它们传递到其stdin中.它总是抱怨密码短语错误",但是在命令行输入命令并在那里输入密码可以正常工作-问题出在我的popen技术上. puttygen会提示三次输入密码-一次读取openssh生成的密钥,两次提示新文件的密钥. Puttygen在第一个提示后报告一个错误,因此问题出在我试图将密码短语发送到子进程的问题.

I'm writing a python script to generate SSH keys for users. After generating them using ssh-keygen, I'd like to use puttygen to create a .ppk file. Unfortunately, puttygen doesn't allow the passphrase to be provided on the commandline - therefore I'm trying to pipe them into its stdin using popen. It always complains of a 'wrong passphrase', but entering the commands at the commandline and entering the passphrase there works fine - the problem is something in my popen technique. puttygen prompts three times for a passphrase - once to read the openssh-generated key, and twice for the key for the new file. Puttygen reports an error after the first prompt, so the problem is with my attempt to send the passphrase to the subprocess.

平台是Ubuntu 11.10,python 2.7,最新的openssh和putty-tools软件包.这是一个切碎的脚本,用于说明我遇到的问题:

The platform is Ubuntu 11.10, python 2.7, latest openssh and putty-tools packages. Here's a chopped-out script to illustrate the problem I'm having:

#!/usr/bin/python
import sys, os, subprocess

KEYGEN = "/usr/bin/ssh-keygen -t rsa -b 4096 -f id_rsa -N passphrase"
PUTTYGEN = "/usr/bin/puttygen id_rsa -P -O private -o test.ppk"
phrase = "passphrase"

try:
    os.unlink('id_rsa')
except:
    pass

try:
    os.unlink('id_rsa.pub')
except:
    pass

try:
    os.unlink('test.ppk')
except:
    pass

## generate the public and private keys
subprocess.call(KEYGEN.split(' '))

## convert key to PuTTY format
p = subprocess.Popen(PUTTYGEN.split(' '), 
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)

## Two techniques I've tried - also tried variations on CR/LF.  No luck.
if False:
    o, e = p.communicate(phrase + '\n' + phrase + '\n' + phrase + '\n')
    #o, e = p.communicate(phrase + '\r' + phrase + '\r' + phrase + '\r')
    #o, e = p.communicate(phrase + '\r\n' + phrase + '\r\n' + phrase + '\r\n')

    print o
    print e

else:
    p.stdin.write(phrase + '\n')
    p.stdin.write(phrase + '\n')
    p.stdin.write(phrase + '\n')

    print p.stdout.read()
    print p.stderr.read()
    p.stdin.close()

    p.wait()

推荐答案

似乎puttygen会读取所有三个密码短语作为第一个密码短语.最简单的解决方案是插入

It seems like puttygen reads all three passphrases as first one. The simplest solution is to insert

time.sleep(0.1) 

之间

p.stdin.write(phrase + '\n')

这篇关于用Popen控制腻子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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