使用空格分隔符连接输出中的每两行,并在python3中格式化输出

时间:2018-01-17 07:44:40

标签: python-3.x

我创建了一个脚本,用于从Directory manger LDAP ldapsearch命令中提取数据,以获取useruser manger name进行某些验证。作为一个新手学习者,我在python3中编写了以下代码,其中包含数据,基本上是用户和用户管理员的名字:

#!/usr/bin/python3
##  script Name: getUserinfo.py
import subprocess
from subprocess import call

# Authentication
'''ldap_dn = "cn=directory manager"
ldap_pwd = ""
ldap_server = "its3.rraka.com"
ldap_base = "ou=people,o=rraka.com"
ldap_user_file = "uid.txt"' '''

def CheckID(user):
  call("ldapsearch -h server1 -D 'cn=directory manager' -w mypass123 -LLLb 'ou=people,o=rraka.com' managerlogin uid=" + user , shell=True)

def UidCheck():
  with open( '/home/karn/uid.txt', mode='rt', encoding='utf-8' ) as f:
    for line in f.readlines() :
      return CheckID(line)

if __name__ == '__main__':
    UidCheck()

我的上面的脚本返回如下结果,这是我想要的好数据,但是需要解析这些数据以便更具可读性,比如打印用户和用户管理器。

# ./getUserinfo.py

dn: uid=cecile,ou=people,o=rraka.com
managerlogin: simonk

dn: uid=richardb,ou=people,o=rraka.com
managerlogin: hxl

dn: uid=wwoo,ou=people,o=rraka.com
managerlogin: mstanton

dn: uid=ski,ou=people,o=rraka.com
    managerlogin: fkahn

------------ further ouput turnicated deliberately ----------
  

预期的输出将是:

User ID         Manger ID
--------------------------------
cecile          simonk
richardb        hxl

2 个答案:

答案 0 :(得分:1)

首先,您希望将ldapsearch命令的输出保存到变量并将字符串解析为数据结构。 Dictionary是个不错的选择。解析可以用粗略的方式完成

def checkID(user):
    proc = subprocess.Popen("ldapsearch -h server1 -D 'cn=directory manager' -w mypass123 -LLLb 'ou=people,o=rraka.com' managerlogin uid=" + user, shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    #parsing phase
    split_str = info_str.split()
    return {'uid': split_str[1].split(',')[0].split('=')[1],
         'manager': split_str[-1]}

稍微修改您的代码以使用list comprehension我们会得到一个词典列表。

def UidCheck():
  with open( '/home/karn/uid.txt', mode='rt', encoding='utf-8' ) as f:
    return [checkID(line) for line in f.readlines()]

在主函数中,您以所需的格式编写该字典。

from io import StringIO
from csv import DictWriter

if __name__ = '__main__':
    fileobj = StringIO()
    writer = DictWriter(fileobj, fieldnames=['uid', 'manager'], delimiter='\t')
    writer.writeheader()
    writer.writerows(UidCheck())
    print(fileobj.getvalue())

或者如果您喜欢文件

with open('/path/to/a/file.csv', mode='w') as outfile:
    writer = DictWriter(outfile, fieldnames=['uid', 'manager'], delimiter='\t')
    writer.writeheader()
    writer.writerows(UidCheck())

答案 1 :(得分:1)

经过一些修改后我得到了代码,并且@kaidokuuppa为使用Dictionary和数据解析的想法提供了很大的帮助。

这是工作代码段..

#!/usr/bin/python3
##  script Name: getUserinfo.py
import subprocess
from subprocess import call

def CheckUid(user):    
    proc = subprocess.Popen("ldapsearch -h server1 -D 'cn=directory manager' -w mypass123 -LLLb 'ou=people,o=rraka.com'  'uid=%s' managerlogin" % (user), shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    split_str = info_str.split()
    print({'UserID': split_str[1].split(',')[0].split('=')[1], 'MangerID': split_str[-1]})

def CallUid():
    with open('uid.txt', mode='rt', encoding='utf-8') as f:
       for line in f.readlines():
         CheckUid(line)

if __name__ == '__main__':
    CallUid()
  

现在结果产生为:

# ./getUserinfo.py
    {'UserID': 'amitnegi', 'MangerID': 'suhas'}
    {'UserID': 'anagpal', 'MangerID': 'benjamin'}
    {'UserID': 'bharattp', 'MangerID': 'fkahn'}
    {'UserID': 'bhavin', 'MangerID': 'mbao'}