python从输出中提取几行

时间:2018-07-26 17:25:39

标签: python python-3.x python-2.7

我创建了一个python类来执行curl命令,该命令反过来会生成令牌。代码按预期工作,脚本生成预期的输出,现在,从下面提到的输出中不需要几行,而不是整个输出。

如何从输出中提取以下行。

lines starting after 
Set-Cookie: SESSION=   till  =;  

。如何提取这些行。

    import requests
    import json
    from akamai.edgegrid import EdgeGridAuth, EdgeRc
    from tabulate import tabulate
    import os
    import re
    import base64

    class generate_token(object):

        """
          This library is to generate token for the test application

        """

        def __init__(self,kwargs):

            self.username     = 'user'
            self.password     = 'abcdef'
            self.contractName = kwargs.get("Names")
            self.contractType = kwargs.get("Type")
            self.accountId    = kwargs.get("Id")
            self.env          = kwargs.get("env")

        def requestSession(self):

             if self.env == "test":
               ping = os.popen('ping -c 1  hostname.com').read()
               ip_addr  = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",ping)[0]

             else:
                ping = os.popen('ping -c 1  different_hostname.com').read()
                ip_addr = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",ping)[0]

             url = "https://%s/EdgeAuth/asyncUserLogin" %(ip_addr)
             command = "curl -is -v  -k  -d username=%s -d password=%s --request POST '%s' " %(self.username,self.password,url)
             self.session = os.popen(command).read()


if __name__ == "__main__":
    initData = {
                'Names': 'names',
                'Type': 'type',
                'Id': 'ID',
                'env' : 'test'
                }

    c = generate_token(kwargs=initData)
    result = c.requestSession()

整个输出:

* TCP_NODELAY set
* WARNING: disabling hostname validation also disables SNI.
> POST /EdgeAuth/asyncUserLogin HTTP/1.1
> Host: 143.111.112.202
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 33
> Content-Type: application/x-www-form-urlencoded
>
} [33 bytes data]
* upload completely sent off: 33 out of 33 bytes
< HTTP/1.1 302 Moved Temporarily
< Date: Thu, 26 Jul 2018 15:54:07 GMT
< Server: Apache-Coyote/1.1
< Location: https://192.168.93.201/homeng/view/main
< Content-Length: 0
< Set-Cookie: SESSION=1-7FOmRFhEcci+8fAfh+DvLg==-1bk61eksykUHbWc9kx3LzL0KdkaxyDodxsEsu6siMR/1cpR7yLaD7HtTjXEr+XDowzpYcug4bfKIMjk2/T0aqJiHg5BrbRbnBeZnTcAUIpdyKGvtnmEQkSADoaxvgfYGrxqQctrVPdqJtPziqvIbjO1X8xh0Xtj/ZNvJXaSFs//w9ISNZ5hvIDBygUo+0EuYT8PSTYVPrcBCLaJUkC8ACg==-jdN937gosTsMx8fdaJqP5sA7wKPRgqv1RxRkX65SWeE=; 
Path=/; Secure
< Via: 1.1 %{HTTP_HOST}
< X-Content-Type-Options: nosniff
< Content-Type: text/plain

必需的输出:

17FOmRFhEcci+8fAfh+DvLg==-1bk61eksykUHbWc9kx3LzL0KdkaxyDodxsEsu6siMR/1cpR7yLaD7HtTjXEr+XDowzpYcug4bfKIMjk2/T0aqJiHg5BrbRbnBeZnTcAUIpdyKGvtnmEQkSADoaxvgfYGrxqQctrVPdqJtPziqvIbjO1X8xh0Xtj/ZNvJXaSFs//w9ISNZ5hvIDBygUo+0EuYT8PSTYVPrcBCLaJUkC8ACg==-jdN937gosTsMx8fdaJqP5sA7wKPRgqv1RxRkX65SWeE=;

1 个答案:

答案 0 :(得分:0)

不要使用os.popen和朋友来执行外部程序-为此,请使用subprocess模块:

ping = subprocess.check_output(['ping', '-c', '1', 'hostname.com'])

以同样的方式,不要仅仅为了从URL获取cookie而执行子进程-您已经在代码中导入了出色的requests库,为什么不使用它!

r = requests.post(url, data={'username': self.username, 'password': self.password})
print (r.cookies['SESSION'])