Argparse:如果提供了另一个参数,则绕过参数

时间:2017-04-22 08:06:14

标签: python rsa argparse

关注this post我正在创建一个小型Python脚本,可以输入公共RSA密钥并输出私有RSA密钥。

现在可以通过这种方式传递参数:

./Converter.py -input publikey.pem

这是代码:

<!-- language: lang-py -->

parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='infile', help="input a .pem file which contains pubilc key")
args = parser.parse_args()
# --- Here we search for n and e ---
PublicKey = args.infile
OpenPublicKey = open(PublicKey, 'r')
ReadPublicKey = OpenPublicKey.read()
TheKey = RSA.importKey(ReadPublicKey)
n = long(TheKey.n)
e = long(TheKey.e)
print 'This is modulus n: ', n, '\n'
print 'This is public exponent e: ', e, '\n'

我还希望脚本在没有公钥.pem文件时工作,在这种情况下,用户需要以这种方式输入ne

./Converter.py -n 7919 -e 65537

我正在使用argparse,现在基本上Python正在从n文件中提取e.pem

但我希望argparse在用户提供ne时绕过此提取

2 个答案:

答案 0 :(得分:2)

#!python2
import argparse
from Crypto.PublicKey import RSA
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)

group.add_argument('-f','--infile', help="input a .pem file which contains pubilc key")
group.add_argument('-ne',nargs=2, help="value of n and e")

args = parser.parse_args()
# --- Here we search for n and e ---
if args.infile:
    PublicKey = args.infile
    OpenPublicKey = open(PublicKey, 'r')
    ReadPublicKey = OpenPublicKey.read()
    TheKey = RSA.importKey(ReadPublicKey)
    n = long(TheKey.n)
    e = long(TheKey.e)

else:
    n,e=map(long,args.ne)
print 'This is modulus n: ', n
print 'This is public exponent e: ', e

对于文件输入:

./Converter.py -f publickey.pem

对于变量输入:

./Converter.py -ne 4 5

答案 1 :(得分:1)

只需为-n-e

添加可选的关键字参数即可
parser.add_argument('-n', type=int)
parser.add_argument('-e', type=int)

如果args.n and args.e求值为True,则忽略输入参数并跳过处理它的代码。

相关问题